From 82fcbbe2807764a5c4fad26893327358ce4fd3c9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 01:50:16 +0100 Subject: [PATCH 001/136] feat(platform): add a database provisioning crate and the PostgreSQL 17 floor Products and rstack dev each spell the roles, grants and schema a runtime needs. registry-platform-provision builds that plan once, as reviewed SQL, and converges a server towards it without altering existing objects. The maintained floor, PostgreSQL 17, is exported from registry-platform-activation so the provisioner and the activation checks refuse the same servers. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 1 + Cargo.lock | 16 + Cargo.toml | 2 + crates/registry-platform-activation/README.md | 6 +- .../registry-platform-activation/src/lib.rs | 17 +- crates/registry-platform-provision/Cargo.toml | 39 + crates/registry-platform-provision/README.md | 30 + .../registry-platform-provision/src/admin.rs | 448 ++++++ .../src/execute.rs | 553 +++++++ crates/registry-platform-provision/src/lib.rs | 28 + .../registry-platform-provision/src/plan.rs | 871 +++++++++++ crates/registry-platform-provision/src/sql.rs | 172 +++ .../tests/postgres.rs | 1332 +++++++++++++++++ 13 files changed, 3513 insertions(+), 2 deletions(-) create mode 100644 crates/registry-platform-provision/Cargo.toml create mode 100644 crates/registry-platform-provision/README.md create mode 100644 crates/registry-platform-provision/src/admin.rs create mode 100644 crates/registry-platform-provision/src/execute.rs create mode 100644 crates/registry-platform-provision/src/lib.rs create mode 100644 crates/registry-platform-provision/src/plan.rs create mode 100644 crates/registry-platform-provision/src/sql.rs create mode 100644 crates/registry-platform-provision/tests/postgres.rs diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index ae2711ffcf..4914488620 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -39,6 +39,7 @@ "registry-platform-metrics", "registry-platform-objectstore", "registry-platform-oidc", + "registry-platform-provision", "registry-platform-ratelimit", "registry-platform-resilience", "registry-platform-script", diff --git a/Cargo.lock b/Cargo.lock index f6c815cd09..ca975408f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8027,6 +8027,22 @@ dependencies = [ "uuid", ] +[[package]] +name = "registry-platform-provision" +version = "0.49.0" +dependencies = [ + "getrandom 0.4.3", + "postgres-protocol", + "registry-platform-activation", + "rustls", + "thiserror 2.0.21", + "tokio", + "tokio-postgres", + "tokio-postgres-rustls", + "url", + "zeroize", +] + [[package]] name = "registry-platform-ratelimit" version = "0.49.0" diff --git a/Cargo.toml b/Cargo.toml index 8be5c1b7cf..f24ac1733a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,6 +52,7 @@ members = [ "crates/registry-platform-metrics", "crates/registry-platform-objectstore", "crates/registry-platform-oidc", + "crates/registry-platform-provision", "crates/registry-platform-ratelimit", "crates/registry-platform-resilience", "crates/registry-platform-script", @@ -206,6 +207,7 @@ registry-platform-httputil = { path = "crates/registry-platform-httputil", versi registry-platform-metrics = { path = "crates/registry-platform-metrics", version = "0.49.0" } registry-platform-objectstore = { path = "crates/registry-platform-objectstore", version = "0.49.0" } registry-platform-oidc = { path = "crates/registry-platform-oidc", version = "0.49.0" } +registry-platform-provision = { path = "crates/registry-platform-provision", version = "0.49.0" } registry-platform-ratelimit = { path = "crates/registry-platform-ratelimit", version = "0.49.0" } registry-platform-resilience = { path = "crates/registry-platform-resilience", version = "0.49.0" } registry-platform-script = { path = "crates/registry-platform-script", version = "0.49.0" } diff --git a/crates/registry-platform-activation/README.md b/crates/registry-platform-activation/README.md index ed8a9fdab1..41c607242a 100644 --- a/crates/registry-platform-activation/README.md +++ b/crates/registry-platform-activation/README.md @@ -3,7 +3,11 @@ `registry-platform-activation` is the single PostgreSQL implementation of the package activation ledger and its runtime-role boundary for the stateful Registry Stack products. Activation and runtime checks require PostgreSQL 17 -or newer, matching the maintained database support floor. +or newer, matching the maintained database support floor. The crate exports +the floor as `MINIMUM_SERVER_VERSION_NUM` (`170_000`). The one technical +reason found for it is BReg's: its closed-catalog check expects every managed +table to grant the `MAINTAIN` privilege, which PostgreSQL introduced in +version 17 (`registry-breg/src/postgres/schema.rs`). The crate owns the product-neutral parts of activation: ledger reads and appends, deployment database identity checks, active-package startup checks, diff --git a/crates/registry-platform-activation/src/lib.rs b/crates/registry-platform-activation/src/lib.rs index 2c47cab6e3..acbf1a587e 100644 --- a/crates/registry-platform-activation/src/lib.rs +++ b/crates/registry-platform-activation/src/lib.rs @@ -280,8 +280,18 @@ pub async fn relation_exists(client: &impl GenericClient, relation: &str) -> Res Ok(row.get(1)) } +/// Lowest `server_version_num` every Registry Stack product that uses this +/// ledger accepts (PostgreSQL 17). +/// +/// The recorded reason is the maintained database support floor +/// (`README.md`). The one technical reason found is BReg's: its closed-catalog +/// check expects every managed table to grant the MAINTAIN privilege, which +/// PostgreSQL introduced in version 17 +/// (`registry-breg/src/postgres/schema.rs`, `MIN_POSTGRES_VERSION_NUM`). +pub const MINIMUM_SERVER_VERSION_NUM: i32 = 170_000; + fn verify_postgres_version(version_num: i32) -> Result<(), Error> { - if version_num < 170_000 { + if version_num < MINIMUM_SERVER_VERSION_NUM { return Err(Error::UnsupportedPostgres); } Ok(()) @@ -1019,6 +1029,11 @@ mod tests { } } + #[test] + fn postgres_floor_constant_is_version_17() { + assert_eq!(MINIMUM_SERVER_VERSION_NUM, 170_000); + } + #[test] fn layouts_accept_only_unquoted_postgres_identifiers() { assert!(Layout::new( diff --git a/crates/registry-platform-provision/Cargo.toml b/crates/registry-platform-provision/Cargo.toml new file mode 100644 index 0000000000..1daa1c7cb5 --- /dev/null +++ b/crates/registry-platform-provision/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "registry-platform-provision" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Product-free PostgreSQL provisioning plans: roles, database, schemas and extensions for Registry Stack runtimes." +repository.workspace = true +publish = false + +[lints] +workspace = true + +[features] +default = [] +# Runs tests/postgres.rs against the disposable PostgreSQL superuser named by +# PROVISION_TEST_DATABASE_URL, over TLS verified with PROVISION_TEST_DATABASE_CA. +# It also needs PROVISION_TEST_OLD_DATABASE_URL, a server older than the floor. +# With the feature on, a missing variable fails the suite. +postgres-test = [] + +[[test]] +name = "postgres" +required-features = ["postgres-test"] + +[dependencies] +postgres-protocol.workspace = true +registry-platform-activation.workspace = true +rustls.workspace = true +thiserror.workspace = true +tokio = { workspace = true, features = ["rt", "time"] } +tokio-postgres.workspace = true +tokio-postgres-rustls.workspace = true +url.workspace = true +zeroize.workspace = true + +[dev-dependencies] +getrandom.workspace = true +tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } diff --git a/crates/registry-platform-provision/README.md b/crates/registry-platform-provision/README.md new file mode 100644 index 0000000000..bbacf1703c --- /dev/null +++ b/crates/registry-platform-provision/README.md @@ -0,0 +1,30 @@ +# Registry Platform Provision + +`registry-platform-provision` turns what a product needs from an empty +PostgreSQL server into an ordered plan of statements: the migration and runtime +login roles, an isolated database that is closed to `PUBLIC`, the schema layout +the product's migrations expect, and the optional `btree_gist` and PostGIS +extensions. + +A product describes itself as data (`ProductDatabase`) and names its roles and +database (`ProvisionTarget`). The crate carries no product, schema or role +name. + +- `plan` builds the statements. A statement with a `Probe` runs only when its + object is absent. A grant, revoke or connection switch has no probe and is + safe to run again. A single-role target (one name for both roles) plans one + role. +- `render_script` prints the plan for an administrator to review and run with + `psql`. The script holds no password and no password verifier: each login + role is followed by a `\password` line, and a statement that needs a + superuser is marked. +- `verify_server_version` refuses a server below the shared PostgreSQL floor, + `registry_platform_activation::MINIMUM_SERVER_VERSION_NUM`. +- `sql` holds the statement builders and the identifier and literal quoting. + +Passwords enter only through `RoleCredential`, whose `Debug` prints the name. +The executable text of a role statement carries a SCRAM-SHA-256 verifier +computed in the client, never the password. No API in this crate prints, +formats or logs a secret. + +This crate builds plans only. It opens no connection. diff --git a/crates/registry-platform-provision/src/admin.rs b/crates/registry-platform-provision/src/admin.rs new file mode 100644 index 0000000000..3f953368db --- /dev/null +++ b/crates/registry-platform-provision/src/admin.rs @@ -0,0 +1,448 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The administrator connection: URL rules, verified TLS and bounded sessions. +//! +//! Nothing in this module echoes the URL, the password or a driver message +//! into an error. Errors name the rule that failed or the SQLSTATE. + +use std::{future::Future, str::FromStr, time::Duration}; + +use rustls::pki_types::{pem::PemObject as _, CertificateDer}; +use tokio_postgres::{ + config::{Host, SslMode}, + Client, Config, +}; +use tokio_postgres_rustls::MakeRustlsConnect; +use url::Url; + +pub(crate) const CONNECTION_TIMEOUT: Duration = Duration::from_secs(10); +pub(crate) const STATEMENT_TIMEOUT: Duration = Duration::from_secs(10); +pub(crate) const OPERATION_TIMEOUT: Duration = Duration::from_secs(15); +const KEEPALIVE_IDLE: Duration = Duration::from_secs(30); +const DEFAULT_PORT: u16 = 5432; + +/// A validated administrator endpoint with its TLS settings. `Debug` prints +/// the host, port, user and database only. +#[derive(Clone)] +pub struct AdminConfig { + config: Config, + tls: MakeRustlsConnect, + host: String, + port: u16, +} + +/// Why an administrator URL or CA file was refused. Each message names the +/// rule, never the URL. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum AdminConfigError { + #[error("the PostgreSQL admin URL is not a parseable URL")] + NotParseable, + #[error("the PostgreSQL admin URL must be an absolute postgres:// or postgresql:// URL")] + NotAPostgresUrl, + #[error("the PostgreSQL admin URL must include an explicit host, user, and password")] + MissingEndpointOrCredentials, + #[error("the PostgreSQL admin URL must include one explicit database name")] + MissingDatabase, + #[error("the PostgreSQL admin URL must not override its endpoint or credentials in the query")] + QueryOverridesEndpoint, + #[error( + "the PostgreSQL admin URL sslmode must be require, verify-ca, or verify-full; \ + provisioning always uses verified TLS" + )] + UnsupportedSslMode, + #[error("the PostgreSQL admin URL must not set sslrootcert; pass the CA PEM file instead")] + SslRootCertInUrl, + #[error( + "the PostgreSQL admin URL has a query parameter that is not supported; \ + only connect_timeout and application_name are" + )] + UnsupportedQueryParameter, + #[error("the PostgreSQL admin URL has an invalid query parameter value")] + InvalidQueryValue, + #[error("the PostgreSQL admin URL must name one TCP host, user, password, and database")] + NotOneTcpEndpoint, + #[error("the PostgreSQL CA PEM is invalid or holds no certificate")] + CaInvalid, + #[error("cannot initialize the PostgreSQL TLS provider")] + TlsProvider, + #[error("cannot load native roots for PostgreSQL TLS")] + NativeRoots, +} + +impl AdminConfigError { + /// The diagnostic code of the report. + pub fn code(&self) -> &'static str { + match self { + Self::CaInvalid | Self::TlsProvider | Self::NativeRoots => { + "platform.provision.admin-ca-invalid" + } + _ => "platform.provision.admin-url-invalid", + } + } +} + +/// Validates an administrator URL and builds its verified-TLS settings. +/// +/// With `ca_pem`, the server certificate must chain to it. Without, the +/// platform's native roots are used. The connection always requires TLS. +pub fn admin_config(url: &str, ca_pem: Option<&[u8]>) -> Result { + let parsed = Url::parse(url).map_err(|_| AdminConfigError::NotParseable)?; + if !matches!(parsed.scheme(), "postgres" | "postgresql") + || parsed.cannot_be_a_base() + || parsed.fragment().is_some() + { + return Err(AdminConfigError::NotAPostgresUrl); + } + if parsed.username().is_empty() + || parsed.password().is_none_or(str::is_empty) + || parsed.host().is_none() + { + return Err(AdminConfigError::MissingEndpointOrCredentials); + } + let database = parsed.path().strip_prefix('/').unwrap_or_default(); + if database.is_empty() || database.contains('/') { + return Err(AdminConfigError::MissingDatabase); + } + if parsed.query_pairs().any(|(key, _)| { + matches!( + key.as_ref(), + "host" | "hostaddr" | "port" | "user" | "password" | "dbname" + ) + }) { + return Err(AdminConfigError::QueryOverridesEndpoint); + } + for (key, value) in parsed.query_pairs() { + match key.as_ref() { + "sslmode" => { + if !matches!(value.as_ref(), "require" | "verify-ca" | "verify-full") { + return Err(AdminConfigError::UnsupportedSslMode); + } + } + "sslrootcert" => return Err(AdminConfigError::SslRootCertInUrl), + "connect_timeout" | "application_name" => {} + _ => return Err(AdminConfigError::UnsupportedQueryParameter), + } + } + + // tokio-postgres does not parse verify-ca or verify-full, and provisioning + // sets its own TLS mode, so the checked sslmode is not passed on. + let mut sanitized = parsed.clone(); + let kept: Vec<(String, String)> = parsed + .query_pairs() + .filter(|(key, _)| key != "sslmode") + .map(|(key, value)| (key.into_owned(), value.into_owned())) + .collect(); + if kept.is_empty() { + sanitized.set_query(None); + } else { + sanitized.query_pairs_mut().clear().extend_pairs(kept); + } + let mut config = + Config::from_str(sanitized.as_str()).map_err(|_| AdminConfigError::InvalidQueryValue)?; + config.keepalives_idle(KEEPALIVE_IDLE); + config.ssl_mode(SslMode::Require); + if config.get_hosts().len() != 1 + || !matches!(config.get_hosts().first(), Some(Host::Tcp(_))) + || !config.get_hostaddrs().is_empty() + || config.get_user().is_none_or(str::is_empty) + || config.get_password().is_none_or(<[u8]>::is_empty) + || config.get_dbname().is_none_or(str::is_empty) + { + return Err(AdminConfigError::NotOneTcpEndpoint); + } + apply_session_options(&mut config); + + let host = match config.get_hosts().first() { + Some(Host::Tcp(host)) => host.clone(), + _ => return Err(AdminConfigError::NotOneTcpEndpoint), + }; + let port = config.get_ports().first().copied().unwrap_or(DEFAULT_PORT); + Ok(AdminConfig { + config, + tls: tls_connector(ca_pem)?, + host, + port, + }) +} + +impl AdminConfig { + pub fn host(&self) -> &str { + &self.host + } + + pub fn port(&self) -> u16 { + self.port + } + + pub fn user(&self) -> &str { + self.config.get_user().unwrap_or_default() + } + + /// The database the administrator URL names. + pub fn database(&self) -> &str { + self.config.get_dbname().unwrap_or_default() + } + + /// Opens a session to `database` as the administrator. + pub(crate) async fn connect(&self, database: Option<&str>) -> Result { + let mut config = self.config.clone(); + if let Some(database) = database { + config.dbname(database); + } + Session::open(&config, &self.tls).await + } + + /// Opens a session to `database` as another role, over the same endpoint. + pub(crate) async fn connect_as( + &self, + database: &str, + role: &str, + password: &str, + ) -> Result { + let mut config = self.config.clone(); + config.dbname(database).user(role).password(password); + Session::open(&config, &self.tls).await + } +} + +impl std::fmt::Debug for AdminConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AdminConfig") + .field("host", &self.host) + .field("port", &self.port) + .field("user", &self.user()) + .field("database", &self.database()) + .finish_non_exhaustive() + } +} + +/// Startup options for every administrator session: the statement deadline and +/// the CREATEROLE self-grant. The comma in the self-grant value is not a +/// separator for the server's startup option parser, which splits on spaces. +fn apply_session_options(config: &mut Config) { + let added = format!( + "-c statement_timeout={} -c createrole_self_grant={}", + STATEMENT_TIMEOUT.as_millis(), + crate::sql::CREATEROLE_SELF_GRANT + ); + if let Some(existing) = config.get_options().filter(|value| !value.is_empty()) { + config.options(format!("{existing} {added}")); + } else { + config.options(added); + } +} + +fn tls_connector(ca_pem: Option<&[u8]>) -> Result { + let provider = rustls::crypto::ring::default_provider(); + if provider.install_default().is_err() + && rustls::crypto::CryptoProvider::get_default().is_none() + { + return Err(AdminConfigError::TlsProvider); + } + + if let Some(pem) = ca_pem { + let mut roots = rustls::RootCertStore::empty(); + let mut count = 0usize; + for certificate in CertificateDer::pem_slice_iter(pem) { + let certificate = certificate.map_err(|_| AdminConfigError::CaInvalid)?; + roots + .add(certificate) + .map_err(|_| AdminConfigError::CaInvalid)?; + count += 1; + } + if count == 0 { + return Err(AdminConfigError::CaInvalid); + } + let config = rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(); + Ok(MakeRustlsConnect::new(config)) + } else { + MakeRustlsConnect::with_native_certs() + .map(|value| value.0) + .map_err(|_| AdminConfigError::NativeRoots) + } +} + +/// Why a session could not be opened. Carries the SQLSTATE when the server +/// answered, never the driver's message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ConnectFailure { + pub sqlstate: Option, +} + +/// One open session. Dropping it ends the connection task. +pub(crate) struct Session { + pub client: Client, + task: tokio::task::JoinHandle>, +} + +impl Session { + async fn open(config: &Config, tls: &MakeRustlsConnect) -> Result { + let attempt = tokio::time::timeout(CONNECTION_TIMEOUT, config.connect(tls.clone())).await; + match attempt { + Ok(Ok((client, connection))) => Ok(Self { + client, + task: tokio::spawn(connection), + }), + Ok(Err(error)) => Err(ConnectFailure { + sqlstate: error.code().map(|code| code.code().to_owned()), + }), + Err(_) => Err(ConnectFailure { sqlstate: None }), + } + } +} + +impl Drop for Session { + fn drop(&mut self) { + self.task.abort(); + } +} + +/// How one database call ended, without the driver's message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum CallFailure { + /// The server answered with this SQLSTATE. + Server { sqlstate: String }, + /// The deadline passed or the connection broke: whether the server + /// applied the call is unknown. + Unconfirmed, +} + +impl CallFailure { + pub(crate) fn lacks_privilege(&self) -> bool { + matches!(self, Self::Server { sqlstate } if sqlstate == "42501") + } +} + +pub(crate) async fn bounded_call( + future: impl Future>, +) -> Result { + match tokio::time::timeout(OPERATION_TIMEOUT, future).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(error)) => Err(match error.as_db_error() { + Some(db) => CallFailure::Server { + sqlstate: db.code().code().to_owned(), + }, + None => CallFailure::Unconfirmed, + }), + Err(_) => Err(CallFailure::Unconfirmed), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const URL: &str = "postgresql://admin:secret-pw@db.example:5433/postgres"; + + /// A throwaway self-signed CA certificate. Only its structure matters here. + fn test_ca_pem() -> &'static str { + "-----BEGIN CERTIFICATE-----\n\ + MIIDGzCCAgOgAwIBAgIUXGhkX0Z058UoUVAxJidqxKazAaQwDQYJKoZIhvcNAQEL\n\ + BQAwHTEbMBkGA1UEAwwSbTMtczIgdGhyb3dhd2F5IENBMB4XDTI2MTEyNzAwMzA1\n\ + NVoXDTI2MTEyOTAwMzA1NVowHTEbMBkGA1UEAwwSbTMtczIgdGhyb3dhd2F5IENB\n\ + MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsKgPCAb1XWG8zeCpVIrg\n\ + IkAHtIqq7KlkqgGhTDBLTwFMoyBlnHUT+3qd87+0scqpv0IJA38DthaVVOo3UUkg\n\ + pPUBZySYSljOAfkDvBdJ3ev40Ww8uFl9br/XlWrrskfwC1HAjswdAzRUMSqnV/wH\n\ + In5Sb++75rnZbfUUYBbHcvT2MLlULWX98wDFGQXbEMvWbPsDlzFmYga3K98XUQDr\n\ + clbDEFACakpK2SpKFPS2azvfnRehN28eOauBlRbRHnZcS1gLDeqmnRviJoYsoOvE\n\ + tYIMN+YZCaSNZUpuD7bN1iHGOeTBDatT7ZSwArKDBV0yJHbhi/6nfPka/M3e8b1/\n\ + xQIDAQABo1MwUTAdBgNVHQ4EFgQUeaMUxXla07H5aYfj7dYnVJlTKHYwHwYDVR0j\n\ + BBgwFoAUeaMUxXla07H5aYfj7dYnVJlTKHYwDwYDVR0TAQH/BAUwAwEB/zANBgkq\n\ + hkiG9w0BAQsFAAOCAQEACC7s1MOYnU7322I3dvweCuwJvZ7a1T6KO0GyaMsw1uZZ\n\ + 2vvaTrJgQBDi5n4/pNOgx9ZzQxyBQR7QvVEV/z20x/gVOH1uQq9gQnMGAA+rFdHR\n\ + LgoNLe1zY6THUkD4l+KWQgraUKtAf0Ko1ruLrrMbH4tq3w6bJX7KeHrWsKDY04/d\n\ + /HyACVlWnoGeuyPppd6009SuMwQvKMUDz+UU55Jj49FLHWAH9V9AbuLmHkbdKQ1x\n\ + qE5kizB4UytufC/y99522L3p2bD0pAvHSxDIXYtAlC3Fx4XyFbT+5/JY3hYRwbfs\n\ + 6NlpU4TdevxbiVlIM5anyYHY+yhBKdIQH1D+0lOfvw==\n\ + -----END CERTIFICATE-----\n" + } + + fn refused(url: &str) -> AdminConfigError { + admin_config(url, Some(b"")).expect_err("the URL should be refused") + } + + #[test] + fn url_rules_are_named_and_never_echo_the_url() { + let cases: [(&str, AdminConfigError); 9] = [ + ("not a url", AdminConfigError::NotParseable), + ("mysql://a:b@h/db", AdminConfigError::NotAPostgresUrl), + ( + "postgresql://h/db", + AdminConfigError::MissingEndpointOrCredentials, + ), + ( + "postgresql://a:secret-pw@h/", + AdminConfigError::MissingDatabase, + ), + ( + "postgresql://a:secret-pw@h/db?port=1", + AdminConfigError::QueryOverridesEndpoint, + ), + ( + "postgresql://a:secret-pw@h/db?sslmode=disable", + AdminConfigError::UnsupportedSslMode, + ), + ( + "postgresql://a:secret-pw@h/db?sslrootcert=/x", + AdminConfigError::SslRootCertInUrl, + ), + ( + "postgresql://a:secret-pw@h/db?options=x", + AdminConfigError::UnsupportedQueryParameter, + ), + ( + "postgresql://a:secret-pw@h/db?connect_timeout=soon", + AdminConfigError::InvalidQueryValue, + ), + ]; + for (url, expected) in cases { + let error = refused(url); + // The CA is checked after the URL, so a URL rule is what fires first. + assert_eq!(error, expected, "{url}"); + assert_eq!(error.code(), "platform.provision.admin-url-invalid"); + assert!(!error.to_string().contains("secret-pw")); + assert!(!format!("{error:?}").contains("secret-pw")); + } + } + + #[test] + fn a_ca_without_certificates_is_refused_with_its_own_code() { + let error = admin_config(URL, Some(b"")).unwrap_err(); + assert_eq!(error, AdminConfigError::CaInvalid); + assert_eq!(error.code(), "platform.provision.admin-ca-invalid"); + let error = admin_config(URL, Some(b"not a certificate")).unwrap_err(); + assert_eq!(error, AdminConfigError::CaInvalid); + } + + #[test] + fn debug_prints_the_endpoint_and_no_password() { + let ca = test_ca_pem(); + let config = admin_config(URL, Some(ca.as_bytes())).expect("valid administrator URL"); + let printed = format!("{config:?}"); + assert!(printed.contains("db.example")); + assert!(printed.contains("5433")); + assert!(!printed.contains("secret-pw")); + assert_eq!(config.host(), "db.example"); + assert_eq!(config.port(), 5433); + assert_eq!(config.user(), "admin"); + assert_eq!(config.database(), "postgres"); + } + + #[test] + fn session_options_carry_the_deadline_and_the_self_grant() { + let ca = test_ca_pem(); + let config = admin_config(URL, Some(ca.as_bytes())).expect("valid administrator URL"); + let options = config.config.get_options().expect("options are set"); + assert!(options.contains("statement_timeout=10000")); + assert!(options.contains("createrole_self_grant=set,inherit")); + } + + #[test] + fn the_port_defaults_to_5432() { + let ca = test_ca_pem(); + let config = admin_config("postgresql://a:secret-pw@h/db", Some(ca.as_bytes())) + .expect("valid administrator URL"); + assert_eq!(config.port(), 5432); + } +} diff --git a/crates/registry-platform-provision/src/execute.rs b/crates/registry-platform-provision/src/execute.rs new file mode 100644 index 0000000000..150fd48239 --- /dev/null +++ b/crates/registry-platform-provision/src/execute.rs @@ -0,0 +1,553 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runs a [`Plan`] against a server as an administrator. +//! +//! Every statement runs on its own, so a refusal names exactly one step. No +//! error carries statement text, a URL, a password, a verifier or a driver +//! message: errors name the step, the object and the SQLSTATE. + +use std::fmt; + +use crate::{ + admin::{bounded_call, AdminConfig, CallFailure, ConnectFailure, Session}, + plan::{verify_server_version, Needs, Plan, Probe, ProvisionTarget, Scope, Statement}, +}; + +/// How [`execute`] treats objects that already exist. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + /// Probe the catalog first, create only what is absent, and refuse what + /// exists in a different shape. Every `*ctl provision` uses this. + Converge, + /// The server is known to be empty: no floor check and no probes. + Fresh, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StatementOutcome { + /// The statement ran and its object did not exist before. + Created, + /// The object already existed in the expected shape, so nothing ran. + Present, + /// A grant, revoke or connection setting ran. It is a no-op when it + /// already held. + Applied, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Outcome { + /// One entry per planned statement, in plan order. + pub statements: Vec<(&'static str, StatementOutcome)>, + pub single_role: bool, +} + +/// Why provisioning stopped. `code` is the diagnostic code of the report. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProvisionError { + AdminConnectFailed { + sqlstate: Option, + }, + UnsupportedPostgres, + StatementNeedsPrivilege { + step: &'static str, + needs: Needs, + scope: Scope, + database: String, + }, + RoleAttributesDiffer { + step: &'static str, + role: String, + }, + DatabaseOwnerDiffers { + database: String, + }, + SchemaOwnerDiffers { + step: &'static str, + schema: String, + database: String, + }, + ExtensionTooOld { + step: &'static str, + extension: String, + }, + RoleLoginFailed { + role: String, + }, + EffectUnconfirmed { + step: &'static str, + }, + StatementFailed { + step: &'static str, + sqlstate: String, + }, +} + +impl ProvisionError { + pub fn code(&self) -> &'static str { + match self { + Self::AdminConnectFailed { .. } => "platform.provision.admin-connect-failed", + Self::UnsupportedPostgres => "platform.provision.unsupported-postgres", + Self::StatementNeedsPrivilege { .. } => "platform.provision.statement-needs-privilege", + Self::RoleAttributesDiffer { .. } => "platform.provision.role-attributes-differ", + Self::DatabaseOwnerDiffers { .. } => "platform.provision.database-owner-differs", + Self::SchemaOwnerDiffers { .. } => "platform.provision.schema-owner-differs", + Self::ExtensionTooOld { .. } => "platform.provision.extension-too-old", + Self::RoleLoginFailed { .. } => "platform.provision.role-login-failed", + Self::EffectUnconfirmed { .. } => "platform.provision.effect-unconfirmed", + Self::StatementFailed { .. } => "platform.provision.statement-failed", + } + } + + /// The step of the plan the error belongs to, the report's `path`. + pub fn step(&self) -> Option<&'static str> { + match self { + Self::StatementNeedsPrivilege { step, .. } + | Self::RoleAttributesDiffer { step, .. } + | Self::SchemaOwnerDiffers { step, .. } + | Self::ExtensionTooOld { step, .. } + | Self::EffectUnconfirmed { step } + | Self::StatementFailed { step, .. } => Some(step), + Self::DatabaseOwnerDiffers { .. } => Some("database.create"), + Self::AdminConnectFailed { .. } + | Self::UnsupportedPostgres + | Self::RoleLoginFailed { .. } => None, + } + } +} + +fn statement_kind(step: &str) -> &str { + match step { + "role.migration" | "role.runtime" | "role.spatial-bbox" => "CREATE ROLE", + "database.create" => "CREATE DATABASE", + "database.revoke-public" => "REVOKE on the database", + "database.grant-connect" => "GRANT CONNECT on the database", + "database.grant-create" => "GRANT CREATE on the database", + "database.allow-connections" => "ALTER DATABASE", + "extension.btree-gist" => "CREATE EXTENSION btree_gist", + "extension.postgis" => "CREATE EXTENSION postgis", + "schema.owned" => "CREATE SCHEMA", + "schema.public" => "GRANT on schema public", + other => other, + } +} + +fn needed(needs: Needs) -> &'static str { + match needs { + Needs::CreateRole => "CREATEROLE", + Needs::CreateDb => "CREATEDB", + Needs::DatabaseOwner => "ownership of the database", + Needs::Superuser => "a superuser", + } +} + +impl fmt::Display for ProvisionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AdminConnectFailed { sqlstate: None } => { + f.write_str("cannot open a session with the administrator URL") + } + Self::AdminConnectFailed { + sqlstate: Some(sqlstate), + } => write!( + f, + "cannot open a session with the administrator URL (SQLSTATE {sqlstate})" + ), + Self::UnsupportedPostgres => fmt::Display::fmt(&crate::plan::UnsupportedPostgres, f), + Self::StatementNeedsPrivilege { + step, + needs, + scope, + database, + } => { + let place = match scope { + Scope::Server => "the server".to_owned(), + Scope::Database => format!("database \"{database}\""), + }; + write!( + f, + "the administrator role cannot run {} in {place}; it needs {}", + statement_kind(step), + needed(*needs) + ) + } + Self::RoleAttributesDiffer { role, .. } => write!( + f, + "the role \"{role}\" already exists with attributes other than provisioning \ + creates it with. It is not altered: use another name or correct the role as \ + an administrator" + ), + Self::DatabaseOwnerDiffers { database } => write!( + f, + "the database \"{database}\" already exists under an owner the administrator \ + role cannot act as" + ), + Self::SchemaOwnerDiffers { + schema, database, .. + } => write!( + f, + "the schema \"{schema}\" in database \"{database}\" already exists under a role \ + other than the migration role" + ), + Self::ExtensionTooOld { extension, .. } => write!( + f, + "the extension \"{extension}\" is installed below the version this product needs" + ), + Self::RoleLoginFailed { role } => write!( + f, + "the role \"{role}\" cannot open a session with its configured credential" + ), + Self::EffectUnconfirmed { step } => write!( + f, + "the outcome of step {step} is unknown after a timeout or a lost connection; \ + run provision again" + ), + Self::StatementFailed { step, sqlstate } => { + write!(f, "step {step} failed on the server (SQLSTATE {sqlstate})") + } + } + } +} + +impl std::error::Error for ProvisionError {} + +fn connect_failed(failure: ConnectFailure) -> ProvisionError { + ProvisionError::AdminConnectFailed { + sqlstate: failure.sqlstate, + } +} + +/// A row that did not have the shape the query selects: not a server error, +/// reported as the internal-error SQLSTATE. +fn unreadable(step: &'static str) -> ProvisionError { + ProvisionError::StatementFailed { + step, + sqlstate: "XX000".to_owned(), + } +} + +fn call_error(step: &'static str, failure: CallFailure) -> ProvisionError { + match failure { + CallFailure::Unconfirmed => ProvisionError::EffectUnconfirmed { step }, + CallFailure::Server { sqlstate } => ProvisionError::StatementFailed { step, sqlstate }, + } +} + +/// Runs every statement of `plan` as the administrator `admin`. +/// +/// In [`Mode::Converge`] the server version is checked against the shared +/// floor before the first statement. A statement with a probe runs only when +/// its object is absent, and a statement without one is re-applied. An +/// existing object in another shape is refused and never altered. +pub async fn execute( + admin: &AdminConfig, + plan: &Plan, + mode: Mode, +) -> Result { + let server = admin.connect(None).await.map_err(connect_failed)?; + if mode == Mode::Converge { + verify_floor(&server).await?; + } + let mut database: Option = None; + let mut statements = Vec::with_capacity(plan.statements().len()); + for statement in plan.statements() { + let session = match statement.scope { + Scope::Server => &server, + Scope::Database => match &mut database { + Some(session) => session, + empty => empty.insert( + admin + .connect(Some(plan.database())) + .await + .map_err(connect_failed)?, + ), + }, + }; + let outcome = run_statement(session, plan, statement, mode).await?; + statements.push((statement.step, outcome)); + } + Ok(Outcome { + statements, + single_role: plan.single_role(), + }) +} + +async fn verify_floor(server: &Session) -> Result<(), ProvisionError> { + const STEP: &str = "server.version"; + let row = bounded_call(server.client.query_one( + "SELECT pg_catalog.current_setting('server_version_num')::int4", + &[], + )) + .await + .map_err(|failure| call_error(STEP, failure))?; + let version: i32 = row.try_get(0).map_err(|_| unreadable(STEP))?; + verify_server_version(version).map_err(|_| ProvisionError::UnsupportedPostgres) +} + +async fn run_statement( + session: &Session, + plan: &Plan, + statement: &Statement, + mode: Mode, +) -> Result { + if mode == Mode::Converge { + if let Some(probe) = &statement.probe { + if probe_is_satisfied(session, plan, statement, probe).await? { + return Ok(StatementOutcome::Present); + } + } + } + apply(session, plan, statement).await?; + Ok(if statement.probe.is_some() { + StatementOutcome::Created + } else { + StatementOutcome::Applied + }) +} + +async fn apply( + session: &Session, + plan: &Plan, + statement: &Statement, +) -> Result<(), ProvisionError> { + bounded_call(session.client.batch_execute(statement.executable())) + .await + .map_err(|failure| { + if failure.lacks_privilege() { + ProvisionError::StatementNeedsPrivilege { + step: statement.step, + needs: statement.needs, + scope: statement.scope, + database: plan.database().to_owned(), + } + } else { + call_error(statement.step, failure) + } + }) +} + +/// Whether the probed object already exists in the shape the plan creates. +/// An object that exists in another shape is an error, not `false`. +async fn probe_is_satisfied( + session: &Session, + plan: &Plan, + statement: &Statement, + probe: &Probe, +) -> Result { + let step = statement.step; + match probe { + Probe::Role { name, login } => { + let row = bounded_call(session.client.query_opt( + "SELECT rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, \ + rolbypassrls, rolreplication \ + FROM pg_catalog.pg_roles WHERE rolname = $1", + &[name], + )) + .await + .map_err(|failure| call_error(step, failure))?; + let Some(row) = row else { + return Ok(false); + }; + let can_login: bool = row.try_get(0).map_err(|_| unreadable(step))?; + let mut others = false; + for column in 1..7 { + let flag: bool = row.try_get(column).map_err(|_| unreadable(step))?; + others |= flag; + } + if can_login != *login || others { + return Err(ProvisionError::RoleAttributesDiffer { + step, + role: name.clone(), + }); + } + Ok(true) + } + Probe::Database { name } => { + // Ownership privileges follow membership with INHERIT, which is + // what `pg_has_role(..., 'USAGE')` tests, and are held by every + // superuser. + let row = bounded_call(session.client.query_opt( + "SELECT pg_catalog.pg_has_role(current_user, datdba, 'USAGE') \ + FROM pg_catalog.pg_database WHERE datname = $1", + &[name], + )) + .await + .map_err(|failure| call_error(step, failure))?; + match row { + None => Ok(false), + Some(row) => { + let can_act: bool = row.try_get(0).map_err(|_| unreadable(step))?; + if can_act { + Ok(true) + } else { + Err(ProvisionError::DatabaseOwnerDiffers { + database: name.clone(), + }) + } + } + } + } + Probe::Extension { + name, + minimum_version, + } => { + let row = bounded_call(session.client.query_opt( + "SELECT extversion::text FROM pg_catalog.pg_extension WHERE extname = $1", + &[name], + )) + .await + .map_err(|failure| call_error(step, failure))?; + let Some(row) = row else { + return Ok(false); + }; + let installed: String = row.try_get(0).map_err(|_| unreadable(step))?; + match minimum_version { + Some(minimum) if !version_at_least(&installed, *minimum) => { + Err(ProvisionError::ExtensionTooOld { + step, + extension: name.clone(), + }) + } + _ => Ok(true), + } + } + Probe::Schema { name, owner } => { + let row = bounded_call(session.client.query_opt( + "SELECT pg_catalog.pg_get_userbyid(nspowner)::text \ + FROM pg_catalog.pg_namespace WHERE nspname = $1", + &[name], + )) + .await + .map_err(|failure| call_error(step, failure))?; + match row { + None => Ok(false), + Some(row) => { + let actual: String = row.try_get(0).map_err(|_| unreadable(step))?; + if actual == *owner { + Ok(true) + } else { + Err(ProvisionError::SchemaOwnerDiffers { + step, + schema: name.clone(), + database: plan.database().to_owned(), + }) + } + } + } + } + } +} + +/// Compares the leading `major.minor` of an extension version such as +/// `3.5.2` or `3.6.0dev`. +fn version_at_least(version: &str, minimum: (u32, u32)) -> bool { + let mut parts = version.split('.').map(|part| { + part.chars() + .take_while(char::is_ascii_digit) + .collect::() + .parse::() + .ok() + }); + match (parts.next().flatten(), parts.next().flatten()) { + (Some(major), Some(minor)) => (major, minor) >= minimum, + _ => false, + } +} + +/// Opens one session per product role, in the provisioned database, and asks +/// each who it is. A role that already existed keeps its stored password, so +/// this is what tells an operator that the configured credential does not +/// open a session. The administrator URL supplies only the endpoint and TLS. +pub async fn verify_logins( + admin: &AdminConfig, + target: &ProvisionTarget, +) -> Result<(), ProvisionError> { + let mut roles = vec![&target.migration]; + if target.runtime.name != target.migration.name { + roles.push(&target.runtime); + } + for role in roles { + let failed = || ProvisionError::RoleLoginFailed { + role: role.name.clone(), + }; + let session = admin + .connect_as(&target.database, &role.name, role.password()) + .await + .map_err(|_| failed())?; + let row = bounded_call(session.client.query_one("SELECT current_user::text", &[])) + .await + .map_err(|_| failed())?; + let current: String = row.try_get(0).map_err(|_| failed())?; + if current != role.name { + return Err(failed()); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extension_versions_compare_by_major_and_minor() { + assert!(version_at_least("3.5.2", (3, 5))); + assert!(version_at_least("3.6.0dev", (3, 5))); + assert!(version_at_least("4.0.0", (3, 5))); + assert!(!version_at_least("3.4.9", (3, 5))); + assert!(!version_at_least("3", (3, 5))); + assert!(!version_at_least("not a version", (3, 5))); + } + + #[test] + fn every_code_is_distinct_and_in_the_provision_family() { + let errors = [ + ProvisionError::AdminConnectFailed { sqlstate: None }, + ProvisionError::UnsupportedPostgres, + ProvisionError::StatementNeedsPrivilege { + step: "database.create", + needs: Needs::CreateDb, + scope: Scope::Server, + database: "d".to_owned(), + }, + ProvisionError::RoleAttributesDiffer { + step: "role.migration", + role: "r".to_owned(), + }, + ProvisionError::DatabaseOwnerDiffers { + database: "d".to_owned(), + }, + ProvisionError::SchemaOwnerDiffers { + step: "schema.owned", + schema: "s".to_owned(), + database: "d".to_owned(), + }, + ProvisionError::ExtensionTooOld { + step: "extension.postgis", + extension: "postgis".to_owned(), + }, + ProvisionError::RoleLoginFailed { + role: "r".to_owned(), + }, + ProvisionError::EffectUnconfirmed { + step: "role.runtime", + }, + ProvisionError::StatementFailed { + step: "role.runtime", + sqlstate: "42710".to_owned(), + }, + ]; + let mut codes: Vec<&str> = errors.iter().map(ProvisionError::code).collect(); + assert!(codes + .iter() + .all(|code| code.starts_with("platform.provision."))); + codes.sort_unstable(); + codes.dedup(); + assert_eq!(codes.len(), errors.len()); + } + + #[test] + fn the_floor_error_uses_the_ledger_sentence() { + assert!(ProvisionError::UnsupportedPostgres + .to_string() + .starts_with("PostgreSQL 17 or newer is required")); + } +} diff --git a/crates/registry-platform-provision/src/lib.rs b/crates/registry-platform-provision/src/lib.rs new file mode 100644 index 0000000000..404ad8d7aa --- /dev/null +++ b/crates/registry-platform-provision/src/lib.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Product-free PostgreSQL provisioning for Registry Stack runtimes. +//! +//! A product describes what it needs from an empty server as data +//! ([`ProductDatabase`]) and names its roles and database ([`ProvisionTarget`]). +//! [`plan`] turns those into an ordered list of statements. [`render_script`] +//! prints that list for an administrator to review and run with `psql`. The +//! printed script never holds a password or a password verifier. +//! +//! [`execute`] runs the same plan against a server as an administrator over +//! verified TLS ([`admin_config`]). It checks the server version first, creates +//! only what is absent, refuses what exists in another shape, and names the one +//! statement an administrator role lacks the privilege for. Role passwords +//! reach the server as SCRAM-SHA-256 verifiers and never reach an error or a +//! report. [`verify_logins`] then opens a session as each product role. + +mod admin; +mod execute; +mod plan; +pub mod sql; + +pub use admin::{admin_config, AdminConfig, AdminConfigError}; +pub use execute::{execute, verify_logins, Mode, Outcome, ProvisionError, StatementOutcome}; + +pub use plan::{ + plan, render_script, verify_server_version, Needs, Plan, PlanError, Probe, ProductDatabase, + ProvisionTarget, RoleCredential, SchemaLayout, Scope, Spatial, Statement, UnsupportedPostgres, +}; diff --git a/crates/registry-platform-provision/src/plan.rs b/crates/registry-platform-provision/src/plan.rs new file mode 100644 index 0000000000..450019d177 --- /dev/null +++ b/crates/registry-platform-provision/src/plan.rs @@ -0,0 +1,871 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The provisioning plan: which statements a product needs, in order, and the +//! rules that make running them again safe. + +use std::fmt; + +use zeroize::Zeroizing; + +use crate::sql; + +/// What one product needs from an empty server. Built by the product, never by +/// this crate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProductDatabase { + /// Names the product in reports only. + pub product: &'static str, + pub layout: SchemaLayout, + pub btree_gist: bool, + pub spatial: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaLayout { + /// Tables live in `public`. The migration role gets USAGE and CREATE on it. + PublicForMigration, + /// Named schemas, each created with AUTHORIZATION the migration role. + Owned(Vec), + /// `apply` creates the schema. The migration role gets CREATE on the database. + CreatedByApply, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Spatial { + /// Schema holding PostGIS. Written unquoted, so it must be a plain lower-case identifier. + pub schema: String, + pub bbox_role: String, + pub minimum_postgis: (u32, u32), +} + +/// A role name and its password. `Debug` prints the name only. +pub struct RoleCredential { + pub name: String, + password: Zeroizing, +} + +impl RoleCredential { + pub fn new(name: impl Into, password: impl Into) -> Self { + Self { + name: name.into(), + password: Zeroizing::new(password.into()), + } + } + + /// For the login check, which opens a session as this role. + pub(crate) fn password(&self) -> &str { + &self.password + } +} + +impl fmt::Debug for RoleCredential { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RoleCredential") + .field("name", &self.name) + .finish_non_exhaustive() + } +} + +/// Role names, database name and passwords. +#[derive(Debug)] +pub struct ProvisionTarget { + pub database: String, + pub migration: RoleCredential, + /// The same name as `migration` means single-role mode. + pub runtime: RoleCredential, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scope { + Server, + Database, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Needs { + CreateRole, + CreateDb, + DatabaseOwner, + Superuser, +} + +/// The catalog fact that tells a converging run the object already exists. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Probe { + Role { + name: String, + login: bool, + }, + Database { + name: String, + }, + Extension { + name: String, + minimum_version: Option<(u32, u32)>, + }, + Schema { + name: String, + owner: String, + }, +} + +pub struct Statement { + pub step: &'static str, + pub scope: Scope, + pub needs: Needs, + /// Never holds a password or a verifier. + pub printable: String, + /// `None`: re-applied on every run, a no-op when already true. + pub probe: Option, + /// The role the printed script asks the administrator to set a password for. + pub password_for: Option, + executable: Zeroizing, +} + +impl Statement { + /// The text an executor sends. Holds the SCRAM verifier, so it is never printed. + pub(crate) fn executable(&self) -> &str { + &self.executable + } +} + +impl fmt::Debug for Statement { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Statement") + .field("step", &self.step) + .field("scope", &self.scope) + .field("needs", &self.needs) + .field("printable", &self.printable) + .field("probe", &self.probe) + .finish_non_exhaustive() + } +} + +#[derive(Debug)] +pub struct Plan { + product: &'static str, + database: String, + single_role: bool, + statements: Vec, +} + +impl Plan { + pub fn product(&self) -> &'static str { + self.product + } + pub fn database(&self) -> &str { + &self.database + } + pub fn single_role(&self) -> bool { + self.single_role + } + pub fn statements(&self) -> &[Statement] { + &self.statements + } +} + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum PlanError { + /// Names the field, never its value. + #[error("invalid {what}")] + InvalidName { what: &'static str }, + #[error("an owned schema layout needs at least one schema")] + NoSchemas, + #[error("single-role mode needs one password for the one role")] + SingleRolePasswordsDiffer, +} + +/// The sentence is the activation ledger's own, so every product refuses an +/// old server in the same words. +#[derive(Debug, PartialEq, Eq)] +pub struct UnsupportedPostgres; + +impl fmt::Display for UnsupportedPostgres { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(®istry_platform_activation::Error::UnsupportedPostgres, f) + } +} + +impl std::error::Error for UnsupportedPostgres {} + +/// Refuses a `server_version_num` below the shared PostgreSQL floor. +pub fn verify_server_version(version_num: i32) -> Result<(), UnsupportedPostgres> { + if version_num < registry_platform_activation::MINIMUM_SERVER_VERSION_NUM { + return Err(UnsupportedPostgres); + } + Ok(()) +} + +const MAX_NAME_BYTES: usize = 63; + +fn check_name(what: &'static str, name: &str) -> Result<(), PlanError> { + if name.is_empty() || name.len() > MAX_NAME_BYTES || name.contains('\0') { + return Err(PlanError::InvalidName { what }); + } + Ok(()) +} + +/// The PostGIS schema is written unquoted in the statement text. +fn check_plain_identifier(what: &'static str, name: &str) -> Result<(), PlanError> { + check_name(what, name)?; + let mut bytes = name.bytes(); + let first_ok = bytes + .next() + .is_some_and(|b| b.is_ascii_lowercase() || b == b'_'); + if !first_ok || !bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') { + return Err(PlanError::InvalidName { what }); + } + Ok(()) +} + +fn statement( + step: &'static str, + scope: Scope, + needs: Needs, + printable: String, + probe: Option, +) -> Statement { + Statement { + step, + scope, + needs, + executable: Zeroizing::new(printable.clone()), + printable, + probe, + password_for: None, + } +} + +fn login_role(step: &'static str, credential: &RoleCredential) -> Statement { + let verifier = Zeroizing::new(postgres_protocol::password::scram_sha_256( + credential.password.as_bytes(), + )); + let mut statement = statement( + step, + Scope::Server, + Needs::CreateRole, + sql::create_role_printable_sql(&credential.name), + Some(Probe::Role { + name: credential.name.clone(), + login: true, + }), + ); + statement.executable = Zeroizing::new(sql::create_role_sql(&credential.name, &verifier)); + statement.password_for = Some(credential.name.clone()); + statement +} + +/// Builds the ordered statements one product needs on an empty server. +/// +/// A statement with a `probe` runs only when its object is absent. One +/// without is a grant, revoke or connection switch that is a no-op when it +/// already holds, so it runs every time. Passwords reach only the private +/// executable text, as SCRAM verifiers. +pub fn plan(product: &ProductDatabase, target: &ProvisionTarget) -> Result { + check_name("database name", &target.database)?; + check_name("migration role name", &target.migration.name)?; + check_name("runtime role name", &target.runtime.name)?; + let single_role = target.migration.name == target.runtime.name; + if single_role && *target.migration.password != *target.runtime.password { + return Err(PlanError::SingleRolePasswordsDiffer); + } + if let SchemaLayout::Owned(schemas) = &product.layout { + if schemas.is_empty() { + return Err(PlanError::NoSchemas); + } + for schema in schemas { + check_name("schema name", schema)?; + } + } + if let Some(spatial) = &product.spatial { + check_plain_identifier("PostGIS schema name", &spatial.schema)?; + check_name("PostGIS bbox role name", &spatial.bbox_role)?; + } + + let database = target.database.as_str(); + let migration = target.migration.name.as_str(); + let runtime = target.runtime.name.as_str(); + let mut statements = vec![login_role("role.migration", &target.migration)]; + if !single_role { + statements.push(login_role("role.runtime", &target.runtime)); + } + if let Some(spatial) = &product.spatial { + statements.push(statement( + "role.spatial-bbox", + Scope::Server, + Needs::CreateRole, + sql::create_nologin_role_sql(&spatial.bbox_role), + Some(Probe::Role { + name: spatial.bbox_role.clone(), + login: false, + }), + )); + } + let owner = + |step, printable| statement(step, Scope::Server, Needs::DatabaseOwner, printable, None); + statements.push(statement( + "database.create", + Scope::Server, + Needs::CreateDb, + sql::create_database_sql(database), + Some(Probe::Database { + name: database.to_owned(), + }), + )); + statements.push(owner( + "database.revoke-public", + sql::revoke_public_sql(database), + )); + let grantees: Vec<&str> = if single_role { + vec![migration] + } else { + vec![migration, runtime] + }; + statements.push(owner( + "database.grant-connect", + sql::grant_connect_sql(database, &grantees), + )); + if product.layout == SchemaLayout::CreatedByApply { + statements.push(owner( + "database.grant-create", + sql::grant_create_sql(database, migration), + )); + } + statements.push(owner( + "database.allow-connections", + sql::allow_connections_sql(database), + )); + + let in_database = |step, printable, probe| { + statement( + step, + Scope::Database, + Needs::DatabaseOwner, + printable, + probe, + ) + }; + if product.btree_gist { + statements.push(in_database( + "extension.btree-gist", + sql::btree_gist_sql().to_owned(), + Some(Probe::Extension { + name: "btree_gist".to_owned(), + minimum_version: None, + }), + )); + } + match &product.layout { + SchemaLayout::Owned(schemas) => { + for schema in schemas { + statements.push(in_database( + "schema.owned", + sql::owned_schema_sql(schema, migration), + Some(Probe::Schema { + name: schema.clone(), + owner: migration.to_owned(), + }), + )); + } + } + SchemaLayout::PublicForMigration => { + statements.push(in_database( + "schema.public", + sql::public_schema_sql(migration), + None, + )); + } + SchemaLayout::CreatedByApply => {} + } + if let Some(spatial) = &product.spatial { + let mut postgis = in_database( + "extension.postgis", + sql::postgis_prerequisites_sql(&spatial.schema, migration, runtime, &spatial.bbox_role), + Some(Probe::Extension { + name: "postgis".to_owned(), + minimum_version: Some(spatial.minimum_postgis), + }), + ); + postgis.needs = Needs::Superuser; + statements.push(postgis); + } + + Ok(Plan { + product: product.product, + database: target.database.clone(), + single_role, + statements, + }) +} + +/// The script an administrator reviews and runs with `psql`. It holds no +/// password and no verifier: each login role is followed by a `\password` +/// line so `psql` prompts for it. +pub fn render_script(plan: &Plan) -> String { + let mut script = format!( + "-- provision script, product {}. Nothing was run.\n\ + -- For a server where these objects do not exist yet. Review, then run with psql as an\n\ + -- administrator that has CREATEROLE and CREATEDB.\n\ + SET createrole_self_grant = {};\n", + plan.product, + sql::quote_literal(sql::CREATEROLE_SELF_GRANT), + ); + let mut connected = false; + for statement in &plan.statements { + if statement.scope == Scope::Database && !connected { + script.push_str(&format!( + "\\connect {}\n", + sql::quote_identifier(&plan.database) + )); + connected = true; + } + if statement.needs == Needs::Superuser { + script.push_str("-- needs a superuser\n"); + } + script.push_str(&statement.printable); + if !statement.printable.ends_with(';') { + script.push(';'); + } + script.push('\n'); + if let Some(role) = &statement.password_for { + script.push_str(&format!("\\password {}\n", sql::quote_identifier(role))); + } + } + script +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sql::*; + + const PASSWORD_M: &str = "migration-pass-0123"; + const PASSWORD_R: &str = "runtime-pass-4567"; + + fn target() -> ProvisionTarget { + ProvisionTarget { + database: "casework".to_owned(), + migration: RoleCredential::new("casework_migration", PASSWORD_M), + runtime: RoleCredential::new("casework_runtime", PASSWORD_R), + } + } + + fn product(layout: SchemaLayout) -> ProductDatabase { + ProductDatabase { + product: "casework", + layout, + btree_gist: false, + spatial: None, + } + } + + fn breg_schemas() -> Vec { + [ + "registry_internal", + "registry_data", + "registry_source", + "registry_derived", + "registry_context", + ] + .map(str::to_owned) + .to_vec() + } + + fn breg_spatial() -> ProductDatabase { + ProductDatabase { + product: "breg", + layout: SchemaLayout::Owned(breg_schemas()), + btree_gist: true, + spatial: Some(Spatial { + schema: "registry_spatial_ext".to_owned(), + bbox_role: "casework_runtime__spatial_bbox".to_owned(), + minimum_postgis: (3, 5), + }), + } + } + + fn steps(plan: &Plan) -> Vec<&'static str> { + plan.statements().iter().map(|s| s.step).collect() + } + + #[test] + fn plan_lists_statements_in_order_for_public_layout() { + let plan = plan(&product(SchemaLayout::PublicForMigration), &target()).unwrap(); + assert_eq!( + steps(&plan), + [ + "role.migration", + "role.runtime", + "database.create", + "database.revoke-public", + "database.grant-connect", + "database.allow-connections", + "schema.public", + ] + ); + assert!(!plan.single_role()); + } + + #[test] + fn plan_lists_statements_in_order_for_owned_layout_with_spatial() { + let plan = plan(&breg_spatial(), &target()).unwrap(); + assert_eq!( + steps(&plan), + [ + "role.migration", + "role.runtime", + "role.spatial-bbox", + "database.create", + "database.revoke-public", + "database.grant-connect", + "database.allow-connections", + "extension.btree-gist", + "schema.owned", + "schema.owned", + "schema.owned", + "schema.owned", + "schema.owned", + "extension.postgis", + ] + ); + let postgis = plan.statements().last().unwrap(); + assert_eq!(postgis.needs, Needs::Superuser); + assert_eq!(postgis.scope, Scope::Database); + } + + #[test] + fn plan_lists_statements_in_order_for_created_by_apply_layout() { + let plan = plan(&product(SchemaLayout::CreatedByApply), &target()).unwrap(); + assert_eq!( + steps(&plan), + [ + "role.migration", + "role.runtime", + "database.create", + "database.revoke-public", + "database.grant-connect", + "database.grant-create", + "database.allow-connections", + ] + ); + } + + #[test] + fn statements_carry_scope_needs_and_probe() { + let plan = plan(&product(SchemaLayout::PublicForMigration), &target()).unwrap(); + let by_step = |step| plan.statements().iter().find(|s| s.step == step).unwrap(); + let role = by_step("role.migration"); + assert_eq!((role.scope, role.needs), (Scope::Server, Needs::CreateRole)); + assert_eq!( + role.probe, + Some(Probe::Role { + name: "casework_migration".to_owned(), + login: true + }) + ); + let create = by_step("database.create"); + assert_eq!(create.needs, Needs::CreateDb); + assert_eq!( + create.probe, + Some(Probe::Database { + name: "casework".to_owned() + }) + ); + for step in [ + "database.revoke-public", + "database.grant-connect", + "database.allow-connections", + "schema.public", + ] { + assert_eq!(by_step(step).probe, None, "{step}"); + assert_eq!(by_step(step).needs, Needs::DatabaseOwner, "{step}"); + } + assert_eq!(by_step("schema.public").scope, Scope::Database); + assert_eq!(by_step("database.revoke-public").scope, Scope::Server); + } + + #[test] + fn rendered_script_holds_no_password_and_no_verifier() { + for product in [product(SchemaLayout::PublicForMigration), breg_spatial()] { + let target = target(); + let plan = plan(&product, &target).unwrap(); + let script = render_script(&plan); + for secret in [PASSWORD_M, PASSWORD_R, "SCRAM-SHA-256", "PASSWORD '"] { + assert!(!script.contains(secret), "{secret} in {script}"); + } + for rendered in [format!("{plan:?}"), format!("{target:?}")] { + assert!(!rendered.contains(PASSWORD_M) && !rendered.contains(PASSWORD_R)); + assert!(!rendered.contains("SCRAM-SHA-256")); + } + for statement in plan.statements() { + assert!(!statement.printable.contains("SCRAM-SHA-256")); + assert!(!statement.printable.contains(PASSWORD_M)); + } + } + } + + #[test] + fn executable_role_statements_carry_a_verifier_never_the_password() { + let plan = plan(&product(SchemaLayout::PublicForMigration), &target()).unwrap(); + for statement in plan + .statements() + .iter() + .filter(|s| s.password_for.is_some()) + { + let executable = statement.executable(); + assert!( + executable.contains("PASSWORD 'SCRAM-SHA-256$"), + "{}", + statement.step + ); + assert!(!executable.contains(PASSWORD_M) && !executable.contains(PASSWORD_R)); + } + } + + #[test] + fn rendered_script_asks_for_passwords_and_switches_database() { + let script = render_script(&plan(&breg_spatial(), &target()).unwrap()); + assert!(script.contains("Nothing was run"), "{script}"); + assert!( + script.contains("SET createrole_self_grant = 'set,inherit';"), + "{script}" + ); + assert!( + script.contains("\\password \"casework_migration\""), + "{script}" + ); + assert!( + script.contains("\\password \"casework_runtime\""), + "{script}" + ); + assert!( + !script.contains("\\password \"casework_runtime__spatial_bbox\""), + "{script}" + ); + let connect = script.find("\\connect \"casework\"").expect("connect line"); + let allow = script.find("ALLOW_CONNECTIONS true").unwrap(); + let btree = script.find("CREATE EXTENSION btree_gist").unwrap(); + assert!(allow < connect && connect < btree, "{script}"); + let marker = script.find("-- needs a superuser").unwrap(); + assert!(script[marker..].contains("CREATE EXTENSION IF NOT EXISTS postgis")); + assert_eq!(script.matches("-- needs a superuser").count(), 1); + } + + #[test] + fn single_role_target_plans_one_role() { + let target = ProvisionTarget { + database: "adapter".to_owned(), + migration: RoleCredential::new("adapter", PASSWORD_M), + runtime: RoleCredential::new("adapter", PASSWORD_M), + }; + let plan = plan(&product(SchemaLayout::PublicForMigration), &target).unwrap(); + assert!(plan.single_role()); + let roles: Vec<_> = plan + .statements() + .iter() + .filter(|s| s.step.starts_with("role.")) + .collect(); + assert_eq!(roles.len(), 1); + assert_eq!(roles[0].step, "role.migration"); + let grant = plan + .statements() + .iter() + .find(|s| s.step == "database.grant-connect") + .unwrap(); + assert_eq!( + grant.printable.matches("\"adapter\"").count(), + 2, + "{}", + grant.printable + ); + assert!( + grant.printable.ends_with("TO \"adapter\""), + "{}", + grant.printable + ); + } + + #[test] + fn single_role_with_two_passwords_is_refused() { + let target = ProvisionTarget { + database: "adapter".to_owned(), + migration: RoleCredential::new("adapter", PASSWORD_M), + runtime: RoleCredential::new("adapter", PASSWORD_R), + }; + assert!(matches!( + plan(&product(SchemaLayout::PublicForMigration), &target), + Err(PlanError::SingleRolePasswordsDiffer) + )); + } + + #[test] + fn unusable_names_are_refused_without_echoing_them() { + let mut bad = target(); + bad.database = String::new(); + let error = plan(&product(SchemaLayout::PublicForMigration), &bad).unwrap_err(); + assert_eq!( + error, + PlanError::InvalidName { + what: "database name" + } + ); + + let mut long = target(); + long.migration = RoleCredential::new("m".repeat(64), PASSWORD_M); + assert!(plan(&product(SchemaLayout::PublicForMigration), &long).is_err()); + + let mut nul = target(); + nul.runtime = RoleCredential::new("a\0b", PASSWORD_R); + assert!(plan(&product(SchemaLayout::PublicForMigration), &nul).is_err()); + + assert_eq!( + plan(&product(SchemaLayout::Owned(Vec::new())), &target()).unwrap_err(), + PlanError::NoSchemas + ); + + let mut spatial = breg_spatial(); + spatial.spatial.as_mut().unwrap().schema = "bad schema; DROP".to_owned(); + assert_eq!( + plan(&spatial, &target()).unwrap_err(), + PlanError::InvalidName { + what: "PostGIS schema name" + } + ); + } + + #[test] + fn server_below_the_floor_is_refused() { + for version in [0, 90_600, 160_999, 169_999] { + assert_eq!( + verify_server_version(version), + Err(UnsupportedPostgres), + "{version}" + ); + } + for version in [170_000, 170_011, 180_000] { + assert_eq!(verify_server_version(version), Ok(()), "{version}"); + } + assert!(UnsupportedPostgres + .to_string() + .starts_with("PostgreSQL 17 or newer is required")); + assert_eq!( + registry_platform_activation::MINIMUM_SERVER_VERSION_NUM, + 170_000 + ); + } + + // Builder and quoting tests, carried over from `registry-rstack-dev`. + + #[test] + fn identifiers_and_passwords_are_quoted_for_postgresql() { + assert_eq!(quote_identifier("a\"b"), "\"a\"\"b\""); + assert_eq!(quote_literal("a'b"), "'a''b'"); + } + + #[test] + fn role_statement_carries_a_postgresql_scram_verifier_not_cleartext() { + let password = "a-throwaway-credential"; + let verifier = postgres_protocol::password::scram_sha_256(password.as_bytes()); + let sql = create_role_sql("rstack_role", &verifier); + let expected = format!( + "CREATE ROLE \"rstack_role\" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD '{verifier}'" + ); + assert!(verifier.starts_with("SCRAM-SHA-256$")); + assert!(sql == expected && !sql.contains(password)); + } + + #[test] + fn nologin_role_statement_has_no_password_clause() { + assert_eq!( + create_nologin_role_sql("bbox"), + "CREATE ROLE \"bbox\" NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS" + ); + } + + #[test] + fn database_creation_is_closed_to_connections() { + assert_eq!( + create_database_sql("db\"x"), + "CREATE DATABASE \"db\"\"x\" WITH ALLOW_CONNECTIONS false" + ); + } + + #[test] + fn database_access_is_closed_to_public_before_connections_are_enabled() { + let sql = database_access_sql("casework", "casework_migration", "casework_runtime"); + let revoke = sql.find("REVOKE ALL ON DATABASE").unwrap(); + let grant = sql.find("GRANT CONNECT ON DATABASE").unwrap(); + let enable = sql.find("ALLOW_CONNECTIONS true").unwrap(); + assert!(revoke < grant && grant < enable, "{sql}"); + assert!(sql.contains("e_identifier("casework_migration"))); + assert!(sql.contains("e_identifier("casework_runtime"))); + assert_eq!( + sql, + "REVOKE ALL ON DATABASE \"casework\" FROM PUBLIC; \ + GRANT CONNECT ON DATABASE \"casework\" TO \"casework_migration\", \"casework_runtime\"; \ + ALTER DATABASE \"casework\" ALLOW_CONNECTIONS true" + ); + } + + #[test] + fn grant_create_is_on_the_database_for_the_migration_role() { + assert_eq!( + grant_create_sql("coordinator", "coordinator_migration"), + "GRANT CREATE ON DATABASE \"coordinator\" TO \"coordinator_migration\"" + ); + } + + #[test] + fn breg_setup_installs_extension_and_all_owned_schemas() { + let layout = SchemaLayout::Owned(breg_schemas()); + let sql = database_setup_sql("casework_migration", &layout, true); + assert!(sql.starts_with("CREATE EXTENSION btree_gist;"), "{sql}"); + for schema in breg_schemas() { + assert!( + sql.contains(&format!( + "CREATE SCHEMA {} AUTHORIZATION {}", + quote_identifier(&schema), + quote_identifier("casework_migration") + )), + "{sql}" + ); + assert!( + sql.contains(&format!( + "REVOKE ALL ON SCHEMA {} FROM PUBLIC", + quote_identifier(&schema) + )), + "{sql}" + ); + } + } + + #[test] + fn public_setup_restricts_create_and_grants_the_migration_role() { + assert_eq!( + database_setup_sql( + "casework_migration", + &SchemaLayout::PublicForMigration, + false + ), + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO \"casework_migration\"" + ); + assert_eq!( + database_setup_sql("m", &SchemaLayout::CreatedByApply, false), + "" + ); + } + + #[test] + fn postgis_prerequisites_name_the_schema_and_both_roles() { + let sql = postgis_prerequisites_sql("registry_spatial_ext", "m", "r", "bbox"); + assert_eq!( + sql, + "CREATE SCHEMA IF NOT EXISTS registry_spatial_ext;\n\ + REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC;\n\ + CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA registry_spatial_ext;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO \"m\", \"r\";\n\ + GRANT \"bbox\" TO \"m\" WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO \"bbox\";" + ); + } +} diff --git a/crates/registry-platform-provision/src/sql.rs b/crates/registry-platform-provision/src/sql.rs new file mode 100644 index 0000000000..0baea3347a --- /dev/null +++ b/crates/registry-platform-provision/src/sql.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Statement builders. Every builder returns text and runs nothing. The text +//! of each statement is the text `rstack dev` provisions with. + +use crate::plan::SchemaLayout; + +/// Lets a role holding CREATEROLE use the roles it creates. PostgreSQL 16 and +/// later grant such a creator only ADMIN on them, which is not enough for +/// `CREATE SCHEMA ... AUTHORIZATION` or `CREATE DATABASE ... OWNER`. +pub const CREATEROLE_SELF_GRANT: &str = "set,inherit"; + +pub fn quote_identifier(value: &str) -> String { + format!("\"{}\"", value.replace('"', "\"\"")) +} + +pub fn quote_literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + +/// `verifier` is a SCRAM-SHA-256 verifier, never a password. +pub fn create_role_sql(role: &str, verifier: &str) -> String { + format!( + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD {}", + quote_identifier(role), + quote_literal(verifier) + ) +} + +/// The login role without its `PASSWORD` clause, for the printed script. +pub(crate) fn create_role_printable_sql(role: &str) -> String { + format!( + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS", + quote_identifier(role) + ) +} + +pub fn create_nologin_role_sql(role: &str) -> String { + format!( + "CREATE ROLE {} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS", + quote_identifier(role) + ) +} + +pub fn create_database_sql(database: &str) -> String { + format!( + "CREATE DATABASE {} WITH ALLOW_CONNECTIONS false", + quote_identifier(database) + ) +} + +pub fn revoke_public_sql(database: &str) -> String { + format!( + "REVOKE ALL ON DATABASE {} FROM PUBLIC", + quote_identifier(database) + ) +} + +pub fn grant_connect_sql(database: &str, roles: &[&str]) -> String { + let roles = roles + .iter() + .map(|role| quote_identifier(role)) + .collect::>() + .join(", "); + format!( + "GRANT CONNECT ON DATABASE {} TO {roles}", + quote_identifier(database) + ) +} + +pub fn grant_create_sql(database: &str, migration: &str) -> String { + format!( + "GRANT CREATE ON DATABASE {} TO {}", + quote_identifier(database), + quote_identifier(migration) + ) +} + +pub fn allow_connections_sql(database: &str) -> String { + format!( + "ALTER DATABASE {} ALLOW_CONNECTIONS true", + quote_identifier(database) + ) +} + +/// The three statements that close a new database to PUBLIC, open it to the +/// run's roles and then let it accept connections, in that order. +pub fn database_access_sql(database: &str, migration: &str, runtime: &str) -> String { + format!( + "{}; {}; {}", + revoke_public_sql(database), + grant_connect_sql(database, &distinct_roles(migration, runtime)), + allow_connections_sql(database), + ) +} + +pub fn btree_gist_sql() -> &'static str { + "CREATE EXTENSION btree_gist" +} + +pub fn owned_schema_sql(schema: &str, owner: &str) -> String { + format!( + "CREATE SCHEMA {schema} AUTHORIZATION {owner}; \ + REVOKE ALL ON SCHEMA {schema} FROM PUBLIC", + schema = quote_identifier(schema), + owner = quote_identifier(owner), + ) +} + +pub fn public_schema_sql(migration: &str) -> String { + format!( + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO {}", + quote_identifier(migration) + ) +} + +/// Everything that runs inside the database apart from PostGIS: the one batch +/// `rstack dev` configures a fresh database with. `CreatedByApply` has none. +pub fn database_setup_sql(migration: &str, layout: &SchemaLayout, btree_gist: bool) -> String { + match layout { + SchemaLayout::Owned(schemas) => { + let schemas = schemas + .iter() + .map(|schema| owned_schema_sql(schema, migration)) + .collect::>() + .join("; "); + if btree_gist { + format!("{}; {schemas}", btree_gist_sql()) + } else { + schemas + } + } + SchemaLayout::PublicForMigration => public_schema_sql(migration), + SchemaLayout::CreatedByApply => String::new(), + } +} + +/// Administrator-run PostGIS setup: the extension in its own schema, usable by +/// both roles, and the bbox role the migration role may SET. The bbox role +/// itself is created earlier. `schema` is written unquoted, so the caller +/// checks it is a plain lower-case identifier. +pub fn postgis_prerequisites_sql( + schema: &str, + migration: &str, + runtime: &str, + bbox_role: &str, +) -> String { + let roles = distinct_roles(migration, runtime) + .iter() + .map(|role| quote_identifier(role)) + .collect::>() + .join(", "); + let migration = quote_identifier(migration); + let bbox = quote_identifier(bbox_role); + format!( + "CREATE SCHEMA IF NOT EXISTS {schema};\n\ + REVOKE ALL ON SCHEMA {schema} FROM PUBLIC;\n\ + CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA {schema};\n\ + GRANT USAGE ON SCHEMA {schema} TO {roles};\n\ + GRANT {bbox} TO {migration} WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ + GRANT USAGE ON SCHEMA {schema} TO {bbox};" + ) +} + +/// Single-role mode names one role once. +fn distinct_roles<'a>(migration: &'a str, runtime: &'a str) -> Vec<&'a str> { + if migration == runtime { + vec![migration] + } else { + vec![migration, runtime] + } +} diff --git a/crates/registry-platform-provision/tests/postgres.rs b/crates/registry-platform-provision/tests/postgres.rs new file mode 100644 index 0000000000..16af51bc4f --- /dev/null +++ b/crates/registry-platform-provision/tests/postgres.rs @@ -0,0 +1,1332 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runs the provisioning executor against real PostgreSQL servers. +//! +//! The suite reads three variables and fails, never skips, when one is +//! missing: +//! +//! - `PROVISION_TEST_DATABASE_URL`: a disposable PostgreSQL 17 superuser with +//! PostGIS available, over TLS. +//! - `PROVISION_TEST_DATABASE_CA`: the CA PEM file that signs its certificate. +//! - `PROVISION_TEST_OLD_DATABASE_URL`: a disposable superuser on a server +//! older than the floor, signed by the same CA. +//! +//! Each test creates its own administrator role, so a test that provisions as +//! a non-superuser holds only the attributes the test names. + +use registry_platform_provision::{ + admin_config, execute, plan, render_script, verify_logins, AdminConfig, AdminConfigError, Mode, + Needs, Outcome, ProductDatabase, ProvisionError, ProvisionTarget, RoleCredential, SchemaLayout, + Scope, Spatial, StatementOutcome, +}; +use rustls::pki_types::{pem::PemObject as _, CertificateDer}; +use tokio_postgres::{config::SslMode, Client, Config}; +use tokio_postgres_rustls::MakeRustlsConnect; +use url::Url; + +/// One test at a time: concurrent `CREATE DATABASE` calls contend for +/// `template1`. +static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +const NON_SUPERUSER_ADMIN: &str = "CREATEROLE CREATEDB"; +const SUPERUSER_ADMIN: &str = "SUPERUSER"; + +fn required(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("the postgres-test feature needs {name}")) +} + +fn random_hex(bytes: usize) -> String { + let mut buffer = vec![0_u8; bytes]; + getrandom::fill(&mut buffer).expect("random bytes"); + buffer.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn quote(identifier: &str) -> String { + format!("\"{}\"", identifier.replace('"', "\"\"")) +} + +fn tls(ca: &[u8]) -> MakeRustlsConnect { + let provider = rustls::crypto::ring::default_provider(); + if provider.install_default().is_err() { + assert!( + rustls::crypto::CryptoProvider::get_default().is_some(), + "no TLS provider" + ); + } + let mut roots = rustls::RootCertStore::empty(); + for certificate in CertificateDer::pem_slice_iter(ca) { + roots.add(certificate.expect("CA PEM")).expect("CA root"); + } + MakeRustlsConnect::new( + rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(), + ) +} + +/// A plain session for the test's own setup and catalog reads. +struct Raw { + client: Client, + task: tokio::task::JoinHandle>, +} + +impl Drop for Raw { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl Raw { + async fn connect(base: &Url, ca: &[u8], user: &str, password: &str, database: &str) -> Self { + let mut config = Config::new(); + config + .host(base.host_str().expect("host")) + .port(base.port().unwrap_or(5432)) + .user(user) + .password(password) + .dbname(database) + .ssl_mode(SslMode::Require); + let (client, connection) = config.connect(tls(ca)).await.expect("test session"); + Self { + client, + task: tokio::spawn(connection), + } + } + + async fn exec(&self, sql: &str) { + self.client.batch_execute(sql).await.unwrap(); + } + + async fn text(&self, sql: &str) -> String { + self.client + .query_one(sql, &[]) + .await + .unwrap() + .get::<_, Option>(0) + .unwrap_or_default() + } + + async fn flag(&self, sql: &str) -> bool { + self.client.query_one(sql, &[]).await.unwrap().get(0) + } +} + +struct Server { + url: Url, + ca: Vec, + superuser: Raw, +} + +impl Server { + async fn start(url_variable: &str) -> Self { + let url = Url::parse(&required(url_variable)).expect("test URL"); + let ca = std::fs::read(required("PROVISION_TEST_DATABASE_CA")).expect("CA file"); + let superuser = Raw::connect( + &url, + &ca, + url.username(), + url.password().expect("password"), + "postgres", + ) + .await; + Self { url, ca, superuser } + } + + async fn session(&self, user: &str, password: &str, database: &str) -> Raw { + Raw::connect(&self.url, &self.ca, user, password, database).await + } +} + +/// Names and passwords for one test, and the administrator it provisions as. +struct Fixture { + server: Server, + suffix: String, + admin_password: String, + migration_password: String, + runtime_password: String, +} + +impl Fixture { + async fn new(administrator_attributes: &str) -> Self { + Self::on( + Server::start("PROVISION_TEST_DATABASE_URL").await, + administrator_attributes, + ) + .await + } + + async fn on(server: Server, administrator_attributes: &str) -> Self { + let fixture = Self { + server, + suffix: random_hex(5), + admin_password: random_hex(16), + migration_password: random_hex(16), + runtime_password: random_hex(16), + }; + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} LOGIN {administrator_attributes} PASSWORD '{}'", + quote(&fixture.admin_name()), + fixture.admin_password + )) + .await; + fixture + } + + fn database(&self) -> String { + format!("s2_db_{}", self.suffix) + } + fn migration_name(&self) -> String { + format!("s2_mig_{}", self.suffix) + } + fn runtime_name(&self) -> String { + format!("s2_run_{}", self.suffix) + } + fn admin_name(&self) -> String { + format!("s2_adm_{}", self.suffix) + } + fn bbox_name(&self) -> String { + format!("s2_bbox_{}", self.suffix) + } + + fn admin_url(&self) -> String { + let mut url = self.server.url.clone(); + url.set_username(&self.admin_name()).unwrap(); + url.set_password(Some(&self.admin_password)).unwrap(); + url.set_path("/postgres"); + url.into() + } + + fn admin(&self) -> AdminConfig { + admin_config(&self.admin_url(), Some(&self.server.ca)).unwrap() + } + + fn target(&self) -> ProvisionTarget { + ProvisionTarget { + database: self.database(), + migration: RoleCredential::new(self.migration_name(), &self.migration_password), + runtime: RoleCredential::new(self.runtime_name(), &self.runtime_password), + } + } + + fn single_role_target(&self) -> ProvisionTarget { + ProvisionTarget { + database: self.database(), + migration: RoleCredential::new(self.migration_name(), &self.migration_password), + runtime: RoleCredential::new(self.migration_name(), &self.migration_password), + } + } + + fn owned_product() -> ProductDatabase { + ProductDatabase { + product: "owned", + layout: SchemaLayout::Owned(vec!["s2_one".to_owned(), "s2_two".to_owned()]), + btree_gist: true, + spatial: None, + } + } + + fn public_product() -> ProductDatabase { + ProductDatabase { + product: "public", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } + } + + fn created_by_apply_product() -> ProductDatabase { + ProductDatabase { + product: "created-by-apply", + layout: SchemaLayout::CreatedByApply, + btree_gist: false, + spatial: None, + } + } + + fn spatial_product(&self, minimum_postgis: (u32, u32)) -> ProductDatabase { + ProductDatabase { + product: "spatial", + layout: SchemaLayout::Owned(vec!["s2_one".to_owned()]), + btree_gist: true, + spatial: Some(Spatial { + schema: "registry_spatial_ext".to_owned(), + bbox_role: self.bbox_name(), + minimum_postgis, + }), + } + } + + fn layouts() -> [ProductDatabase; 3] { + [ + Self::owned_product(), + Self::public_product(), + Self::created_by_apply_product(), + ] + } + + async fn provision(&self, product: &ProductDatabase) -> Result { + let plan = plan(product, &self.target()).unwrap(); + execute(&self.admin(), &plan, Mode::Converge).await + } + + /// The catalog this fixture's objects leave behind, with this fixture's + /// names replaced by placeholders, so two fixtures compare by shape. + async fn snapshot(&self) -> String { + let su = &self.server.superuser; + let names = vec![self.migration_name(), self.runtime_name(), self.bbox_name()]; + let roles = su + .client + .query_one( + "SELECT string_agg(concat_ws('|', rolname, rolsuper, rolinherit, rolcreaterole, \ + rolcreatedb, rolcanlogin, rolreplication, rolbypassrls, rolconnlimit, \ + coalesce(rolvaliduntil::text, '')), E'\\n' ORDER BY rolname) \ + FROM pg_catalog.pg_roles WHERE rolname = ANY($1)", + &[&names], + ) + .await + .unwrap() + .get::<_, Option>(0) + .unwrap_or_default(); + let members = su + .client + .query_one( + "SELECT string_agg(concat_ws('|', r.rolname, m.rolname, a.admin_option, \ + a.inherit_option, a.set_option), E'\\n' ORDER BY r.rolname, m.rolname) \ + FROM pg_catalog.pg_auth_members a \ + JOIN pg_catalog.pg_roles r ON r.oid = a.roleid \ + JOIN pg_catalog.pg_roles m ON m.oid = a.member \ + WHERE r.rolname = ANY($1) OR m.rolname = ANY($1)", + &[&names], + ) + .await + .unwrap() + .get::<_, Option>(0) + .unwrap_or_default(); + let database = su + .client + .query_opt( + "SELECT concat_ws('|', datname, pg_catalog.pg_get_userbyid(datdba), \ + datallowconn, coalesce(datacl::text, '')) \ + FROM pg_catalog.pg_database WHERE datname = $1", + &[&self.database()], + ) + .await + .unwrap() + .map(|row| row.get::<_, String>(0)) + .unwrap_or_else(|| "".to_owned()); + let inside = if database == "" { + String::new() + } else { + let session = self + .server + .session( + self.server.url.username(), + self.server.url.password().unwrap(), + &self.database(), + ) + .await; + let schemas = session + .text( + "SELECT string_agg(concat_ws('|', nspname, \ + pg_catalog.pg_get_userbyid(nspowner), coalesce(nspacl::text, '')), \ + E'\\n' ORDER BY nspname) \ + FROM pg_catalog.pg_namespace \ + WHERE nspname !~ '^pg_' AND nspname <> 'information_schema'", + ) + .await; + let extensions = session + .text( + "SELECT string_agg(extname, ',' ORDER BY extname) \ + FROM pg_catalog.pg_extension", + ) + .await; + format!("{schemas}\n{extensions}") + }; + let snapshot = format!("{roles}\n--\n{members}\n--\n{database}\n--\n{inside}"); + snapshot + .replace(&self.database(), "") + .replace(&self.migration_name(), "") + .replace(&self.runtime_name(), "") + .replace(&self.bbox_name(), "") + .replace(&self.admin_name(), "") + } + + async fn role_exists(&self, role: &str) -> bool { + self.server + .superuser + .flag(&format!( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = '{role}')" + )) + .await + } + + async fn database_exists(&self) -> bool { + self.server + .superuser + .flag(&format!( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{}')", + self.database() + )) + .await + } + + async fn cleanup(self) { + let su = &self.server.superuser; + su.exec(&format!( + "DROP DATABASE IF EXISTS {} WITH (FORCE)", + quote(&self.database()) + )) + .await; + for role in [ + self.migration_name(), + self.runtime_name(), + self.bbox_name(), + self.admin_name(), + ] { + su.exec(&format!("DROP ROLE IF EXISTS {}", quote(&role))) + .await; + } + } +} + +async fn count_records(session: &Raw) -> String { + session.text("SELECT count(*)::text FROM records").await +} + +async fn lock() -> tokio::sync::MutexGuard<'static, ()> { + SERIAL.lock().await +} + +fn outcome_of(outcome: &Outcome, step: &str) -> StatementOutcome { + outcome + .statements + .iter() + .find(|(name, _)| *name == step) + .unwrap_or_else(|| panic!("no outcome for {step}")) + .1 +} + +fn created(outcome: &Outcome) -> Vec<&'static str> { + outcome + .statements + .iter() + .filter(|(_, result)| *result == StatementOutcome::Created) + .map(|(step, _)| *step) + .collect() +} + +// ---- A.13 test 4 ---------------------------------------------------------- + +#[tokio::test] +async fn provision_twice_leaves_the_same_catalog() { + let _serial = lock().await; + for product in Fixture::layouts() { + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let first = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&first, "role.migration"), + StatementOutcome::Created + ); + assert_eq!( + outcome_of(&first, "role.runtime"), + StatementOutcome::Created + ); + assert_eq!( + outcome_of(&first, "database.create"), + StatementOutcome::Created + ); + assert_eq!( + outcome_of(&first, "database.grant-connect"), + StatementOutcome::Applied + ); + let after_first = fixture.snapshot().await; + assert!(after_first.contains(""), "{after_first}"); + + let second = fixture.provision(&product).await.unwrap(); + assert_eq!(created(&second), Vec::<&str>::new(), "{product:?}"); + assert_eq!( + outcome_of(&second, "role.migration"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&second, "role.runtime"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&second, "database.create"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&second, "database.revoke-public"), + StatementOutcome::Applied + ); + assert_eq!( + first + .statements + .iter() + .map(|(step, _)| *step) + .collect::>(), + second + .statements + .iter() + .map(|(step, _)| *step) + .collect::>() + ); + assert_eq!(after_first, fixture.snapshot().await, "{product:?}"); + verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap(); + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn schema_work_converges_by_object() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = Fixture::owned_product(); + let first = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&first, "extension.btree-gist"), + StatementOutcome::Created + ); + let schemas: Vec<_> = first + .statements + .iter() + .filter(|(step, _)| *step == "schema.owned") + .map(|(_, result)| *result) + .collect(); + assert_eq!(schemas, vec![StatementOutcome::Created; 2]); + let second = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&second, "extension.btree-gist"), + StatementOutcome::Present + ); + let schemas: Vec<_> = second + .statements + .iter() + .filter(|(step, _)| *step == "schema.owned") + .map(|(_, result)| *result) + .collect(); + assert_eq!(schemas, vec![StatementOutcome::Present; 2]); + fixture.cleanup().await; +} + +// ---- A.13 test 5 ---------------------------------------------------------- + +#[tokio::test] +async fn non_superuser_administrator_provisions() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let su = &fixture.server.superuser; + let attributes = su + .text(&format!( + "SELECT concat_ws('|', rolsuper, rolcreaterole, rolcreatedb, rolbypassrls, \ + rolreplication) \ + FROM pg_catalog.pg_roles WHERE rolname = '{}'", + fixture.admin_name() + )) + .await; + assert_eq!(attributes, "f|t|t|f|f"); + + let outcome = fixture.provision(&Fixture::owned_product()).await.unwrap(); + assert!(!outcome.single_role); + assert_eq!( + outcome_of(&outcome, "schema.owned"), + StatementOutcome::Created + ); + verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap(); + fixture.cleanup().await; +} + +// ---- A.11: split roles, forced row-level security --------------------------- + +#[tokio::test] +async fn split_roles_hold_only_what_the_plan_grants() { + let _serial = lock().await; + for product in Fixture::layouts() { + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture.provision(&product).await.unwrap(); + let su = &fixture.server.superuser; + let (m, r, db) = ( + fixture.migration_name(), + fixture.runtime_name(), + fixture.database(), + ); + for role in [&m, &r] { + let attributes = su + .text(&format!( + "SELECT concat_ws('|', rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, \ + rolinherit, rolbypassrls, rolreplication) \ + FROM pg_catalog.pg_roles WHERE rolname = '{role}'" + )) + .await; + assert_eq!(attributes, "t|f|f|f|f|f|f", "{role}"); + } + assert!( + su.flag(&format!( + "SELECT has_database_privilege('{r}', '{db}', 'CONNECT')" + )) + .await + ); + assert!( + su.flag(&format!( + "SELECT has_database_privilege('{m}', '{db}', 'CONNECT')" + )) + .await + ); + assert!( + !su.flag(&format!( + "SELECT has_database_privilege('{r}', '{db}', 'CREATE')" + )) + .await + ); + assert!( + !su.flag(&format!( + "SELECT has_database_privilege('{r}', '{db}', 'TEMPORARY')" + )) + .await, + "PUBLIC temporary access is revoked" + ); + let acl = su + .text(&format!( + "SELECT datacl::text FROM pg_catalog.pg_database WHERE datname = '{db}'" + )) + .await; + assert!( + !acl.split(',') + .any(|entry| entry.trim_start_matches('{').starts_with('=')), + "no PUBLIC entry remains: {acl}" + ); + let wants_create = matches!(product.layout, SchemaLayout::CreatedByApply); + assert_eq!( + su.flag(&format!( + "SELECT has_database_privilege('{m}', '{db}', 'CREATE')" + )) + .await, + wants_create, + "{product:?}" + ); + match &product.layout { + SchemaLayout::Owned(schemas) => { + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &db, + ) + .await; + for schema in schemas { + let owner = session + .text(&format!( + "SELECT pg_catalog.pg_get_userbyid(nspowner) FROM pg_catalog.pg_namespace \ + WHERE nspname = '{schema}'" + )) + .await; + assert_eq!(owner, m); + assert!( + !session + .flag(&format!( + "SELECT has_schema_privilege('{r}', '{schema}', 'USAGE')" + )) + .await, + "the runtime role gets nothing on {schema}" + ); + } + } + SchemaLayout::PublicForMigration => { + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &db, + ) + .await; + assert!( + session + .flag(&format!( + "SELECT has_schema_privilege('{m}', 'public', 'CREATE')" + )) + .await + ); + assert!( + !session + .flag(&format!( + "SELECT has_schema_privilege('{r}', 'public', 'CREATE')" + )) + .await + ); + } + SchemaLayout::CreatedByApply => {} + } + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn provisioned_roles_are_bound_by_forced_row_level_security() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture.provision(&Fixture::public_product()).await.unwrap(); + let migration = fixture + .server + .session( + &fixture.migration_name(), + &fixture.migration_password, + &fixture.database(), + ) + .await; + let runtime = fixture + .server + .session( + &fixture.runtime_name(), + &fixture.runtime_password, + &fixture.database(), + ) + .await; + migration + .exec("CREATE TABLE records (id int PRIMARY KEY, visible bool NOT NULL)") + .await; + migration + .exec("INSERT INTO records VALUES (1, true), (2, false)") + .await; + migration + .exec(&format!( + "GRANT SELECT ON records TO {}", + quote(&fixture.runtime_name()) + )) + .await; + migration + .exec("ALTER TABLE records ENABLE ROW LEVEL SECURITY") + .await; + migration + .exec("CREATE POLICY only_visible ON records FOR SELECT USING (visible)") + .await; + // The owner is exempt from a policy that is not forced. + assert_eq!(count_records(&migration).await, "2"); + assert_eq!(count_records(&runtime).await, "1"); + migration + .exec("ALTER TABLE records FORCE ROW LEVEL SECURITY") + .await; + // Neither role bypasses row-level security, so forcing it binds the owner too. + assert_eq!(count_records(&migration).await, "1"); + assert_eq!(count_records(&runtime).await, "1"); + let denied = runtime + .client + .batch_execute("CREATE TABLE elsewhere (id int)") + .await + .unwrap_err(); + assert_eq!(denied.code().map(|code| code.code()), Some("42501")); + drop((migration, runtime)); + fixture.cleanup().await; +} + +#[tokio::test] +async fn single_role_mode_creates_one_role() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let target = fixture.single_role_target(); + let plan = plan(&Fixture::public_product(), &target).unwrap(); + assert!(plan.single_role()); + let outcome = execute(&fixture.admin(), &plan, Mode::Converge) + .await + .unwrap(); + assert!(outcome.single_role); + assert!(outcome + .statements + .iter() + .all(|(step, _)| *step != "role.runtime")); + assert!(fixture.role_exists(&fixture.migration_name()).await); + assert!(!fixture.role_exists(&fixture.runtime_name()).await); + verify_logins(&fixture.admin(), &target).await.unwrap(); + fixture.cleanup().await; +} + +// ---- A.13 test 6 ---------------------------------------------------------- + +#[tokio::test] +async fn administrator_without_createdb_is_told_the_statement() { + let _serial = lock().await; + let fixture = Fixture::new("CREATEROLE").await; + let error = fixture + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + assert_eq!(error.step(), Some("database.create")); + match &error { + ProvisionError::StatementNeedsPrivilege { + needs, + scope, + database, + .. + } => { + assert_eq!(*needs, Needs::CreateDb); + assert_eq!(*scope, Scope::Server); + assert_eq!(database, &fixture.database()); + } + other => panic!("unexpected error {other:?}"), + } + assert_eq!( + error.to_string(), + "the administrator role cannot run CREATE DATABASE in the server; it needs CREATEDB" + ); + assert!(!fixture.database_exists().await); + fixture.cleanup().await; +} + +#[tokio::test] +async fn administrator_without_createrole_is_told_the_first_statement() { + let _serial = lock().await; + let fixture = Fixture::new("").await; + let error = fixture + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + assert_eq!(error.step(), Some("role.migration")); + assert_eq!( + error.to_string(), + "the administrator role cannot run CREATE ROLE in the server; it needs CREATEROLE" + ); + assert!(!fixture.role_exists(&fixture.migration_name()).await); + fixture.cleanup().await; +} + +// ---- A.13 test 7 ---------------------------------------------------------- + +#[tokio::test] +async fn postgis_without_superuser_names_the_extension_statement() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + let error = fixture.provision(&product).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + assert_eq!(error.step(), Some("extension.postgis")); + match &error { + ProvisionError::StatementNeedsPrivilege { + needs, + scope, + database, + .. + } => { + assert_eq!(*needs, Needs::Superuser); + assert_eq!(*scope, Scope::Database); + assert_eq!(database, &fixture.database()); + } + other => panic!("unexpected error {other:?}"), + } + assert_eq!( + error.to_string(), + format!( + "the administrator role cannot run CREATE EXTENSION postgis in database \"{}\"; \ + it needs a superuser", + fixture.database() + ) + ); + + // A superuser runs the one statement the error names, from the plan. + let plan = plan(&product, &fixture.target()).unwrap(); + let statement = plan + .statements() + .iter() + .find(|statement| statement.step == "extension.postgis") + .unwrap(); + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + session.exec(&statement.printable).await; + drop(session); + + let outcome = execute(&fixture.admin(), &plan, Mode::Converge) + .await + .unwrap(); + assert_eq!( + outcome_of(&outcome, "extension.postgis"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&outcome, "schema.owned"), + StatementOutcome::Present + ); + fixture.cleanup().await; +} + +#[tokio::test] +async fn postgis_is_created_when_the_administrator_is_a_superuser() { + let _serial = lock().await; + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + let first = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&first, "extension.postgis"), + StatementOutcome::Created + ); + assert_eq!( + outcome_of(&first, "role.spatial-bbox"), + StatementOutcome::Created + ); + let second = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&second, "extension.postgis"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&second, "role.spatial-bbox"), + StatementOutcome::Present + ); + + // An installed PostGIS below the product's minimum is named, not skipped. + let too_new = fixture.spatial_product((99, 0)); + let error = fixture.provision(&too_new).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.extension-too-old"); + assert_eq!(error.step(), Some("extension.postgis")); + fixture.cleanup().await; +} + +// ---- A.13 test 8 ---------------------------------------------------------- + +#[tokio::test] +async fn existing_role_with_other_attributes_is_refused() { + let _serial = lock().await; + let differing = [ + ("LOGIN CREATEDB", "role.migration", true), + ("LOGIN CREATEROLE", "role.migration", true), + ("LOGIN REPLICATION", "role.migration", true), + ("LOGIN BYPASSRLS", "role.migration", true), + ("LOGIN INHERIT", "role.migration", true), + ("NOLOGIN", "role.migration", true), + ("LOGIN CREATEDB", "role.runtime", false), + ]; + for (attributes, step, migration) in differing { + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let role = if migration { + fixture.migration_name() + } else { + fixture.runtime_name() + }; + let before = "SELECT concat_ws('|', rolcanlogin, rolcreatedb, rolcreaterole, rolinherit, \ + rolbypassrls, rolreplication) FROM pg_catalog.pg_roles WHERE rolname = "; + fixture + .server + .superuser + .exec(&format!("CREATE ROLE {} {attributes}", quote(&role))) + .await; + let stored = fixture + .server + .superuser + .text(&format!("{before}'{role}'")) + .await; + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!( + error.code(), + "platform.provision.role-attributes-differ", + "{attributes}" + ); + assert_eq!(error.step(), Some(step)); + assert!(error.to_string().contains(&role)); + assert_eq!( + fixture + .server + .superuser + .text(&format!("{before}'{role}'")) + .await, + stored, + "the existing role is never altered" + ); + assert!( + !fixture.database_exists().await, + "nothing runs after a refusal" + ); + fixture + .server + .superuser + .exec(&format!( + "DROP ROLE IF EXISTS {}", + quote(&fixture.migration_name()) + )) + .await; + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn existing_database_owned_by_another_role_is_refused() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture + .server + .superuser + .exec(&format!("CREATE DATABASE {}", quote(&fixture.database()))) + .await; + let acl_before = fixture + .server + .superuser + .text(&format!( + "SELECT coalesce(datacl::text, '') FROM pg_catalog.pg_database WHERE datname = '{}'", + fixture.database() + )) + .await; + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.database-owner-differs"); + assert_eq!(error.step(), Some("database.create")); + assert_eq!( + acl_before, + fixture + .server + .superuser + .text(&format!( + "SELECT coalesce(datacl::text, '') FROM pg_catalog.pg_database \ + WHERE datname = '{}'", + fixture.database() + )) + .await + ); + fixture.cleanup().await; +} + +#[tokio::test] +async fn existing_schema_owned_by_another_role_is_refused() { + let _serial = lock().await; + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + fixture + .server + .superuser + .exec(&format!("CREATE DATABASE {}", quote(&fixture.database()))) + .await; + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + session.exec("CREATE SCHEMA s2_one").await; + drop(session); + let error = fixture + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.schema-owner-differs"); + assert_eq!(error.step(), Some("schema.owned")); + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_changed_password_fails_the_login_check_for_that_role() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture.provision(&Fixture::public_product()).await.unwrap(); + verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap(); + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {} PASSWORD '{}'", + quote(&fixture.runtime_name()), + random_hex(16) + )) + .await; + // The existing role keeps its stored password, so converging reports it + // present and only the login check notices the mismatch. + let again = fixture.provision(&Fixture::public_product()).await.unwrap(); + assert_eq!( + outcome_of(&again, "role.runtime"), + StatementOutcome::Present + ); + let error = verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.role-login-failed"); + assert!(error.to_string().contains(&fixture.runtime_name())); + assert!(!error.to_string().contains(&fixture.migration_name())); + fixture.cleanup().await; +} + +// ---- A.13 test 9 ---------------------------------------------------------- + +fn unquote(identifier: &str) -> String { + identifier + .trim() + .trim_start_matches('"') + .trim_end_matches('"') + .replace("\"\"", "\"") +} + +/// Runs a printed script the way `psql` does: a `\connect` opens a new +/// session that has none of the earlier `SET`s, and `\password` sets the +/// password the administrator would have typed. +async fn run_script(fixture: &Fixture, script: &str) { + let server = &fixture.server; + let mut session = server + .session(&fixture.admin_name(), &fixture.admin_password, "postgres") + .await; + let mut pending = String::new(); + for line in script.lines() { + if pending.is_empty() && line.starts_with("--") { + continue; + } + if let Some(database) = line.strip_prefix("\\connect ") { + session = server + .session( + &fixture.admin_name(), + &fixture.admin_password, + &unquote(database), + ) + .await; + continue; + } + if let Some(role) = line.strip_prefix("\\password ") { + let role = unquote(role); + let password = if role == fixture.migration_name() { + &fixture.migration_password + } else { + &fixture.runtime_password + }; + session + .exec(&format!( + "ALTER ROLE {} PASSWORD '{password}'", + quote(&role) + )) + .await; + continue; + } + pending.push_str(line); + pending.push('\n'); + if line.ends_with(';') { + session.exec(&pending).await; + pending.clear(); + } + } + assert!(pending.is_empty(), "the script ends inside a statement"); +} + +#[tokio::test] +async fn printed_script_gives_the_same_catalog() { + let _serial = lock().await; + for product in Fixture::layouts() { + let executed = Fixture::new(NON_SUPERUSER_ADMIN).await; + executed.provision(&product).await.unwrap(); + + let scripted = Fixture::new(NON_SUPERUSER_ADMIN).await; + let script = render_script(&plan(&product, &scripted.target()).unwrap()); + run_script(&scripted, &script).await; + verify_logins(&scripted.admin(), &scripted.target()) + .await + .unwrap(); + + assert_eq!( + executed.snapshot().await, + scripted.snapshot().await, + "{product:?}" + ); + executed.cleanup().await; + scripted.cleanup().await; + } +} + +// ---- Floor ------------------------------------------------------------------ + +#[tokio::test] +async fn server_below_the_floor_is_refused_before_any_statement() { + let _serial = lock().await; + let old = Server::start("PROVISION_TEST_OLD_DATABASE_URL").await; + let version: i32 = old + .superuser + .text("SELECT current_setting('server_version_num')") + .await + .parse() + .unwrap(); + assert!(version < 170_000, "the old server must be below the floor"); + let fixture = Fixture::on(old, SUPERUSER_ADMIN).await; + let error = fixture + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.unsupported-postgres"); + assert_eq!(error.step(), None); + assert!( + error + .to_string() + .starts_with("PostgreSQL 17 or newer is required"), + "{error}" + ); + assert!(!fixture.role_exists(&fixture.migration_name()).await); + assert!(!fixture.database_exists().await); + + // Fresh mode is for a server the caller just made, and does not check. + let plan = plan(&Fixture::public_product(), &fixture.target()).unwrap(); + execute(&fixture.admin(), &plan, Mode::Fresh).await.unwrap(); + assert!(fixture.database_exists().await); + fixture.cleanup().await; +} + +// ---- A.13 test 11 ----------------------------------------------------------- + +/// Every rendering of a value the caller could print or log. +fn renderings(error: &(dyn std::error::Error + 'static)) -> Vec { + let mut texts = vec![ + format!("{error}"), + format!("{error:?}"), + format!("{error:#?}"), + ]; + let mut source = error.source(); + while let Some(cause) = source { + texts.push(format!("{cause}")); + texts.push(format!("{cause:?}")); + source = cause.source(); + } + texts +} + +fn assert_clean(texts: &[String], secrets: &[String]) { + for text in texts { + for secret in secrets { + assert!(!secret.is_empty()); + assert!(!text.contains(secret.as_str()), "a secret reached: {text}"); + } + assert!( + !text.contains("SCRAM-SHA-256$"), + "a verifier reached: {text}" + ); + assert!(!text.contains("postgresql://"), "a URL reached: {text}"); + assert!(!text.contains("PASSWORD"), "statement text reached: {text}"); + } +} + +#[tokio::test] +async fn error_text_never_contains_a_password_a_verifier_or_a_url() { + let _serial = lock().await; + let mut texts: Vec = Vec::new(); + + // A CREATE ROLE statement that carries a verifier and is refused. + let without_createrole = Fixture::new("").await; + let mut secrets = vec![ + without_createrole.admin_password.clone(), + without_createrole.migration_password.clone(), + without_createrole.runtime_password.clone(), + without_createrole.admin_url(), + ]; + let error = without_createrole + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + texts.extend(renderings(&error)); + without_createrole.cleanup().await; + + // A statement that fails on the server with a verifier in its text, and + // the verifiers the server stores. + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + secrets.extend([ + fixture.admin_password.clone(), + fixture.migration_password.clone(), + fixture.runtime_password.clone(), + fixture.admin_url(), + ]); + let success = fixture.provision(&Fixture::public_product()).await.unwrap(); + texts.push(format!("{success:?}")); + for role in [fixture.migration_name(), fixture.runtime_name()] { + secrets.push( + fixture + .server + .superuser + .text(&format!( + "SELECT rolpassword FROM pg_catalog.pg_authid WHERE rolname = '{role}'" + )) + .await, + ); + } + let plan = plan(&Fixture::public_product(), &fixture.target()).unwrap(); + texts.push(format!("{plan:?}")); + texts.push(format!("{:?}", fixture.target())); + texts.push(format!("{:?}", fixture.admin())); + texts.push(render_script(&plan)); + let error = execute(&fixture.admin(), &plan, Mode::Fresh) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-failed"); + assert_eq!(error.step(), Some("role.migration")); + texts.extend(renderings(&error)); + + // A refused existing role. + let other = Fixture::new(NON_SUPERUSER_ADMIN).await; + secrets.extend([ + other.migration_password.clone(), + other.runtime_password.clone(), + ]); + other + .server + .superuser + .exec(&format!( + "CREATE ROLE {} LOGIN CREATEDB", + quote(&other.migration_name()) + )) + .await; + let error = other + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + texts.extend(renderings(&error)); + other.cleanup().await; + + // A wrong administrator password. + let wrong = random_hex(16); + secrets.push(wrong.clone()); + let mut url = Url::parse(&fixture.admin_url()).unwrap(); + url.set_password(Some(&wrong)).unwrap(); + secrets.push(url.to_string()); + let admin = admin_config(url.as_str(), Some(&fixture.server.ca)).unwrap(); + let error = execute(&admin, &plan, Mode::Converge).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.admin-connect-failed"); + assert!(matches!( + &error, + ProvisionError::AdminConnectFailed { sqlstate: Some(state) } if state == "28P01" + )); + texts.extend(renderings(&error)); + + // A changed password. + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {} PASSWORD '{}'", + quote(&fixture.migration_name()), + random_hex(16) + )) + .await; + let error = verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap_err(); + texts.extend(renderings(&error)); + + // A URL the executor refuses to read. + let error: AdminConfigError = admin_config( + &format!("{}&sslmode=disable", fixture.admin_url()), + Some(&fixture.server.ca), + ) + .unwrap_err(); + texts.extend(renderings(&error)); + + assert_clean(&texts, &secrets); + fixture.cleanup().await; +} From 33eb28c898e1195e7227cb4ed1c6b4ba488be579 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 01:50:42 +0100 Subject: [PATCH 002/136] test: characterise token admission in every runtime with a shared token corpus test(platform): add a token fixture corpus and a driver to run it Each product decides what a provider's token reaches from its own reading of the claims. The corpus holds positive and negative token shapes from ThunderID, Keycloak, Supabase Auth and eSignet as fixtures signed at test time, with the expected result per product beside them, so a change to any verifier shows up as a cell that moved. test: characterise token admission in every runtime that verifies a token Each runtime's own verifier now runs the token fixture corpus and must give the result its column in expected.yaml records. The caller-contract work changes these results row by row, so every change is a test that moved rather than a reading of the code. Signed-off-by: Jeremi Joslin --- Cargo.lock | 6 + crates/registry-adapter/Cargo.toml | 2 +- crates/registry-adapter/src/serve.rs | 3 + .../src/serve/token_characterisation.rs | 122 ++ crates/registry-breg/Cargo.toml | 7 +- .../tests/token_characterisation.rs | 421 ++++++ crates/registry-casework/Cargo.toml | 2 +- .../tests/token_characterisation.rs | 271 ++++ crates/registry-coordinator/Cargo.toml | 2 +- crates/registry-coordinator/src/access.rs | 3 + .../src/access/token_characterisation.rs | 149 ++ crates/registry-documents/Cargo.toml | 2 +- .../tests/token_characterisation.rs | 303 +++++ crates/registry-evidence-oid4vci/Cargo.toml | 1 + .../tests/token_characterisation.rs | 197 +++ crates/registry-evidence/Cargo.toml | 1 + .../tests/token_characterisation.rs | 226 ++++ crates/registry-mcp-edge/Cargo.toml | 2 +- crates/registry-mcp-edge/src/lib.rs | 3 + .../src/token_characterisation.rs | 177 +++ crates/registry-messaging/Cargo.toml | 2 +- .../tests/token_characterisation.rs | 263 ++++ crates/registry-platform-testing/Cargo.toml | 10 + crates/registry-platform-testing/README.md | 21 + crates/registry-platform-testing/src/lib.rs | 10 + .../src/token_fixtures.rs | 1195 +++++++++++++++++ .../tests/token_fixtures.rs | 586 ++++++++ crates/registry-render/Cargo.toml | 1 + crates/registry-render/src/auth.rs | 3 + .../src/auth/token_characterisation.rs | 133 ++ crates/registry-scheduling/Cargo.toml | 2 +- .../tests/token_characterisation.rs | 226 ++++ .../platform/conformance/tokens/README.md | 114 ++ .../platform/conformance/tokens/expected.yaml | 604 +++++++++ .../tokens/fixtures/entra-id-token.json | 50 + .../tokens/fixtures/entra-v2-app-access.json | 53 + .../tokens/fixtures/entra-v2-user-access.json | 51 + .../tokens/fixtures/esignet-access-token.json | 42 + .../tokens/fixtures/esignet-id-token.json | 44 + .../tokens/fixtures/identity-only.json | 45 + .../keycloak-client-credentials-stock.json | 58 + .../fixtures/keycloak-client-credentials.json | 60 + .../tokens/fixtures/keycloak-id-token.json | 55 + .../fixtures/keycloak-refresh-token.json | 47 + .../tokens/fixtures/keycloak-user-access.json | 63 + .../tokens/fixtures/rstack-dev-run-user.json | 46 + .../fixtures/supabase-api-key-anon.json | 32 + .../fixtures/supabase-api-key-opaque.json | 16 + .../supabase-api-key-service-role.json | 32 + .../tokens/fixtures/supabase-id-token.json | 41 + .../supabase-oauth-server-user-access.json | 54 + .../tokens/fixtures/supabase-user-access.json | 55 + .../thunderid-client-credentials.json | 51 + .../tokens/fixtures/thunderid-id-token.json | 51 + .../fixtures/thunderid-user-access.json | 53 + .../tokens/token-fixture.schema.json | 143 ++ 56 files changed, 6204 insertions(+), 8 deletions(-) create mode 100644 crates/registry-adapter/src/serve/token_characterisation.rs create mode 100644 crates/registry-breg/tests/token_characterisation.rs create mode 100644 crates/registry-casework/tests/token_characterisation.rs create mode 100644 crates/registry-coordinator/src/access/token_characterisation.rs create mode 100644 crates/registry-documents/tests/token_characterisation.rs create mode 100644 crates/registry-evidence-oid4vci/tests/token_characterisation.rs create mode 100644 crates/registry-evidence/tests/token_characterisation.rs create mode 100644 crates/registry-mcp-edge/src/token_characterisation.rs create mode 100644 crates/registry-messaging/tests/token_characterisation.rs create mode 100644 crates/registry-platform-testing/src/token_fixtures.rs create mode 100644 crates/registry-platform-testing/tests/token_fixtures.rs create mode 100644 crates/registry-render/src/auth/token_characterisation.rs create mode 100644 crates/registry-scheduling/tests/token_characterisation.rs create mode 100644 products/platform/conformance/tokens/README.md create mode 100644 products/platform/conformance/tokens/expected.yaml create mode 100644 products/platform/conformance/tokens/fixtures/entra-id-token.json create mode 100644 products/platform/conformance/tokens/fixtures/entra-v2-app-access.json create mode 100644 products/platform/conformance/tokens/fixtures/entra-v2-user-access.json create mode 100644 products/platform/conformance/tokens/fixtures/esignet-access-token.json create mode 100644 products/platform/conformance/tokens/fixtures/esignet-id-token.json create mode 100644 products/platform/conformance/tokens/fixtures/identity-only.json create mode 100644 products/platform/conformance/tokens/fixtures/keycloak-client-credentials-stock.json create mode 100644 products/platform/conformance/tokens/fixtures/keycloak-client-credentials.json create mode 100644 products/platform/conformance/tokens/fixtures/keycloak-id-token.json create mode 100644 products/platform/conformance/tokens/fixtures/keycloak-refresh-token.json create mode 100644 products/platform/conformance/tokens/fixtures/keycloak-user-access.json create mode 100644 products/platform/conformance/tokens/fixtures/rstack-dev-run-user.json create mode 100644 products/platform/conformance/tokens/fixtures/supabase-api-key-anon.json create mode 100644 products/platform/conformance/tokens/fixtures/supabase-api-key-opaque.json create mode 100644 products/platform/conformance/tokens/fixtures/supabase-api-key-service-role.json create mode 100644 products/platform/conformance/tokens/fixtures/supabase-id-token.json create mode 100644 products/platform/conformance/tokens/fixtures/supabase-oauth-server-user-access.json create mode 100644 products/platform/conformance/tokens/fixtures/supabase-user-access.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-client-credentials.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-id-token.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-user-access.json create mode 100644 products/platform/conformance/tokens/token-fixture.schema.json diff --git a/Cargo.lock b/Cargo.lock index ca975408f9..2ee2299196 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7091,6 +7091,7 @@ dependencies = [ "registry-platform-ratelimit", "registry-platform-sdjwt", "registry-platform-sqlite", + "registry-platform-testing", "registry-platform-text", "registry-platform-x509", "registry-platform-yaml", @@ -7248,6 +7249,7 @@ dependencies = [ "registry-platform-oidc", "registry-platform-ratelimit", "registry-platform-sdjwt", + "registry-platform-testing", "registry-platform-yaml", "registry-thunderid-tooling", "reqwest 0.12.28", @@ -8110,12 +8112,15 @@ dependencies = [ "bytes", "futures", "jsonwebtoken", + "rand 0.9.5", "registry-platform-audit", "registry-platform-crypto", "registry-platform-httpsec", "registry-platform-httputil", "registry-platform-oidc", + "registry-platform-yaml", "reqwest 0.12.28", + "serde", "serde_json", "sha2 0.11.1", "tempfile", @@ -8211,6 +8216,7 @@ dependencies = [ "registry-platform-httputil", "registry-platform-metrics", "registry-platform-oidc", + "registry-platform-testing", "registry-platform-yaml", "registry-render-client", "reqwest 0.12.28", diff --git a/crates/registry-adapter/Cargo.toml b/crates/registry-adapter/Cargo.toml index 06ed52e255..539dfdfdb8 100644 --- a/crates/registry-adapter/Cargo.toml +++ b/crates/registry-adapter/Cargo.toml @@ -101,6 +101,6 @@ proptest.workspace = true # dependency. rcgen.workspace = true tokio-rustls.workspace = true -registry-platform-testing.workspace = true +registry-platform-testing = { workspace = true, features = ["token-fixtures"] } tempfile.workspace = true serde_norway.workspace = true diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 77f693e66b..f03ec46a64 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -998,6 +998,9 @@ fn tolerate_metrics_shutdown_timeout(result: std::io::Result<()>) -> std::io::Re } } +#[cfg(test)] +mod token_characterisation; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-adapter/src/serve/token_characterisation.rs b/crates/registry-adapter/src/serve/token_characterisation.rs new file mode 100644 index 0000000000..f07e66e7b7 --- /dev/null +++ b/crates/registry-adapter/src/serve/token_characterisation.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Characterises which identity-provider tokens the facade's real caller +//! authentication admits, against the token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Each row builds the authenticator the server builds, through +//! `serve::authenticator`, over a static key set holding the corpus signer's +//! public keys, and presents the fixture to `Authenticator::authenticate`. The +//! payment host builds its authenticator through the same function and +//! authenticates a bearer through the same method. The module sits under +//! `serve` so it can also ask the authenticator's own verifier for the check +//! that refused a token, which `CallerRefusal` does not carry. +use super::*; +use registry_platform_config::SecretProvider; +use registry_platform_testing::{ + ClaimValue, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "registry-adapter-test"; +const KEY_FILE: &str = "issuer-keys.json"; +const PLACEHOLDER_CLIENT: &str = "journey-app"; + +fn literal(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the token names, read the way the verifier reads it. +fn client_of(fixture: &TokenFixture) -> Option { + literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) +} + +fn stage_of(error: &OidcError) -> Outcome { + format!("refused/{}", error.authentication_stage().label()) + .parse() + .expect("every authentication stage label is a result value") +} + +fn runtime_for(case: &FixtureCase) -> AdapterRuntimeConfig { + let client = client_of(&case.fixture).unwrap_or_else(|| PLACEHOLDER_CLIENT.into()); + serde_json::from_value(json!({ + "id": "token-characterisation", + "endpoints": [{"endpoint": "tracker", "baseUrl": "https://tracker.example.invalid"}], + "listener": {"bind": "127.0.0.1:8080"}, + "database": { + "runtimeUrlRef": "secret:file/database-runtime", + "migrationUrlRef": "secret:file/database-migration" + }, + "oidc": { + "issuer": case.issuer, + "audience": case.audience, + "jwksSource": {"type": "static", "documentRef": format!("secret:file/{KEY_FILE}")} + }, + "allowedClients": [client], + "allowedPrivateCidrs": ["10.0.0.0/8"], + "audit": {"retentionDays": 90} + })) + .expect("the runtime configuration parses") +} + +async fn observe(authenticator: &Authenticator, token: &str) -> Outcome { + let verdict = authenticator.verifier.verify(token).await; + let admission = authenticator.authenticate(token).await; + match (admission, verdict) { + (Ok(_), Ok(_)) => Outcome::Admitted(None), + (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), + (Err(_), Err(error)) => stage_of(&error), + (Err(CallerRefusal::Unauthenticated), Ok(_)) => { + "refused/claims".parse().expect("result value") + } + (Err(CallerRefusal::Unavailable), Ok(_)) => { + "refused/unavailable".parse().expect("result value") + } + } +} + +/// The corpus public keys a static key document may hold: it admits RSA and +/// EC keys only, so the corpus's EdDSA key is left out. +fn static_key_document(signer: &TokenSigner) -> String { + let mut keys = signer.public_key_set(); + keys["keys"] + .as_array_mut() + .expect("a key set lists keys") + .retain(|key| key["kty"] != "OKP"); + keys.to_string() +} + +#[tokio::test] +async fn caller_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let root = tempfile::tempdir().expect("key directory"); + let root_path = root.path().canonicalize().expect("physical key directory"); + let key_file = root_path.join(KEY_FILE); + std::fs::write(&key_file, static_key_document(&signer)).expect("write the key set"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + } + let resolver = SecretResolver::new([SecretProvider::File], root_path).expect("resolver"); + let resolver = &resolver; + let report = corpus + .run_product_async("adapter", &signer, ISSUER, AUDIENCE, |case| async move { + let runtime = runtime_for(&case); + let authenticator = authenticator(&runtime, resolver) + .await + .expect("the authenticator builds over the static key set"); + observe(&authenticator, case.token.expose()).await + }) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran" + ); + report.assert_matches(); +} diff --git a/crates/registry-breg/Cargo.toml b/crates/registry-breg/Cargo.toml index 42da9de42b..38c108bf58 100644 --- a/crates/registry-breg/Cargo.toml +++ b/crates/registry-breg/Cargo.toml @@ -375,7 +375,7 @@ futures-core.workspace = true tempfile.workspace = true rcgen.workspace = true registry-evidence-authoring.workspace = true -registry-platform-testing = { workspace = true, features = ["test-utils"] } +registry-platform-testing = { workspace = true, features = ["test-utils", "token-fixtures"] } registry-breg-client.workspace = true tokio-rustls.workspace = true tower.workspace = true @@ -521,6 +521,11 @@ name = "issuer_portability" path = "tests/issuer_portability.rs" required-features = ["runtime"] +[[test]] +name = "token_characterisation" +path = "tests/token_characterisation.rs" +required-features = ["runtime"] + [[test]] name = "migration_plan" path = "tests/migration_plan.rs" diff --git a/crates/registry-breg/tests/token_characterisation.rs b/crates/registry-breg/tests/token_characterisation.rs new file mode 100644 index 0000000000..debaa70512 --- /dev/null +++ b/crates/registry-breg/tests/token_characterisation.rs @@ -0,0 +1,421 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runs the token fixture corpus through BReg's real authentication path and +//! asserts each result against the `breg` column of `expected.yaml`. +//! +//! The access-token verifier profile and the authority claim mapping come from +//! a runtime file parsed by `parse_runtime_config`, as at startup. The key set +//! is the signer's static public key set. A token that authenticates is sent +//! through the authenticated router to a compiled access profile, so a profile +//! refusal is observed where a request meets it. + +#![cfg(feature = "runtime")] + +use std::collections::BTreeSet; +use std::sync::Arc; + +use axum::body::Body; +use axum::http::header::AUTHORIZATION; +use axum::http::{Request, StatusCode}; +use registry_breg::api::{ + authenticated_router, HeldReadResponse, HttpService, ReadRuntimeIdentity, ReadServiceError, + ReadinessProbe, RecordReadRequest, RecordReadService, ServiceFuture, +}; +use registry_breg::auth::{AuthenticationConfigError, AuthenticationError, RegistryAuthenticator}; +use registry_breg::cursor::CursorCodec; +use registry_breg::runtime_config::parse_runtime_config; +use registry_breg::{compile_project, parse_project_yaml, CompileProfile}; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{ + Against, CapturedDiagnosticLogs, ClaimValue, Configuration, FixtureCase, Outcome, Stage, + TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::{json, Value}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber; +use zeroize::Zeroizing; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "urn:breg:test"; +const RECORD_ID: &str = "00000000-0000-4000-8000-000000000001"; +/// The client a default configuration lists when the fixture names none, so a +/// token without a client claim meets a list that does not include it. +const LISTED_CLIENT: &str = "journey-app"; +/// The scope a profile requires when the fixture carries none. +const FALLBACK_SCOPE: &str = "records:get"; + +#[tokio::test] +async fn breg_token_characterisation() { + let corpus = TokenCorpus::load().expect("the corpus loads"); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("breg", &signer, ISSUER, AUDIENCE, observe) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran, so the test proves nothing" + ); + report.assert_matches(); +} + +/// What a configuration changes in the runtime file's `authentication.oidc` +/// block, derived from the fixture the way `expected.yaml` describes. +struct Shape { + algorithm: &'static str, + access_token_type: String, + scope_claim: &'static str, + /// Empty writes `allowedClients: unrestricted`. + clients: Vec, + /// The scope the compiled access profile requires. + scope: String, + /// The client a people-only profile serves. + profile_client: String, +} + +impl Shape { + fn of(case: &FixtureCase) -> Self { + let fixture = &case.fixture; + let header = fixture.header.as_ref(); + let algorithm = match header.map(|header| header.alg.as_str()) { + Some("ES256") => "ES256", + Some("EdDSA") => "EdDSA", + _ => "RS256", + }; + let recipe = case.configuration == Configuration::Recipe; + let access_token_type = match case.configuration { + Configuration::Recipe => header + .and_then(|header| header.typ.clone()) + .unwrap_or_else(|| "at+jwt".to_owned()), + Configuration::JwtAccepted => "JWT".to_owned(), + Configuration::Default => "at+jwt".to_owned(), + }; + let scope_claim = if recipe && fixture.claims.contains_key("scp") { + "scp" + } else { + "scope" + }; + let client = literal_text(fixture, "client_id").or_else(|| literal_text(fixture, "azp")); + let clients = match (&client, recipe) { + (Some(client), _) => vec![client.clone()], + (None, true) => Vec::new(), + (None, false) => vec![LISTED_CLIENT.to_owned()], + }; + let scope = first_scope(fixture, scope_claim).unwrap_or_else(|| FALLBACK_SCOPE.to_owned()); + Self { + algorithm, + access_token_type, + scope_claim, + clients, + scope, + profile_client: client.unwrap_or_else(|| LISTED_CLIENT.to_owned()), + } + } + + fn runtime_yaml(&self, case: &FixtureCase) -> String { + let clients = if self.clients.is_empty() { + "unrestricted".to_owned() + } else { + json!(self.clients).to_string() + }; + format!( + r#" +apiVersion: id.registrystack.org/formats/breg/runtime/v1alpha1 +kind: BRegRuntimeConfig +listener: + bind: 127.0.0.1:8080 +identity: + environment: production + instanceId: registry-primary + databaseId: registry-db + databaseInitializationEnvironment: production +secretProviders: + environment: {{}} + file: + root: /var/lib/breg/secrets +database: + runtimeUrlRef: secret:env/BREG_DATABASE_URL + migrationUrlRef: secret:env/BREG_MIGRATION_DATABASE_URL + pool: + maximumConnections: 4 + waitTimeoutMilliseconds: 1000 + createTimeoutMilliseconds: 1000 + recycleTimeoutMilliseconds: 1000 + roles: + migration: registry_migration + runtime: registry_runtime +package: + root: /var/lib/breg/package +authentication: + oidc: + issuer: {issuer} + audience: {audience} + allowedAlgorithm: {algorithm} + accessTokenType: "{access_token_type}" + scopeClaim: {scope_claim} + scopeSeparator: " " + allowedClients: {clients} + maximumTokenLifetimeSeconds: 3600 + leewayMilliseconds: 60000 + authorityClaims: + principal: sub +audit: + hashKeyRef: secret:file/audit-key + path: /var/lib/breg/audit/audit.jsonl +cursor: + secretRef: secret:file/cursor-key + maximumAgeSeconds: 300 +destinations: + hooks: {{}} +operationalTimeouts: + httpRequestMilliseconds: 10000 + shutdownGraceMilliseconds: 30000 + recordLockMilliseconds: 5000 + migrationLockMilliseconds: 30000 + migrationStatementMilliseconds: 60000 +"#, + issuer = case.issuer, + audience = case.audience, + algorithm = self.algorithm, + access_token_type = self.access_token_type, + scope_claim = self.scope_claim, + ) + } + + /// A project with the one access profile the row is read against: a + /// default profile for any actor, or a profile for people only. Each + /// requires the fixture's first scope. A people-only profile names the + /// requester clients it serves, as the compiler demands. + fn project_yaml(&self, against: Against) -> String { + let profile = match against { + Against::PlainRead => format!( + " reader:\n default: true\n principalClaim: sub\n requiredScopes: [{}]\n", + self.scope + ), + Against::HumanOnlyProfile => format!( + " people:\n default: true\n principalClaim: sub\n actorKind: human\n requesterClients: [{}]\n requiredScopes: [{}]\n", + self.profile_client, self.scope + ), + }; + format!( + r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {{id: token-characterisation, version: 0.1.0, defaultLanguage: en, canonicalBaseIri: https://authoring.example.test}} +recordTypes: + case: + primaryDataset: test-dataset + route: cases + mutationMode: mutable + tombstone: false + classification: public + fields: + - {{id: label, type: string, required: true, maximumLength: 100, classification: public}} +datasets: + test-dataset: {{}} +accessProfiles: +{profile} permissions: + records: + - {{recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted}} +"# + ) + } +} + +fn literal_text(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The first scope the fixture carries in `claim`, a space-separated string or +/// a list. +fn first_scope(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => text.split(' ').next().map(str::to_owned), + Some(ClaimValue::Literal(Value::Array(items))) => { + items.first().and_then(Value::as_str).map(str::to_owned) + } + _ => None, + } +} + +async fn observe(case: FixtureCase) -> Outcome { + let shape = Shape::of(&case); + let config = parse_runtime_config(&shape.runtime_yaml(&case)) + .expect("the runtime file for this row parses"); + let registry = Arc::new( + compile_project( + &parse_project_yaml(shape.project_yaml(case.against).as_bytes()) + .expect("project parses"), + &[], + CompileProfile::Authoring, + ) + .expect("project compiles"), + ); + let keys = Arc::new(JwksFetcher::new_static( + serde_json::from_value(case.jwks.clone()).expect("the key set parses"), + JwksFetcherConfig::defaults(), + )); + let authenticator = match RegistryAuthenticator::new( + ®istry, + config.authentication().oidc().token_verifier_config(), + keys, + config.authentication().authority_claim_config(), + ) { + Ok(authenticator) => Arc::new(authenticator), + // A profile that names requester clients cannot be served by a file + // that leaves the clients unrestricted: BReg refuses to start. + Err(AuthenticationConfigError::NamedClientNotListed) => return Outcome::None, + Err(error) => panic!("the authentication block is invalid for the project: {error}"), + }; + + let logs = CapturedDiagnosticLogs::default(); + let token = case.token.expose(); + let claims = authenticator + .authenticate(token) + .with_subscriber(logs.subscriber()) + .await; + let claims = match claims { + Ok(claims) => claims, + Err( + AuthenticationError::VerificationRefused | AuthenticationError::MalformedCredential, + ) => { + return logged_stage(&logs).map_or(Outcome::Unknown, Outcome::Refused); + } + Err(AuthenticationError::MissingActorKind | AuthenticationError::InvalidClaims) => { + return Outcome::Refused(Stage::Claims); + } + }; + let kind = actor_kind_of(&format!("{claims:?}")); + + let profile = match case.against { + Against::PlainRead => "reader", + Against::HumanOnlyProfile => "people", + }; + let status = request_record(®istry, &authenticator, token, profile).await; + if status == StatusCode::OK { + Outcome::Admitted(Some(kind)) + } else { + Outcome::Refused(Stage::Profile) + } +} + +/// The stage of the one value-free diagnostic a refusal logged, when there is +/// exactly one. +fn logged_stage(logs: &CapturedDiagnosticLogs) -> Option { + let text = logs.text(); + let stages: Vec = text + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter_map(|line| line["fields"]["stage"].as_str().map(str::to_owned)) + .collect(); + match stages.as_slice() { + [stage] => Some( + format!("refused/{stage}") + .parse::() + .ok() + .and_then(|outcome| match outcome { + Outcome::Refused(stage) => Some(stage), + _ => None, + }) + .expect("the logged stage is a known stage"), + ), + _ => None, + } +} + +/// The actor kind in a `VerifiedRequestClaims` debug rendering, which prints +/// the kind and redacts every value. +fn actor_kind_of(rendered: &str) -> String { + let after = rendered + .split("actor_kind: Some(") + .nth(1) + .expect("an authenticated request carries an actor kind"); + after + .split(')') + .next() + .expect("the actor kind is closed") + .to_ascii_lowercase() +} + +async fn request_record( + registry: &Arc, + authenticator: &Arc, + token: &str, + profile: &str, +) -> StatusCode { + let service = Arc::new(HttpService::new( + Arc::clone(registry), + ReadRuntimeIdentity { + package_revision: "package-token-test".to_owned(), + schema_fingerprint: "schema-token-test".to_owned(), + }, + Arc::new(OneRecord), + Arc::new(Ready), + Arc::new( + CursorCodec::new( + Zeroizing::new(vec![0x43; 32]), + std::time::Duration::from_secs(300), + ) + .expect("the cursor key is valid"), + ), + )); + let app = authenticated_router(service, Arc::clone(authenticator)); + let request = Request::builder() + .uri(format!( + "/v1/records/cases/{RECORD_ID}?accessProfile={profile}" + )) + .header(AUTHORIZATION, format!("Bearer {token}")) + .body(Body::empty()) + .expect("request"); + app.oneshot(request) + .await + .expect("the router responds") + .status() +} + +struct OneRecord; + +impl RecordReadService for OneRecord { + fn get( + &self, + request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + let fields: BTreeSet = request.selected_fields; + Box::pin(async move { + let data: serde_json::Map = fields + .into_iter() + .map(|field| (field, json!("visible"))) + .collect(); + let record = json!({"id": RECORD_ID, "revision": 1, "data": data}); + Ok(Some( + HeldReadResponse::from_json(&record).expect("the record serializes"), + )) + }) + } + + fn list( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result> { + Box::pin(async { + Ok(HeldReadResponse::from_json(&json!({"items": []})).expect("the list serializes")) + }) + } + + fn lookup( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } +} + +struct Ready; + +impl ReadinessProbe for Ready { + fn is_ready(&self) -> ServiceFuture<'_, bool> { + Box::pin(async { true }) + } +} diff --git a/crates/registry-casework/Cargo.toml b/crates/registry-casework/Cargo.toml index a0e4a4851f..b0e7cf2fff 100644 --- a/crates/registry-casework/Cargo.toml +++ b/crates/registry-casework/Cargo.toml @@ -79,7 +79,7 @@ registry-casework-client.workspace = true registry-breg-client.workspace = true registry-review-client.workspace = true registry-bregctl.workspace = true -registry-platform-testing = { workspace = true, features = ["test-utils", "migration-pins"] } +registry-platform-testing = { workspace = true, features = ["test-utils", "migration-pins", "token-fixtures"] } tempfile.workspace = true tower.workspace = true wiremock.workspace = true diff --git a/crates/registry-casework/tests/token_characterisation.rs b/crates/registry-casework/tests/token_characterisation.rs new file mode 100644 index 0000000000..c50213ad15 --- /dev/null +++ b/crates/registry-casework/tests/token_characterisation.rs @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runs the token fixture corpus through Casework's real authentication path +//! and asserts each result against the `casework` column of `expected.yaml`. +//! +//! The access-token verifier profile and the key source come from a runtime +//! file parsed by `RuntimeConfig::loader` and built by +//! `RuntimeConfig::oidc_verifier`, as at startup, with the signer's public +//! keys served as a static key set. Casework verifies RS256 and ES256 only, so +//! the key set the file points at holds those two keys. + +use std::path::Path; +use std::sync::Arc; + +use registry_casework::{ + secret_resolver, AuthenticationError, CaseworkAuthenticator, RuntimeConfig, +}; +use registry_casework_core::{ + AccessProfile, CaseworkActsAs, CaseworkProject, InboxPolicy, ProjectIdentity, QueuePolicy, + CASEWORK_API_VERSION, CASEWORK_KIND, +}; +use registry_platform_oidc::JwksFetcher; +use registry_platform_testing::{ + Against, CapturedDiagnosticLogs, ClaimValue, Configuration, FixtureCase, Outcome, Stage, + TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::{json, Value}; +use tracing::instrument::WithSubscriber; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "urn:casework:test"; +/// The client a default configuration lists when the fixture names none, so a +/// token without a client claim meets a list that does not include it. +const LISTED_CLIENT: &str = "journey-app"; +/// The scope a profile requires when the fixture carries none. +const FALLBACK_SCOPE: &str = "records:get"; +const JWKS_FILE: &str = "oidc-jwks"; + +#[tokio::test] +async fn casework_token_characterisation() { + let corpus = TokenCorpus::load().expect("the corpus loads"); + let signer = TokenSigner::new(); + let root = tempfile::tempdir().expect("temporary directory"); + let secrets = Secrets::write(root.path(), &signer.public_key_set()); + let report = corpus + .run_product_async("casework", &signer, ISSUER, AUDIENCE, |case| { + observe(case, &secrets) + }) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran, so the test proves nothing" + ); + report.assert_matches(); +} + +/// The directory the runtime file's `file` secret provider reads, holding the +/// static key set. +struct Secrets { + root: std::path::PathBuf, +} + +impl Secrets { + fn write(root: &Path, public_keys: &Value) -> Self { + use std::os::unix::fs::PermissionsExt as _; + let root = std::fs::canonicalize(root).expect("canonical root"); + let directory = root.join("secrets"); + std::fs::create_dir(&directory).expect("secrets directory"); + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)) + .expect("private secrets directory"); + // The runtime refuses a static key set that holds an OKP key, and it + // verifies RS256 and ES256 only. + let keys: Vec<&Value> = public_keys["keys"] + .as_array() + .expect("the key set lists keys") + .iter() + .filter(|key| matches!(key["kty"].as_str(), Some("RSA" | "EC"))) + .collect(); + let file = directory.join(JWKS_FILE); + std::fs::write(&file, json!({ "keys": keys }).to_string()).expect("key set file"); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)) + .expect("private key set file"); + Self { root } + } +} + +/// What a configuration changes in the runtime file's `authentication.oidc` +/// block, derived from the fixture the way `expected.yaml` describes. +struct Shape { + /// `None` leaves `scopeClaim` out, as the runner's own file does. + scope_claim: Option<&'static str>, + /// Empty writes `allowedClients: unrestricted`. + clients: Vec, + /// The scope the access profile requires. + scope: String, +} + +impl Shape { + fn of(case: &FixtureCase) -> Self { + let fixture = &case.fixture; + let recipe = case.configuration == Configuration::Recipe; + let scope_claim = match (recipe, fixture.claims.contains_key("scp")) { + (true, true) => Some("scp"), + (true, false) => Some("scope"), + (false, _) => None, + }; + let client = literal_text(fixture, "client_id").or_else(|| literal_text(fixture, "azp")); + let clients = match (client, recipe) { + (Some(client), _) => vec![client], + (None, true) => Vec::new(), + (None, false) => vec![LISTED_CLIENT.to_owned()], + }; + let scope = first_scope(fixture, scope_claim.unwrap_or("registry_scopes")) + .unwrap_or_else(|| FALLBACK_SCOPE.to_owned()); + Self { + scope_claim, + clients, + scope, + } + } + + fn runtime_yaml(&self, case: &FixtureCase, root: &Path) -> String { + let clients = if self.clients.is_empty() { + "unrestricted".to_owned() + } else { + json!(self.clients).to_string() + }; + let scope_claim = self + .scope_claim + .map(|claim| format!(" scopeClaim: {claim}\n")) + .unwrap_or_default(); + format!( + "apiVersion: id.registrystack.org/formats/casework/runtime/v1alpha1 +kind: CaseworkRuntimeConfig +identity: {{databaseId: casework-token-test}} +package: {{root: {root}/package}} +listener: {{bind: \"127.0.0.1:8100\", tlsTermination: development-loopback}} +secretProviders: {{file: {{root: {root}/secrets}}, environment: {{}}}} +database: {{runtimeUrlRef: secret:env/RUNTIME, migrationUrlRef: secret:env/MIGRATION}} +authentication: + oidc: + issuer: {issuer} + audience: {audience} + allowedClients: {clients} +{scope_claim} jwksSource: {{type: static, documentRef: secret:file/{JWKS_FILE}}} +audit: {{path: {root}/audit.ndjson, hashKeyRef: secret:file/audit}} +contextProviders: {{}} +", + root = root.display(), + issuer = case.issuer, + audience = case.audience, + ) + } + + /// A project with a Requester profile, which a service identity may use, + /// and a Staff profile, which only a person may use. Each requires the + /// fixture's first scope. + fn project(&self) -> CaseworkProject { + let starter = CaseworkProject::from_slice(include_bytes!( + "../../../products/casework/examples/standalone-decision/casework.yaml" + )) + .expect("canonical review fixture"); + let profile = |id: &str, acts_as| AccessProfile { + id: id.to_owned(), + label: None, + description: None, + principal_claim: "sub".to_owned(), + required_scopes: vec![self.scope.clone()], + acts_as, + }; + CaseworkProject { + task_templates: Vec::new(), + api_version: CASEWORK_API_VERSION.to_owned(), + kind: CASEWORK_KIND.to_owned(), + project: ProjectIdentity::new( + "token-characterisation".parse().expect("project id"), + "1".to_owned(), + ), + access_profiles: vec![ + profile("requester", CaseworkActsAs::Requester), + profile("staff", CaseworkActsAs::Staff), + ], + queues: vec![QueuePolicy { + id: "decisions".to_owned(), + label: "Decisions".to_owned(), + }], + teams: starter.teams, + context_providers: Vec::new(), + review_policies: starter.review_policies, + trusted_producers: starter.trusted_producers, + calendars: Vec::new(), + clocks: Vec::new(), + inbox: InboxPolicy::default(), + } + } +} + +fn literal_text(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The first scope the fixture carries in `claim`, a space-separated string or +/// a list. +fn first_scope(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => text.split(' ').next().map(str::to_owned), + Some(ClaimValue::Literal(Value::Array(items))) => { + items.first().and_then(Value::as_str).map(str::to_owned) + } + _ => None, + } +} + +async fn observe(case: FixtureCase, secrets: &Secrets) -> Outcome { + let shape = Shape::of(&case); + let config = RuntimeConfig::loader() + .parse_str::(&shape.runtime_yaml(&case, &secrets.root), |_| None) + .expect("the runtime file for this row parses") + .config; + let resolver = secret_resolver(&config).expect("the secret providers resolve"); + let (verifier, keys): (_, Arc) = config + .oidc_verifier(&resolver) + .await + .expect("the verifier profile builds"); + let authenticator = CaseworkAuthenticator::new( + &shape.project(), + verifier, + keys, + config.authentication.oidc.human_identity.clone(), + ); + + let profile = match case.against { + Against::PlainRead => "requester", + Against::HumanOnlyProfile => "staff", + }; + let logs = CapturedDiagnosticLogs::default(); + let result = authenticator + .authenticate(case.token.expose(), profile) + .with_subscriber(logs.subscriber()) + .await; + match result { + Ok(_) => Outcome::Admitted(None), + Err(AuthenticationError::Claims) => Outcome::Refused(Stage::Claims), + Err( + AuthenticationError::Refused + | AuthenticationError::Profile + | AuthenticationError::NotHuman, + ) => logged_stage(&logs).map_or(Outcome::Unknown, Outcome::Refused), + } +} + +/// The stage of the one value-free diagnostic a refusal logged, when there is +/// exactly one. +fn logged_stage(logs: &CapturedDiagnosticLogs) -> Option { + let text = logs.text(); + let stages: Vec = text + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter_map(|line| line["fields"]["stage"].as_str().map(str::to_owned)) + .collect(); + match stages.as_slice() { + [stage] => match format!("refused/{stage}").parse::() { + Ok(Outcome::Refused(stage)) => Some(stage), + other => panic!("the logged stage is not a known stage: {other:?}"), + }, + _ => None, + } +} diff --git a/crates/registry-coordinator/Cargo.toml b/crates/registry-coordinator/Cargo.toml index 06f1149aa4..e65479cc8a 100644 --- a/crates/registry-coordinator/Cargo.toml +++ b/crates/registry-coordinator/Cargo.toml @@ -185,7 +185,7 @@ zeroize.workspace = true [dev-dependencies] tokio = { workspace = true, features = ["test-util"] } -registry-platform-testing = { workspace = true, features = ["test-utils", "test-authorization-server", "migration-pins"] } +registry-platform-testing = { workspace = true, features = ["test-utils", "test-authorization-server", "migration-pins", "token-fixtures"] } tempfile.workspace = true tower.workspace = true wiremock.workspace = true diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index dce0a4eea2..c8e05f3a53 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -556,6 +556,9 @@ impl Serialize for AccessConfig { } } +#[cfg(test)] +mod token_characterisation; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-coordinator/src/access/token_characterisation.rs b/crates/registry-coordinator/src/access/token_characterisation.rs new file mode 100644 index 0000000000..24d799d920 --- /dev/null +++ b/crates/registry-coordinator/src/access/token_characterisation.rs @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Characterises which identity-provider tokens the Coordinator's real caller +//! authentication admits, against the token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Each row builds the authenticator the server builds, through +//! `AccessConfig::authenticator`, over a static key set holding the corpus +//! signer's public keys, and presents the fixture to `Authenticator::authenticate`. +//! The module sits under `access` so it can also ask the authenticator's own +//! verifier for the check that refused a token: the service answers every +//! refusal with `access.unauthenticated`, which names no check. +use super::*; +use registry_platform_oidc::OidcError; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, +}; +use registry_platform_yaml::Url; +use serde_json::Value; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "urn:coordinator:test"; +const KEY_FILE: &str = "issuer-keys.json"; +const PLACEHOLDER_CLIENT: &str = "journey-app"; +const PLACEHOLDER_SUBJECT: &str = "placeholder-subject"; +const PLACEHOLDER_SCOPE: &str = "records:get"; + +fn literal(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the token names, read the way the verifier reads it. +fn client_of(fixture: &TokenFixture) -> Option { + literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) +} + +fn first_scope(fixture: &TokenFixture) -> Option { + literal(fixture, "scope")? + .split_whitespace() + .next() + .map(str::to_owned) +} + +fn stage_of(error: &OidcError) -> Outcome { + format!("refused/{}", error.authentication_stage().label()) + .parse() + .expect("every authentication stage label is a result value") +} + +async fn authenticator_for(case: &FixtureCase, secrets: &SecretProvidersConfig) -> Authenticator { + let scope_claim = match case.configuration { + Configuration::Recipe => "scope", + _ => "registry_scopes", + }; + let policy = ClientPolicy { + subjects: vec![literal(&case.fixture, "sub").unwrap_or_else(|| PLACEHOLDER_SUBJECT.into())], + required_scopes: vec![ + first_scope(&case.fixture).unwrap_or_else(|| PLACEHOLDER_SCOPE.into()) + ], + workflows: vec!["follow-up".into()], + actions: vec![Action::Start, Action::Status], + operator: false, + }; + let client = client_of(&case.fixture).unwrap_or_else(|| PLACEHOLDER_CLIENT.into()); + let access = AccessConfig { + issuer: OidcIssuerConfig { + issuer: Url::new(case.issuer.clone()).expect("issuer URL"), + audience: case.audience.clone(), + jwks_source: JwksSource::Static { + document_ref: format!("secret:file/{KEY_FILE}"), + }, + allow_insecure_http: false, + }, + assertion_issuers: BTreeMap::new(), + scope_claim: scope_claim.into(), + policies: BTreeMap::from([(client, policy)]), + }; + access + .authenticator(secrets, false) + .await + .expect("the authenticator builds over the static key set") +} + +async fn observe(authenticator: &Authenticator, token: &str) -> Outcome { + let verdict = authenticator.verifier.verify(token).await; + let admission = authenticator.authenticate(token).await; + match (admission, verdict) { + (Ok(_), Ok(_)) => Outcome::Admitted(None), + (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), + (Err(_), Err(error)) => stage_of(&error), + (Err(error), Ok(_)) => match error.code.as_str() { + "access.denied" => "refused/scope".parse().expect("result value"), + "access.unauthenticated" => "refused/claims".parse().expect("result value"), + "access.unavailable" => "refused/unavailable".parse().expect("result value"), + other => panic!("authenticate refused with the unexpected code {other}"), + }, + } +} + +/// The corpus public keys a static key document may hold: it admits RSA and +/// EC keys only, so the corpus's EdDSA key is left out. +fn static_key_document(signer: &TokenSigner) -> String { + let mut keys = signer.public_key_set(); + keys["keys"] + .as_array_mut() + .expect("a key set lists keys") + .retain(|key| key["kty"] != "OKP"); + keys.to_string() +} + +#[tokio::test] +async fn caller_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let root = tempfile::tempdir().expect("key directory"); + let root_path = root.path().canonicalize().expect("physical key directory"); + let key_file = root_path.join(KEY_FILE); + std::fs::write(&key_file, static_key_document(&signer)).expect("write the key set"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + } + let secrets = SecretProvidersConfig { + file: Some(registry_platform_config::FileSecretProviderConfig { root: root_path }), + environment: None, + }; + let secrets = &secrets; + let report = corpus + .run_product_async( + "coordinator", + &signer, + ISSUER, + AUDIENCE, + |case| async move { + let authenticator = authenticator_for(&case, secrets).await; + observe(&authenticator, case.token.expose()).await + }, + ) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran" + ); + report.assert_matches(); +} diff --git a/crates/registry-documents/Cargo.toml b/crates/registry-documents/Cargo.toml index 8d3e3c5f94..a6d0b44bfa 100644 --- a/crates/registry-documents/Cargo.toml +++ b/crates/registry-documents/Cargo.toml @@ -110,7 +110,7 @@ aws-lc-rs.workspace = true base64.workspace = true jsonschema.workspace = true registry-documents-client.workspace = true -registry-platform-testing = { workspace = true, features = ["migration-pins"] } +registry-platform-testing = { workspace = true, features = ["migration-pins", "token-fixtures"] } reqwest.workspace = true serde_norway.workspace = true tempfile.workspace = true diff --git a/crates/registry-documents/tests/token_characterisation.rs b/crates/registry-documents/tests/token_characterisation.rs new file mode 100644 index 0000000000..be42b0b8c7 --- /dev/null +++ b/crates/registry-documents/tests/token_characterisation.rs @@ -0,0 +1,303 @@ +#![allow( + clippy::disallowed_methods, + reason = "tests read back the YAML the code under test wrote, or a published contract or fixture, to assert on it; they read no operator configuration" +)] +// SPDX-License-Identifier: Apache-2.0 + +//! Characterisation of the Document Store's bearer authentication against the +//! token fixture corpus (`products/platform/conformance/tokens`). +//! +//! Every row of `expected.yaml` with a `documents` cell is run through the +//! authenticator the server builds: the verifier profile comes from a +//! `RuntimeConfig` loaded from a runtime file, the keys from that file's static +//! key source, the access profiles from a project package, and the credential +//! goes through `DocumentsAuthenticator::authenticate`. No database is involved. +//! +//! The project package is the published starter with its `staff` access profile +//! rewritten for the row: the fixture's client, the first scope the fixture +//! carries, and the actor kind the fixture declares (`human` when it declares +//! none, or when the row selects the human-only profile). +//! +//! The authenticator reports a verifier refusal as one error. The stage of that +//! refusal is read by running the same token through a second verifier built +//! from the same configuration and keys, so the stage is the shared verifier's +//! own label. + +use std::collections::BTreeMap; +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; + +use registry_documents::auth::{AuthenticationError, DocumentsAuthenticator}; +use registry_documents::config::RuntimeConfig; +use registry_documents::package::{package_limits, PACKAGE_COMMAND, PROJECT_FILE}; +use registry_documents_core::{AccessProfiles, DocumentsProject}; +use registry_platform_config::write_package; +use registry_platform_oidc::TokenVerifier; +use registry_platform_testing::{ + Against, ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://identity.example.test"; +const AUDIENCE: &str = "urn:example:documents"; +/// The client a fixture without a client claim is configured against: the +/// allowed list always holds one client, as the runtime requires. +const PLACEHOLDER_CLIENT: &str = "journey-app"; +const PLACEHOLDER_SCOPE: &str = "records:get"; +/// The clients the starter's other access profiles name. The allowed list +/// keeps them so every profile of the package resolves a client. +const STARTER_CLIENTS: [&str; 4] = [ + "civil-registry-app", + "citizen-portal", + "partner-portal", + "partner-service", +]; +const STARTER_PROJECT: &str = + include_str!("../../../products/documents/examples/starter/documents.yaml"); + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the fixture names, from `client_id` or `azp`. +fn fixture_client(case: &FixtureCase) -> String { + literal_string(case, "client_id") + .or_else(|| literal_string(case, "azp")) + .unwrap_or_else(|| PLACEHOLDER_CLIENT.to_owned()) +} + +/// The claim the configuration reads scopes from. +fn scope_claim(case: &FixtureCase) -> &'static str { + if case.configuration == Configuration::Recipe + && case.fixture.claims.contains_key("scp") + && !case.fixture.claims.contains_key("scope") + { + "scp" + } else { + "scope" + } +} + +/// The first scope the fixture carries in the claim the configuration names. +fn read_scope(case: &FixtureCase, claim: &str) -> String { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => text.split_whitespace().next(), + Some(ClaimValue::Literal(Value::Array(items))) => items.first().and_then(Value::as_str), + _ => None, + } + .unwrap_or(PLACEHOLDER_SCOPE) + .to_owned() +} + +/// The actor kind the profile admits: the one the fixture declares when it is +/// a kind the Document Store has, and `human` otherwise or when the row +/// selects the human-only profile. +fn profile_actor_kind(case: &FixtureCase) -> &'static str { + if case.against == Against::HumanOnlyProfile { + return "human"; + } + match literal_string(case, "registry_actor_kind").as_deref() { + Some("service") => "service", + _ => "human", + } +} + +fn write_private(path: &Path, bytes: &[u8]) { + fs::write(path, bytes).expect("write a private file"); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("restrict the file"); +} + +/// The key set a static key source accepts: it refuses a set holding any key +/// that is not RSA or EC, so the corpus's EdDSA key stays out of the file. No +/// admitted algorithm uses it. +fn static_key_set(jwks: &Value) -> Value { + let keys: Vec = jwks["keys"] + .as_array() + .expect("a key set with a keys array") + .iter() + .filter(|key| matches!(key["kty"].as_str(), Some("RSA" | "EC"))) + .cloned() + .collect(); + json!({ "keys": keys }) +} + +/// The starter project with its `staff` profile rewritten for the row. +fn project_text(client: &str, scope: &str, kind: &str) -> String { + let mut project: Value = serde_norway::from_str(STARTER_PROJECT).expect("the starter parses"); + let staff = project + .pointer_mut("/accessProfiles/staff") + .expect("the starter has a staff access profile"); + staff["requesterClients"] = json!([client]); + staff["requiredScopes"] = json!([scope]); + staff["actorKind"] = json!(kind); + serde_norway::to_string(&project).expect("the project serialises") +} + +fn refusal(stage_label: &str) -> Outcome { + format!("refused/{stage_label}") + .parse() + .expect("a stage the corpus knows") +} + +async fn observe(case: FixtureCase) -> Outcome { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a runtime directory"); + let secrets = root.path().join("secrets"); + fs::create_dir(&secrets).expect("a secrets directory"); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).expect("restrict secrets"); + write_private( + &secrets.join("jwks.json"), + &serde_json::to_vec(&static_key_set(&case.jwks)).expect("a key set"), + ); + // The database is never contacted: only the key source and the verifier + // profile are built from this runtime file. + write_private( + &secrets.join("database-url"), + b"postgresql://corpus@127.0.0.1:1/corpus", + ); + write_private( + &secrets.join("audit-key"), + b"documents-corpus-audit-key-0123456789", + ); + write_private( + &secrets.join("hook-key"), + b"documents-corpus-hook-key-0123456789", + ); + + let claim = scope_claim(&case); + let scope = read_scope(&case, claim); + let client = fixture_client(&case); + let project = project_text(&client, &scope, profile_actor_kind(&case)); + let package = root.path().join("package"); + write_package( + &package, + &BTreeMap::from([(PROJECT_FILE.to_owned(), project.clone().into_bytes())]), + None, + &package_limits(), + PACKAGE_COMMAND, + ) + .expect("the package for the row"); + + let mut allowed = vec![client]; + allowed.extend(STARTER_CLIENTS.map(str::to_owned)); + let runtime_path = root.path().join("runtime.yaml"); + fs::write( + &runtime_path, + format!( + "\ +apiVersion: id.registrystack.org/formats/documents/runtime/v1alpha1 +kind: DocumentsRuntimeConfig +identity: + databaseId: token-characterisation +package: + root: {package} +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback + networkExposure: private-address +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/database-url + migrationUrlRef: secret:file/database-url +authentication: + oidc: + issuer: {issuer} + audience: {audience} + scopeClaim: {claim} + allowedClients: {allowed} + jwksSource: + type: static + documentRef: secret:file/jwks.json +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/audit-key +storage: + type: database +contentVerification: + type: disabled +cleanup: + erasure: active +destinations: + hooks: + owning-system-events: + url: http://127.0.0.1:9/document-events + hmacSha256KeyRef: secret:file/hook-key + attemptTimeoutMilliseconds: 1000 + maximumAttempts: 2 +", + package = package.display(), + secrets = secrets.display(), + issuer = case.issuer, + audience = case.audience, + allowed = serde_json::to_string(&allowed).expect("a client list"), + audit = root.path().join("audit.ndjson").display(), + ), + ) + .expect("write the runtime file"); + let config = RuntimeConfig::load(&runtime_path).expect("the runtime configuration loads"); + let resolver = config.secret_resolver().expect("the secret resolver"); + let keys = config + .jwks_fetcher(&resolver) + .await + .expect("the static key source"); + let decoded = DocumentsProject::decode(PROJECT_FILE, project.as_bytes()) + .expect("the rewritten project decodes") + .value; + + let authenticator = DocumentsAuthenticator::new( + config.verifier_profile(), + keys.clone(), + AccessProfiles::new(&decoded), + config.binds_assertion_issuers(), + ); + let token = case.token.expose(); + match authenticator.authenticate(token).await { + Ok(caller) => Outcome::Admitted(Some(caller.kind.as_str().to_owned())), + Err(AuthenticationError::Claims) => refusal("claims"), + Err(AuthenticationError::Unavailable) => refusal("unavailable"), + Err(error @ (AuthenticationError::Refused | AuthenticationError::Profile)) => { + let reference = TokenVerifier::new(config.verifier_profile(), keys); + match reference.verify(token).await { + Err(failure) => refusal(failure.authentication_stage().label()), + Ok(verified) if error == AuthenticationError::Profile => { + if verified.scopes.iter().any(|held| held == &scope) { + refusal("profile") + } else { + refusal("scope") + } + } + // The credential is not a compact access token, so the + // verifier is never reached. + Ok(_) => refusal("header"), + } + } + } +} + +#[tokio::test] +async fn documents_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("documents", &signer, ISSUER, AUDIENCE, observe) + .await + .expect("every documents row is planned and signed"); + let run = report + .rows + .iter() + .filter(|row| row.observed.is_some()) + .count(); + assert!(run > 0, "no documents row ran"); + eprintln!( + "documents: {run} rows ran, {} differ", + report.mismatches().len() + ); + report.assert_matches(); +} diff --git a/crates/registry-evidence-oid4vci/Cargo.toml b/crates/registry-evidence-oid4vci/Cargo.toml index 79687e89cf..88573bbbfb 100644 --- a/crates/registry-evidence-oid4vci/Cargo.toml +++ b/crates/registry-evidence-oid4vci/Cargo.toml @@ -76,6 +76,7 @@ axum-test.workspace = true ed25519-dalek.workspace = true jsonschema.workspace = true p256.workspace = true +registry-platform-testing = { workspace = true, features = ["token-fixtures"] } registry-thunderid-tooling = { workspace = true, features = ["session"] } reqwest.workspace = true tempfile.workspace = true diff --git a/crates/registry-evidence-oid4vci/tests/token_characterisation.rs b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs new file mode 100644 index 0000000000..be1e1d691d --- /dev/null +++ b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs @@ -0,0 +1,197 @@ +//! Characterises the Evidence OID4VCI offer endpoint's access-token +//! authentication against the shared token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Every row of `expected.yaml` with an `evidence-oid4vci` cell runs through +//! `MintResourceServer::from_config`, the constructor the server calls, with +//! the issuer key set served over HTTP from a loopback listener. +//! +//! `OfferAuthorizer::authorize` collapses every verifier refusal into one +//! error, so the refusal stage is named by a second verifier built from the +//! exported `verifier_profile` over the same configuration. It is consulted +//! only after the real resource server has refused. + +use std::sync::Arc; + +use axum::{routing::get, Json, Router}; +use jsonwebtoken::jwk::JwkSet; +use registry_evidence_oid4vci::{ + authorizer::{verifier_profile, AuthorizationError, MintResourceServer, OfferAuthorizer}, + config::{AccessTokenAlgorithm, OfferAuthorizationConfig, Restriction, ValidationMode}, +}; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier}; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, Stage, TokenCorpus, TokenSigner, +}; +use serde_json::Value; + +/// The audience the product under test is configured with. +const PRODUCT_AUDIENCE: &str = "evidence-oid4vci-fixture"; + +/// The client the `default` configuration admits when a fixture names none, +/// and the scope the `recipe` configuration requires when a fixture carries +/// none. +const FALLBACK_CLIENT: &str = "journey-app"; +const FALLBACK_SCOPE: &str = "oid4vci:offer"; + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +fn fixture_client(case: &FixtureCase) -> Option { + literal_string(case, "client_id").or_else(|| literal_string(case, "azp")) +} + +/// The first scope the fixture carries, read from `scope` or `scp`. +fn first_scope(case: &FixtureCase) -> Option { + if let Some(scope) = literal_string(case, "scope") { + return scope.split_whitespace().next().map(str::to_owned); + } + match case.fixture.claims.get("scp") { + Some(ClaimValue::Literal(Value::String(scope))) => { + scope.split_whitespace().next().map(str::to_owned) + } + Some(ClaimValue::Literal(Value::Array(scopes))) => { + scopes.first().and_then(Value::as_str).map(str::to_owned) + } + _ => None, + } +} + +/// The algorithm the offer boundary is configured with for the row: the +/// fixture's own where the product admits it, and ES256 otherwise. +fn configured_algorithm(case: &FixtureCase) -> AccessTokenAlgorithm { + match case + .fixture + .header + .as_ref() + .map(|header| header.alg.as_str()) + { + Some("RS256") => AccessTokenAlgorithm::RS256, + Some("EdDSA") => AccessTokenAlgorithm::EdDSA, + _ => AccessTokenAlgorithm::ES256, + } +} + +fn row_config(case: &FixtureCase, jwks_uri: &str) -> OfferAuthorizationConfig { + let allowed_clients = match (case.configuration, fixture_client(case)) { + (Configuration::Default, client) => { + Restriction::Listed(vec![client.unwrap_or_else(|| FALLBACK_CLIENT.to_owned())]) + } + (_, Some(client)) => Restriction::Listed(vec![client]), + (_, None) => Restriction::Unrestricted, + }; + let required_scopes = match case.configuration { + Configuration::Default => Restriction::Unrestricted, + _ => Restriction::Listed(vec![ + first_scope(case).unwrap_or_else(|| FALLBACK_SCOPE.to_owned()) + ]), + }; + OfferAuthorizationConfig { + claims: Default::default(), + issuer: case.issuer.clone(), + jwks_uri: jwks_uri.to_owned(), + allow_insecure_http: true, + audiences: vec![case.audience.clone()], + algorithms: vec![configured_algorithm(case)], + allowed_clients, + required_scopes, + maximum_token_lifetime_seconds: 86_400, + } +} + +/// Serve the signer's public key set from a loopback listener and return the +/// origin, which doubles as the issuer. +async fn serve_key_set(key_set: Value) -> String { + let app = Router::new().route( + "/jwks.json", + get(move || { + let key_set = key_set.clone(); + async move { Json(key_set) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("a loopback port is free"); + let port = listener + .local_addr() + .expect("the listener has an address") + .port(); + tokio::spawn(async move { + axum::serve(listener, app) + .await + .expect("the key set server runs for the test"); + }); + format!("http://127.0.0.1:{port}") +} + +/// The stage at which the shared verifier, under the product's own profile, +/// refuses the token. A token it admits is refused by the product's scope gate +/// or by its own claim rules. +async fn refusal_stage(config: &OfferAuthorizationConfig, case: &FixtureCase) -> Stage { + let jwks: JwkSet = serde_json::from_value(case.jwks.clone()).expect("the key set parses"); + let verifier = TokenVerifier::new( + verifier_profile(config), + Arc::new(JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults())), + ); + match verifier.verify(case.token.expose()).await { + Err(error) => { + let label = error.authentication_stage().label(); + match format!("refused/{label}").parse::() { + Ok(Outcome::Refused(stage)) => stage, + other => panic!("the verifier stage `{label}` is not a corpus stage: {other:?}"), + } + } + Ok(verified) => { + let present: Vec<&str> = verified.scopes.iter().map(String::as_str).collect(); + let scope_missing = config + .required_scopes + .items() + .iter() + .any(|scope| !present.contains(&scope.as_str())); + if scope_missing { + Stage::Scope + } else { + Stage::Claims + } + } + } +} + +async fn authorize(case: FixtureCase, key_set_uri: String) -> Outcome { + let config = row_config(&case, &key_set_uri); + let server = + MintResourceServer::from_config(&config, ValidationMode::SupervisedLocalDevelopment); + match server.authorize(case.token.expose()).await { + Ok(_) => Outcome::Admitted(None), + Err(AuthorizationError::Missing) => Outcome::Refused(Stage::Header), + Err(AuthorizationError::KeySource) => Outcome::Refused(Stage::Unavailable), + Err(AuthorizationError::Refused) => Outcome::Refused(refusal_stage(&config, &case).await), + } +} + +#[tokio::test] +async fn evidence_oid4vci_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let origin = serve_key_set(signer.public_key_set()).await; + let key_set_uri = format!("{origin}/jwks.json"); + let report = corpus + .run_product_async( + "evidence-oid4vci", + &signer, + &origin, + PRODUCT_AUDIENCE, + |case| authorize(case, key_set_uri.clone()), + ) + .await + .expect("the corpus runs for evidence-oid4vci"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran through the offer boundary" + ); + report.assert_matches(); +} diff --git a/crates/registry-evidence/Cargo.toml b/crates/registry-evidence/Cargo.toml index c020bd7e07..09bbbe1829 100644 --- a/crates/registry-evidence/Cargo.toml +++ b/crates/registry-evidence/Cargo.toml @@ -99,6 +99,7 @@ rcgen.workspace = true registry-evidence-authoring.workspace = true registry-evidence-presentation.workspace = true registry-platform-crypto = { workspace = true, features = ["test-support", "transit"] } +registry-platform-testing = { workspace = true, features = ["token-fixtures"] } serde_norway.workspace = true tokio-rustls.workspace = true wiremock.workspace = true diff --git a/crates/registry-evidence/tests/token_characterisation.rs b/crates/registry-evidence/tests/token_characterisation.rs new file mode 100644 index 0000000000..e5f2269933 --- /dev/null +++ b/crates/registry-evidence/tests/token_characterisation.rs @@ -0,0 +1,226 @@ +//! Characterises Evidence's access-token authentication against the shared +//! token fixture corpus in `products/platform/conformance/tokens`. +//! +//! Every row of `expected.yaml` with an `evidence` cell runs through +//! `Authenticator::from_config`, the constructor the server calls, with the +//! issuer key set served over HTTP from a loopback listener. The row's +//! configuration is expressed through the bundle's own authentication members. +//! +//! `Authenticator::authenticate` collapses every verifier refusal into one +//! error, so the refusal stage is named by a second verifier built from the +//! same bundle members. It is consulted only after the real authenticator has +//! refused, and a disagreement between the two fails the test. + +use std::{collections::HashSet, sync::Arc, time::Duration}; + +use axum::{routing::get, Json, Router}; +use jsonwebtoken::{jwk::JwkSet, Algorithm}; +use registry_evidence::{ + auth::{AuthenticationError, Authenticator}, + config::{ + AccessTokenAlgorithm, AccessTokenType, AdmissionGate, AuthenticationConfig, EvidenceConfig, + OidcAuthenticationConfig, + }, +}; +use registry_platform_config::JwksSource; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier, TokenVerifierConfig}; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, Stage, TokenCorpus, TokenSigner, +}; +use registry_platform_yaml::{BoundedU64, UniqueList, Url}; +use serde_json::Value; + +/// The audience the product under test is configured with. +const PRODUCT_AUDIENCE: &str = "evidence-fixture"; + +/// The client the `default` configuration admits when a fixture names none, +/// and the scope the `recipe` configuration requires when a fixture carries +/// none. +const FALLBACK_CLIENT: &str = "journey-app"; +const FALLBACK_SCOPE: &str = "records:get"; + +/// The bundle Evidence's own acceptance tests start from. +const STARTER_BUNDLE: &str = + "../../products/evidence/fixtures/acceptance/adult-status/evidence.yaml"; + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +fn fixture_client(case: &FixtureCase) -> Option { + literal_string(case, "client_id").or_else(|| literal_string(case, "azp")) +} + +/// The first scope the fixture carries, read from `scope` or `scp`. +fn first_scope(case: &FixtureCase) -> Option { + if let Some(scope) = literal_string(case, "scope") { + return scope.split_whitespace().next().map(str::to_owned); + } + match case.fixture.claims.get("scp") { + Some(ClaimValue::Literal(Value::String(scope))) => { + scope.split_whitespace().next().map(str::to_owned) + } + Some(ClaimValue::Literal(Value::Array(scopes))) => { + scopes.first().and_then(Value::as_str).map(str::to_owned) + } + _ => None, + } +} + +fn unique(values: Vec) -> UniqueList { + UniqueList::new(values).expect("the values are distinct") +} + +/// The algorithm Evidence is configured with for the row: the fixture's own +/// where Evidence admits it, and the starter's otherwise. +fn configured_algorithm(case: &FixtureCase) -> AccessTokenAlgorithm { + match case + .fixture + .header + .as_ref() + .map(|header| header.alg.as_str()) + { + Some("RS256") => AccessTokenAlgorithm::RS256, + Some("EdDSA") => AccessTokenAlgorithm::EdDSA, + _ => AccessTokenAlgorithm::ES256, + } +} + +fn row_config(case: &FixtureCase, jwks_uri: &str) -> OidcAuthenticationConfig { + let bundle = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(STARTER_BUNDLE); + let bytes = std::fs::read(&bundle).expect("the starter bundle is readable"); + let mut config = EvidenceConfig::parse_yaml(&bytes) + .expect("the starter bundle parses") + .authentication + .oidc; + config.provider.issuer = Url::new(&case.issuer).expect("the issuer is a URL"); + config.provider.audience = case.audience.clone(); + config.provider.jwks_source = JwksSource::Uri { + uri: Url::new(jwks_uri).expect("the key set location is a URL"), + }; + config.provider.allow_insecure_http = true; + config.token_types = vec![AccessTokenType::AtJwt]; + config.algorithms = vec![configured_algorithm(case)]; + config.maximum_token_lifetime_seconds = + BoundedU64::new(86_400).expect("the day is within the lifetime bounds"); + let client = fixture_client(case); + config.allowed_clients = match (case.configuration, client) { + (Configuration::Default, client) => AdmissionGate::listed(unique(vec![ + client.unwrap_or_else(|| FALLBACK_CLIENT.to_owned()) + ])), + (_, Some(client)) => AdmissionGate::listed(unique(vec![client])), + (_, None) => AdmissionGate::unrestricted(), + }; + config.required_scopes = match case.configuration { + Configuration::Default => AdmissionGate::unrestricted(), + _ => AdmissionGate::listed(unique(vec![ + first_scope(case).unwrap_or_else(|| FALLBACK_SCOPE.to_owned()) + ])), + }; + config +} + +/// Serve the signer's public key set from a loopback listener and return the +/// origin, which doubles as the issuer. +async fn serve_key_set(key_set: Value) -> String { + let app = Router::new().route( + "/jwks.json", + get(move || { + let key_set = key_set.clone(); + async move { Json(key_set) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("a loopback port is free"); + let port = listener + .local_addr() + .expect("the listener has an address") + .port(); + tokio::spawn(async move { + axum::serve(listener, app) + .await + .expect("the key set server runs for the test"); + }); + format!("http://127.0.0.1:{port}") +} + +/// The stage at which the shared verifier refuses the token under the row's +/// bundle members, or `None` when it admits it. +async fn verifier_refusal(config: &OidcAuthenticationConfig, case: &FixtureCase) -> Option { + let jwks: JwkSet = serde_json::from_value(case.jwks.clone()).expect("the key set parses"); + let algorithms: Vec = config + .algorithms + .iter() + .map(|algorithm| algorithm.to_jsonwebtoken()) + .collect(); + let verifier = TokenVerifier::new( + TokenVerifierConfig::access_token_profile( + config.issuer().to_owned(), + vec![config.audience().to_owned()], + algorithms, + vec!["at+jwt".to_owned()], + ) + .with_denied_kids(HashSet::new()) + .with_max_token_lifetime(Some(Duration::from_secs( + config.maximum_token_lifetime_seconds.get(), + ))) + .with_allowed_clients(config.allowed_clients.admitted()), + Arc::new(JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults())), + ); + let error = verifier.verify(case.token.expose()).await.err()?; + let label = error.authentication_stage().label(); + match format!("refused/{label}").parse::() { + Ok(Outcome::Refused(stage)) => Some(stage), + other => panic!("the verifier stage `{label}` is not a corpus stage: {other:?}"), + } +} + +async fn authenticate(case: FixtureCase, key_set_uri: String) -> Outcome { + let config = row_config(&case, &key_set_uri); + let authenticator = Authenticator::from_config( + &AuthenticationConfig { + oidc: config.clone(), + }, + Vec::new(), + ); + match authenticator.authenticate(case.token.expose()).await { + Ok(context) => Outcome::Admitted(Some(context.actor_kind().as_str().to_owned())), + Err(AuthenticationError::Malformed) => Outcome::Refused(Stage::Header), + Err(AuthenticationError::Context | AuthenticationError::SenderConstrained) => { + Outcome::Refused(Stage::Claims) + } + Err(AuthenticationError::Verification) => match verifier_refusal(&config, &case).await { + Some(stage) => Outcome::Refused(stage), + None => { + assert!( + !config.required_scopes.admitted().is_empty(), + "the authenticator refused a token the verifier admits and no scope gate is set" + ); + Outcome::Refused(Stage::Scope) + } + }, + } +} + +#[tokio::test] +async fn evidence_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let origin = serve_key_set(signer.public_key_set()).await; + let key_set_uri = format!("{origin}/jwks.json"); + let report = corpus + .run_product_async("evidence", &signer, &origin, PRODUCT_AUDIENCE, |case| { + authenticate(case, key_set_uri.clone()) + }) + .await + .expect("the corpus runs for evidence"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran through Evidence" + ); + report.assert_matches(); +} diff --git a/crates/registry-mcp-edge/Cargo.toml b/crates/registry-mcp-edge/Cargo.toml index d3a5fc7675..6f7a65873b 100644 --- a/crates/registry-mcp-edge/Cargo.toml +++ b/crates/registry-mcp-edge/Cargo.toml @@ -47,7 +47,7 @@ zeroize.workspace = true [dev-dependencies] base64.workspace = true -registry-platform-testing = { workspace = true, features = ["test-authorization-server"] } +registry-platform-testing = { workspace = true, features = ["test-authorization-server", "token-fixtures"] } reqwest.workspace = true tokio.workspace = true tower.workspace = true diff --git a/crates/registry-mcp-edge/src/lib.rs b/crates/registry-mcp-edge/src/lib.rs index 88b5ba9fbc..440576b7e9 100644 --- a/crates/registry-mcp-edge/src/lib.rs +++ b/crates/registry-mcp-edge/src/lib.rs @@ -43,3 +43,6 @@ mod tests; #[cfg(test)] mod compatibility_tests; + +#[cfg(test)] +mod token_characterisation; diff --git a/crates/registry-mcp-edge/src/token_characterisation.rs b/crates/registry-mcp-edge/src/token_characterisation.rs new file mode 100644 index 0000000000..d9f1346988 --- /dev/null +++ b/crates/registry-mcp-edge/src/token_characterisation.rs @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Characterises which identity-provider tokens the MCP edge's real caller +//! authentication admits, against the token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Each row builds a resource server from the public options and verifier +//! constructor the product hosts use, mounts the `require_caller` layer the +//! edge router applies, and sends the fixture as a bearer credential. The +//! layer answers a refusal with a status that names no check, so the check is +//! read from a second verifier built by the same public `token_verifier` +//! constructor over the same key set. + +use std::{sync::Arc, time::Duration}; + +use axum::{ + body::Body, + http::{header, Request, StatusCode}, + routing::post, + Router, +}; +use registry_platform_audit::AuditProfile; +use registry_platform_oidc::{ + parse_static_jwks, JwksFetcher, JwksFetcherConfig, OidcError, TokenVerifier, +}; +use registry_platform_testing::{ + ClaimValue, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::Value; +use tower::ServiceExt; +use zeroize::Zeroizing; + +use crate::{ + inbound::require_caller, token_verifier, AccessTokenAlgorithm, RateLimitOptions, + ResourceServer, ResourceServerOptions, TokenBucketOptions, +}; + +const ISSUER: &str = "https://issuer.example.test"; +const RESOURCE: &str = "https://gateway.example.test/mcp"; +const PLACEHOLDER_CLIENT: &str = "journey-app"; +const PLACEHOLDER_SCOPE: &str = "records:get"; + +fn literal(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the token names, read the way the verifier reads it. +fn client_of(fixture: &TokenFixture) -> Option { + literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) +} + +fn first_scope(fixture: &TokenFixture) -> Option { + literal(fixture, "scope")? + .split_whitespace() + .next() + .map(str::to_owned) +} + +/// The algorithm the fixture declares, when the edge can be configured with +/// it. A symmetric or absent algorithm leaves the edge on RS256, which then +/// refuses the token at the algorithm check. +fn algorithm_of(fixture: &TokenFixture) -> AccessTokenAlgorithm { + match fixture.header.as_ref().map(|header| header.alg.as_str()) { + Some("ES256") => AccessTokenAlgorithm::ES256, + Some("EdDSA") => AccessTokenAlgorithm::EdDSA, + _ => AccessTokenAlgorithm::RS256, + } +} + +fn options_for(case: &FixtureCase) -> ResourceServerOptions { + ResourceServerOptions { + resource: case.audience.clone(), + issuer: case.issuer.clone(), + allow_insecure_http: false, + algorithms: vec![algorithm_of(&case.fixture)], + allowed_clients: vec![client_of(&case.fixture).unwrap_or_else(|| PLACEHOLDER_CLIENT.into())], + required_scopes: vec![ + first_scope(&case.fixture).unwrap_or_else(|| PLACEHOLDER_SCOPE.into()) + ], + scope_claim: "scope".to_owned(), + maximum_token_lifetime: Duration::from_secs(3600), + resource_name: "Token characterisation".to_owned(), + principal_audit_namespace: "principal-v1".to_owned(), + client_audit_namespace: "client-v1".to_owned(), + } +} + +/// A static key document admits RSA and EC keys only, so the corpus's EdDSA +/// key is left out. +fn fetcher_for(case: &FixtureCase) -> Arc { + let mut keys = case.jwks.clone(); + keys["keys"] + .as_array_mut() + .expect("a key set lists keys") + .retain(|key| key["kty"] != "OKP"); + Arc::new(JwksFetcher::new_static( + parse_static_jwks(keys.to_string().as_bytes()).expect("the corpus key set parses"), + JwksFetcherConfig::defaults(), + )) +} + +fn stage_of(error: &OidcError) -> Outcome { + format!("refused/{}", error.authentication_stage().label()) + .parse() + .expect("every authentication stage label is a result value") +} + +async fn observe(case: &FixtureCase) -> Outcome { + let options = options_for(case); + let hasher = AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![5; 32])) + .expect("audit profile") + .key_hasher(); + let server = Arc::new( + ResourceServer::new( + &options, + token_verifier(&options, fetcher_for(case)), + hasher, + RateLimitOptions { + per_principal: TokenBucketOptions { + requests_per_minute: 60, + burst: 1000, + }, + per_client: TokenBucketOptions { + requests_per_minute: 60, + burst: 1000, + }, + }, + ) + .expect("the resource server builds"), + ); + let router = Router::new() + .route("/mcp", post(|| async { "ok" })) + .layer(axum::middleware::from_fn_with_state(server, require_caller)); + let token = case.token.expose(); + let response = router + .oneshot( + Request::post("/mcp") + .header(header::AUTHORIZATION, format!("Bearer {token}")) + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + let probe: TokenVerifier = token_verifier(&options, fetcher_for(case)); + let verdict = probe.verify(token).await; + match (response.status(), verdict) { + (StatusCode::OK, Ok(_)) => Outcome::Admitted(None), + (StatusCode::OK, Err(_)) => panic!("the edge admitted a token its verifier refused"), + (_, Err(error)) => stage_of(&error), + (StatusCode::FORBIDDEN, Ok(_)) => "refused/scope".parse().expect("result value"), + (StatusCode::UNAUTHORIZED, Ok(_)) => "refused/claims".parse().expect("result value"), + (StatusCode::SERVICE_UNAVAILABLE, Ok(_)) => { + "refused/unavailable".parse().expect("result value") + } + (status, Ok(_)) => panic!("the edge answered the unexpected status {status}"), + } +} + +#[tokio::test] +async fn caller_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("mcp-edge", &signer, ISSUER, RESOURCE, |case| async move { + observe(&case).await + }) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran" + ); + report.assert_matches(); +} diff --git a/crates/registry-messaging/Cargo.toml b/crates/registry-messaging/Cargo.toml index f94335976e..59cc34143d 100644 --- a/crates/registry-messaging/Cargo.toml +++ b/crates/registry-messaging/Cargo.toml @@ -113,7 +113,7 @@ hex.workspace = true jsonschema.workspace = true rcgen.workspace = true registry-messaging-client.workspace = true -registry-platform-testing = { workspace = true, features = ["migration-pins", "postgres-catalog"] } +registry-platform-testing = { workspace = true, features = ["migration-pins", "token-fixtures", "postgres-catalog"] } reqwest.workspace = true serde_norway.workspace = true tempfile.workspace = true diff --git a/crates/registry-messaging/tests/token_characterisation.rs b/crates/registry-messaging/tests/token_characterisation.rs new file mode 100644 index 0000000000..b1808a6c6c --- /dev/null +++ b/crates/registry-messaging/tests/token_characterisation.rs @@ -0,0 +1,263 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Characterisation of Messaging's bearer authentication against the token +//! fixture corpus (`products/platform/conformance/tokens`). +//! +//! Every row of `expected.yaml` with a `messaging` cell is run through the +//! authenticator the server builds: the verifier profile comes from a +//! `RuntimeConfig` loaded from a runtime file, the keys from that file's static +//! key source, and the credential goes through +//! `MessagingAuthenticator::authenticate`. No database is involved. +//! +//! The authenticator reports a verifier refusal as one error. The stage of that +//! refusal is read by running the same token through a second verifier built +//! from the same configuration and keys, so the stage is the shared verifier's +//! own label. + +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use registry_messaging::auth::{AuthenticationError, MessagingAuthenticator}; +use registry_messaging::config::RuntimeConfig; +use registry_messaging::package::{package_inputs, write_package_inputs}; +use registry_messaging_core::{ + AccessProfile, AccessProfiles, ActorKind, ActsAs, MESSAGING_RUNTIME_API_VERSION, + MESSAGING_RUNTIME_KIND, +}; +use registry_platform_oidc::TokenVerifier; +use registry_platform_testing::{ + Against, ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://identity.example.test"; +const AUDIENCE: &str = "urn:example:messaging"; +/// The client a fixture without a client claim is configured against: the +/// allowed list always holds one client, as the runtime requires. +const PLACEHOLDER_CLIENT: &str = "journey-app"; +/// Clients the installed starter package names. The runtime refuses a +/// configuration whose allowed list omits a client of a package profile. +const PACKAGE_CLIENTS: [&str; 2] = ["case-system", "operations-console"]; +const PLACEHOLDER_SCOPE: &str = "records:get"; + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the fixture names, from `client_id` or `azp`. +fn fixture_client(case: &FixtureCase) -> String { + literal_string(case, "client_id") + .or_else(|| literal_string(case, "azp")) + .unwrap_or_else(|| PLACEHOLDER_CLIENT.to_owned()) +} + +/// The claim the configuration reads scopes from. +fn scope_claim(case: &FixtureCase) -> &'static str { + if case.configuration == Configuration::Recipe + && case.fixture.claims.contains_key("scp") + && !case.fixture.claims.contains_key("scope") + { + "scp" + } else { + "scope" + } +} + +/// The first scope the fixture carries in the claim the configuration names. +fn read_scope(case: &FixtureCase, claim: &str) -> String { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => text.split_whitespace().next(), + Some(ClaimValue::Literal(Value::Array(items))) => items.first().and_then(Value::as_str), + _ => None, + } + .unwrap_or(PLACEHOLDER_SCOPE) + .to_owned() +} + +fn write_private(path: &Path, bytes: &[u8]) { + fs::write(path, bytes).expect("write a private file"); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("restrict the file"); +} + +/// The key set a static key source accepts: it refuses a set holding any key +/// that is not RSA or EC, so the corpus's EdDSA key stays out of the file. No +/// admitted algorithm uses it. +fn static_key_set(jwks: &Value) -> Value { + let keys: Vec = jwks["keys"] + .as_array() + .expect("a key set with a keys array") + .iter() + .filter(|key| matches!(key["kty"].as_str(), Some("RSA" | "EC"))) + .cloned() + .collect(); + json!({ "keys": keys }) +} + +fn profiles(case: &FixtureCase, scope: &str) -> AccessProfiles { + AccessProfiles::new(vec![AccessProfile { + id: "corpus".to_owned(), + label: None, + description: None, + principal_claim: "sub".to_owned(), + required_scopes: vec![scope.to_owned()], + requester_clients: vec![fixture_client(case)], + actor_kind: (case.against == Against::HumanOnlyProfile).then_some(ActorKind::Human), + acts_as: ActsAs::Operator, + sender_profiles: Vec::new(), + templates: Vec::new(), + allow_direct_content: false, + requests_per_minute: 60, + burst: 10, + maximum_messages_per_day: None, + }]) + .expect("a valid access profile") +} + +fn refusal(stage_label: &str) -> Outcome { + format!("refused/{stage_label}") + .parse() + .expect("a stage the corpus knows") +} + +async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a runtime directory"); + let secrets = root.path().join("secrets"); + fs::create_dir(&secrets).expect("a secrets directory"); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).expect("restrict secrets"); + write_private( + &secrets.join("issuer-jwks"), + &serde_json::to_vec(&static_key_set(&case.jwks)).expect("a key set"), + ); + let claim = scope_claim(&case); + let scope = read_scope(&case, claim); + let runtime_path = root.path().join("runtime.json"); + fs::write( + &runtime_path, + serde_json::to_vec(&json!({ + "apiVersion": MESSAGING_RUNTIME_API_VERSION, + "kind": MESSAGING_RUNTIME_KIND, + "identity": {"databaseId": "token-characterisation"}, + "package": {"root": package_root}, + "listener": {"bind": "127.0.0.1:0", "tlsTermination": "development-loopback"}, + "secretProviders": {"file": {"root": secrets}, "environment": {}}, + "database": { + "runtimeUrlRef": "secret:env/MESSAGING_RUNTIME_URL", + "migrationUrlRef": "secret:env/MESSAGING_MIGRATION_URL" + }, + "authentication": {"oidc": { + "issuer": case.issuer, + "audience": case.audience, + "jwksSource": {"type": "static", "documentRef": "secret:file/issuer-jwks"}, + "allowedClients": [fixture_client(&case), PACKAGE_CLIENTS[0], PACKAGE_CLIENTS[1]], + "scopeClaim": claim + }}, + "audit": {"path": root.path().join("audit"), "hashKeyRef": "secret:file/audit-hash-key"} + })) + .expect("a runtime document"), + ) + .expect("write the runtime file"); + let config = RuntimeConfig::load(&runtime_path).expect("the runtime configuration loads"); + let resolver = config.secret_resolver().expect("the secret resolver"); + let keys = config + .jwks_fetcher(&resolver) + .await + .expect("the static key source"); + + let authenticator = MessagingAuthenticator::new( + config.verifier_profile(), + Arc::clone(&keys), + profiles(&case, &scope), + config.binds_assertion_issuers(), + ); + let token = case.token.expose(); + match authenticator.authenticate(token).await { + Ok(caller) => Outcome::Admitted(Some( + caller + .actor_kind + .map_or("unspecified", ActorKind::as_str) + .to_owned(), + )), + Err(AuthenticationError::Claims) => refusal("claims"), + Err(AuthenticationError::Unavailable) => refusal("unavailable"), + Err(error @ (AuthenticationError::Refused | AuthenticationError::Profile)) => { + let reference = TokenVerifier::new(config.verifier_profile(), keys); + match reference.verify(token).await { + Err(failure) => refusal(failure.authentication_stage().label()), + Ok(verified) if error == AuthenticationError::Profile => { + if verified.scopes.iter().any(|held| held == &scope) { + refusal("profile") + } else { + refusal("scope") + } + } + // The credential is not a compact access token, so the + // verifier is never reached. + Ok(_) => refusal("header"), + } + } + } +} + +/// The published starter, installed as a package the runtime file can name. +fn installed_starter_package() -> tempfile::TempDir { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a package directory"); + let starter = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../products/messaging/examples/starter"); + let project = root.path().join("project"); + fs::create_dir_all(&project).expect("a project directory"); + fs::copy( + starter.join("messaging.yaml"), + project.join("messaging.yaml"), + ) + .expect("the starter manifest"); + copy_tree(&starter.join("templates"), &project.join("templates")); + copy_tree(&starter.join("providers"), &project.join("providers")); + let inputs = package_inputs(&project).expect("the starter package inputs"); + write_package_inputs(&root.path().join("package"), &inputs, None) + .expect("the installed starter package"); + root +} + +fn copy_tree(from: &Path, to: &Path) { + fs::create_dir_all(to).expect("a directory"); + for entry in fs::read_dir(from).expect("a directory to copy") { + let entry = entry.expect("a directory entry"); + let target = to.join(entry.file_name()); + if entry.file_type().expect("an entry type").is_dir() { + copy_tree(&entry.path(), &target); + } else { + fs::copy(entry.path(), target).expect("a copied file"); + } + } +} + +#[tokio::test] +async fn messaging_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let installed = installed_starter_package(); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("messaging", &signer, ISSUER, AUDIENCE, |case| { + observe(installed.path().join("package"), case) + }) + .await + .expect("every messaging row is planned and signed"); + let run = report + .rows + .iter() + .filter(|row| row.observed.is_some()) + .count(); + assert!(run > 0, "no messaging row ran"); + eprintln!( + "messaging: {run} rows ran, {} differ", + report.mismatches().len() + ); + report.assert_matches(); +} diff --git a/crates/registry-platform-testing/Cargo.toml b/crates/registry-platform-testing/Cargo.toml index d0f2a22eda..5ea7f86165 100644 --- a/crates/registry-platform-testing/Cargo.toml +++ b/crates/registry-platform-testing/Cargo.toml @@ -19,11 +19,18 @@ test-authorization-server = ["test-utils", "dep:sha2", "dep:url", "dep:uuid"] migration-pins = ["test-utils", "dep:sha2"] # Canonical PostgreSQL catalogs for migration replay-equivalence tests. postgres-catalog = ["test-utils", "dep:tokio-postgres"] +# The token fixture corpus under `products/platform/conformance/tokens`, a test-time signer and a +# closure-driven driver; see `TokenCorpus`. +token-fixtures = ["test-utils", "dep:rand", "dep:serde", "dep:registry-platform-yaml"] [[test]] name = "test_authorization_server" required-features = ["test-authorization-server"] +[[test]] +name = "token_fixtures" +required-features = ["token-fixtures"] + [dependencies] axum.workspace = true base64.workspace = true @@ -34,7 +41,10 @@ registry-platform-crypto = { workspace = true } registry-platform-httpsec = { workspace = true, features = ["server"] } registry-platform-httputil = { workspace = true } registry-platform-oidc = { workspace = true } +registry-platform-yaml = { workspace = true, optional = true } +rand = { workspace = true, optional = true } reqwest.workspace = true +serde = { workspace = true, optional = true } serde_json.workspace = true sha2 = { workspace = true, optional = true } thiserror.workspace = true diff --git a/crates/registry-platform-testing/README.md b/crates/registry-platform-testing/README.md index ffff7fed95..20301e791b 100644 --- a/crates/registry-platform-testing/README.md +++ b/crates/registry-platform-testing/README.md @@ -138,6 +138,27 @@ response with: - `jwks_from_private_jwk(private)`: return `{"keys": [public]}` as a `serde_json::Value`; useful for mocking a JWKS endpoint. +## Token Fixtures + +The `token-fixtures` feature (off by default) loads the corpus in +`products/platform/conformance/tokens` and drives a product's authentication +with it. The path comes from this crate's manifest directory. + +- `TokenCorpus::load()` reads and validates every fixture and `expected.yaml`. +- `TokenSigner::new()` makes a fresh key per algorithm (RS256, ES256, EdDSA, HS256, + HS512) in memory only. `sign` signs a fixture's header and claims with its + declared algorithm, times as offsets from now. `public_key_set()` holds the + asymmetric public keys. `SignedToken` never prints its text in `Debug`. +- `TokenCorpus::run_product` (and `run_product_async`) takes the product's + authenticator as a closure from `&FixtureCase` to `Outcome`, runs every + applicable row, and returns a `ProductReport` compared with the product's + column of `expected.yaml`. A row asserts `target` where `landed` is true and + `main` otherwise. + +```bash +cargo test -p registry-platform-testing --features token-fixtures +``` + ## Fixture Notes - Fixtures are deterministic and intended for tests only. diff --git a/crates/registry-platform-testing/src/lib.rs b/crates/registry-platform-testing/src/lib.rs index fde20482a8..9de04636a4 100644 --- a/crates/registry-platform-testing/src/lib.rs +++ b/crates/registry-platform-testing/src/lib.rs @@ -24,6 +24,16 @@ pub use migration_pins::{assert_migration_pins, verify_migration_pins, MIGRATION #[cfg(feature = "postgres-catalog")] mod postgres_catalog; +#[cfg(feature = "token-fixtures")] +mod token_fixtures; + +#[cfg(feature = "token-fixtures")] +pub use token_fixtures::{ + Against, Basis, BindTarget, Binding, ClaimValue, Comparison, Configuration, Expectations, + ExpectedCell, ExpectedRow, FixtureCase, FixtureClass, FixtureHeader, Outcome, ProductReport, + RowReport, SignedToken, Stage, TokenCorpus, TokenFixture, TokenFixtureError, TokenSigner, +}; + #[cfg(feature = "postgres-catalog")] pub use postgres_catalog::verify_postgres_schema_equivalence; diff --git a/crates/registry-platform-testing/src/token_fixtures.rs b/crates/registry-platform-testing/src/token_fixtures.rs new file mode 100644 index 0000000000..f0e47e53b2 --- /dev/null +++ b/crates/registry-platform-testing/src/token_fixtures.rs @@ -0,0 +1,1195 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The token fixture corpus, a test-time signer and a closure-driven driver. +//! +//! The corpus lives in `products/platform/conformance/tokens`: one decoded token +//! shape per file under `fixtures/`, and `expected.yaml` with the expected result +//! for every fixture, product and configuration. A fixture holds no signature and +//! no key. [`TokenSigner`] makes a fresh key per algorithm when it is built, keeps +//! it in memory only, and signs a fixture's header and claims with the algorithm +//! the fixture declares. [`TokenCorpus::run_product`] takes a product's +//! authentication as a closure, runs every applicable fixture through it, and +//! compares the results with `expected.yaml` for that product. +//! +//! A product's test depends on this crate and passes its own authenticator in, so +//! no product depends on another. + +use std::{ + collections::{BTreeMap, BTreeSet}, + fmt, + future::Future, + path::{Path, PathBuf}, + str::FromStr, + time::{SystemTime, UNIX_EPOCH}, +}; + +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use futures::FutureExt as _; +use jsonwebtoken::{crypto, Algorithm, DecodingKey, EncodingKey}; +use rand::Rng as _; +use registry_platform_crypto::jws::sign_compact_jws; +use registry_platform_crypto::{ + generate_private_jwk, verify as verify_with_public_jwk, GeneratedKeyAlgorithm, LocalJwkSigner, + PrivateJwk, PublicJwk, +}; +use registry_platform_yaml::{EnvelopeRule, Expect, FormatSpec, Reader}; +use serde::Deserialize; +use serde_json::{json, Map, Value}; +use thiserror::Error; + +const FIXTURE_SCHEMA: &str = "registry.token-fixture/v1"; +const EXPECTATIONS_SCHEMA: &str = "registry.token-fixture-expectations/v1"; +/// `expected.yaml` is test data with a `schema` member and no `apiVersion` or `kind` envelope. +const EXPECTATIONS_FORMAT: FormatSpec<'static> = FormatSpec { + kind: "TokenFixtureExpectations", + envelope: EnvelopeRule::Exempt { + reason: "test data checked by the token fixture corpus tests, not a configuration file", + }, + removed_keys: &[], +}; +const PRIVATE_JWK_MEMBERS: [&str; 7] = ["d", "p", "q", "dp", "dq", "qi", "k"]; +const SIGNING_ALGORITHMS: [&str; 5] = ["RS256", "ES256", "EdDSA", "HS256", "HS512"]; + +/// Why a corpus file did not load, validate, sign or run. +#[derive(Debug, Error)] +pub enum TokenFixtureError { + #[error("token fixture corpus: cannot read {path}: {source}")] + Io { + path: String, + source: std::io::Error, + }, + #[error("token fixture `{fixture}`: {reason}")] + Invalid { fixture: String, reason: String }, + #[error("token fixture expectations: {0}")] + Expectations(String), + #[error("token fixture `{fixture}`: cannot sign: {reason}")] + Signing { fixture: String, reason: String }, + #[error("token fixture signature: {0}")] + Verification(String), + #[error("token fixture driver: product `{0}` is not a column of expected.yaml")] + UnknownProduct(String), +} + +fn invalid(fixture: &str, reason: impl Into) -> TokenFixtureError { + TokenFixtureError::Invalid { + fixture: fixture.to_owned(), + reason: reason.into(), + } +} + +// --------------------------------------------------------------------------- +// Results +// --------------------------------------------------------------------------- + +/// The check at which a product refused a token: the shared verifier's labels, +/// and `claims` for a product's own claim extraction. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Stage { + Header, + Algorithm, + TokenType, + Key, + Signature, + Issuer, + Audience, + Time, + Client, + Scope, + Profile, + Unavailable, + Claims, +} + +const STAGES: [(Stage, &str); 13] = [ + (Stage::Header, "header"), + (Stage::Algorithm, "algorithm"), + (Stage::TokenType, "token-type"), + (Stage::Key, "key"), + (Stage::Signature, "signature"), + (Stage::Issuer, "issuer"), + (Stage::Audience, "audience"), + (Stage::Time, "time"), + (Stage::Client, "client"), + (Stage::Scope, "scope"), + (Stage::Profile, "profile"), + (Stage::Unavailable, "unavailable"), + (Stage::Claims, "claims"), +]; + +impl Stage { + #[must_use] + pub fn as_str(self) -> &'static str { + STAGES + .iter() + .find(|(stage, _)| *stage == self) + .map_or("unknown-stage", |(_, name)| name) + } +} + +impl fmt::Display for Stage { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// The result of running one token through one product. The text forms are the +/// values `expected.yaml` uses. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// `admitted` (no actor kind) or `admitted/`, where the kind + /// may be `unspecified`. + Admitted(Option), + /// `refused/`. + Refused(Stage), + /// `none`: the configuration needs a setting the product does not have. + None, + /// `n-a`: the product has no such concept. + NotApplicable, + /// `unknown`: not determined. + Unknown, +} + +impl fmt::Display for Outcome { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Admitted(None) => f.write_str("admitted"), + Self::Admitted(Some(kind)) => write!(f, "admitted/{kind}"), + Self::Refused(stage) => write!(f, "refused/{stage}"), + Self::None => f.write_str("none"), + Self::NotApplicable => f.write_str("n-a"), + Self::Unknown => f.write_str("unknown"), + } + } +} + +impl FromStr for Outcome { + type Err = String; + + fn from_str(text: &str) -> Result { + match text { + "admitted" => return Ok(Self::Admitted(None)), + "none" => return Ok(Self::None), + "n-a" => return Ok(Self::NotApplicable), + "unknown" => return Ok(Self::Unknown), + _ => {} + } + if let Some(kind) = text.strip_prefix("admitted/") { + let well_formed = !kind.is_empty() + && kind + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + return if well_formed { + Ok(Self::Admitted(Some(kind.to_owned()))) + } else { + Err(format!("`{text}` names no actor kind")) + }; + } + if let Some(stage) = text.strip_prefix("refused/") { + return STAGES + .iter() + .find(|(_, name)| *name == stage) + .map(|(stage, _)| Self::Refused(*stage)) + .ok_or_else(|| format!("`{text}` names no known stage")); + } + Err(format!("`{text}` is not a result value")) + } +} + +impl<'de> Deserialize<'de> for Outcome { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + text.parse().map_err(serde::de::Error::custom) + } +} + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum FixtureClass { + Positive, + Negative, +} + +/// The issuer or audience a claim takes from the product under test. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BindTarget { + Issuer, + Audience, +} + +/// A claim value: plain JSON, or one of three directives. +#[derive(Debug, Clone, PartialEq)] +pub enum ClaimValue { + Literal(Value), + Bind(BindTarget), + /// Seconds after the moment of signing. + OffsetSeconds(i64), + /// A random value made at signing time. + Generated, +} + +/// The JOSE header a fixture declares. `kid` is always generated at signing time. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FixtureHeader { + pub alg: String, + pub typ: Option, +} + +/// One decoded token shape. +#[derive(Debug, Clone, PartialEq)] +pub struct TokenFixture { + pub id: String, + pub class: FixtureClass, + pub provider: String, + pub kind: String, + pub token_use: String, + pub subject_kind: String, + /// The `source` object, kept as written. + pub source: Value, + pub header: Option, + pub claims: BTreeMap, + /// A credential that is not a JWT, as a synthetic string. + pub opaque: Option, + pub omits: Vec, + pub notes: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RawFixture { + schema: String, + id: String, + class: FixtureClass, + provider: String, + kind: String, + token_use: String, + subject_kind: String, + source: Value, + header: Option, + claims: Option>, + opaque: Option, + omits: Option>, + notes: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawHeader { + alg: String, + typ: Option, + kid: Value, +} + +impl TokenFixture { + /// Parse and validate one fixture file. `file_stem` is the file name without + /// its extension and must equal the fixture's `id`. + pub fn parse(file_stem: &str, text: &str) -> Result { + let value: Value = serde_json::from_str(text) + .map_err(|error| invalid(file_stem, format!("not valid JSON: {error}")))?; + reject_key_material(file_stem, &value)?; + let raw: RawFixture = + serde_json::from_value(value).map_err(|error| invalid(file_stem, error.to_string()))?; + if raw.schema != FIXTURE_SCHEMA { + return Err(invalid( + file_stem, + format!("schema must be `{FIXTURE_SCHEMA}`"), + )); + } + if raw.id != file_stem { + return Err(invalid( + file_stem, + format!("id `{}` differs from the file name", raw.id), + )); + } + if raw.source.get("basis").and_then(Value::as_str).is_none() { + return Err(invalid(file_stem, "source.basis is required")); + } + let omits = raw.omits.clone().unwrap_or_default(); + let fixture = match (raw.opaque, raw.header, raw.claims) { + (Some(opaque), None, None) if omits.is_empty() && !opaque.is_empty() => { + (Some(opaque), None, BTreeMap::new()) + } + (Some(_), ..) => return Err(invalid( + file_stem, + "an opaque fixture holds no header, claims or omits, and a JWT fixture no opaque", + )), + (None, Some(header), Some(claims)) => { + let header = parse_header(file_stem, header)?; + let claims = parse_claims(file_stem, &claims)?; + (None, Some(header), claims) + } + (None, ..) => { + return Err(invalid( + file_stem, + "a fixture holds opaque, or both header and claims", + )) + } + }; + let (opaque, header, claims) = fixture; + for omitted in &omits { + if claims.contains_key(omitted) { + return Err(invalid( + file_stem, + format!("omits names claim `{omitted}`, which the fixture sets"), + )); + } + } + Ok(Self { + id: raw.id, + class: raw.class, + provider: raw.provider, + kind: raw.kind, + token_use: raw.token_use, + subject_kind: raw.subject_kind, + source: raw.source, + header, + claims, + opaque, + omits, + notes: raw.notes, + }) + } +} + +fn parse_header(fixture: &str, raw: RawHeader) -> Result { + if !SIGNING_ALGORITHMS.contains(&raw.alg.as_str()) { + return Err(invalid( + fixture, + format!( + "header alg `{}` is not one of {SIGNING_ALGORITHMS:?}", + raw.alg + ), + )); + } + if raw.kid != json!({ "generated": true }) { + return Err(invalid(fixture, "header kid must be {\"generated\": true}")); + } + Ok(FixtureHeader { + alg: raw.alg, + typ: raw.typ, + }) +} + +fn parse_claims( + fixture: &str, + raw: &Map, +) -> Result, TokenFixtureError> { + let mut claims = BTreeMap::new(); + for (name, value) in raw { + let claim = parse_claim(value) + .map_err(|reason| invalid(fixture, format!("claim `{name}`: {reason}")))?; + if matches!(name.as_str(), "exp" | "iat" | "nbf") + && !matches!(claim, ClaimValue::OffsetSeconds(_)) + { + return Err(invalid( + fixture, + format!("claim `{name}` must be an offsetSeconds directive"), + )); + } + claims.insert(name.clone(), claim); + } + if !claims.contains_key("exp") { + return Err(invalid(fixture, "claims must carry exp")); + } + Ok(claims) +} + +fn parse_claim(value: &Value) -> Result { + let Some(map) = value.as_object() else { + return Ok(ClaimValue::Literal(value.clone())); + }; + let is_directive = ["bind", "offsetSeconds", "generated"] + .iter() + .any(|key| map.contains_key(*key)); + if !is_directive { + return Ok(ClaimValue::Literal(value.clone())); + } + if map.len() != 1 { + return Err("a directive holds exactly one member".to_owned()); + } + if let Some(bind) = map.get("bind") { + return match bind.as_str() { + Some("issuer") => Ok(ClaimValue::Bind(BindTarget::Issuer)), + Some("audience") => Ok(ClaimValue::Bind(BindTarget::Audience)), + _ => Err("bind is `issuer` or `audience`".to_owned()), + }; + } + if let Some(offset) = map.get("offsetSeconds") { + return match offset.as_i64() { + Some(seconds) if seconds >= 0 => Ok(ClaimValue::OffsetSeconds(seconds)), + _ => Err("offsetSeconds is a non-negative integer".to_owned()), + }; + } + if map.get("generated") == Some(&Value::Bool(true)) { + return Ok(ClaimValue::Generated); + } + Err("generated is `true`".to_owned()) +} + +/// A fixture is never a key and never a live token: refuse a private JWK member +/// name anywhere, and any string shaped like a compact JWT. +fn reject_key_material(fixture: &str, value: &Value) -> Result<(), TokenFixtureError> { + match value { + Value::Object(map) => { + for (name, member) in map { + if PRIVATE_JWK_MEMBERS.contains(&name.as_str()) { + return Err(invalid( + fixture, + format!("holds the private JWK member name `{name}`"), + )); + } + reject_key_material(fixture, member)?; + } + } + Value::Array(items) => { + for item in items { + reject_key_material(fixture, item)?; + } + } + Value::String(text) => { + if text.starts_with("eyJ") && text.matches('.').count() == 2 { + return Err(invalid(fixture, "holds a string shaped like a compact JWT")); + } + if text.contains("PRIVATE KEY") { + return Err(invalid(fixture, "holds PEM key material")); + } + } + _ => {} + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Expectations +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Against { + PlainRead, + HumanOnlyProfile, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Configuration { + Default, + Recipe, + JwtAccepted, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Basis { + Inferred, + Observed, +} + +/// One product's cell in a row. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ExpectedCell { + pub main: Outcome, + pub target: Outcome, + #[serde(deserialize_with = "milestone_or_none")] + pub changed_by: Option, + pub landed: Option, + pub basis: Basis, + pub reason: Option, + pub target_reason: Option, +} + +impl ExpectedCell { + /// What a test asserts: `target` where the milestone has landed, `main` + /// everywhere else. + #[must_use] + pub fn expected(&self) -> &Outcome { + if self.landed == Some(true) { + &self.target + } else { + &self.main + } + } +} + +fn milestone_or_none<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + let text = String::deserialize(deserializer)?; + if text == "none" { + return Ok(None); + } + let digits = text.strip_prefix('M').unwrap_or(""); + if !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) { + Ok(Some(text)) + } else { + Err(serde::de::Error::custom(format!( + "changedBy `{text}` is neither `none` nor a milestone like `M7`" + ))) + } +} + +/// One fixture, `against` value and configuration, with a cell per product. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExpectedRow { + pub fixture: String, + pub against: Against, + pub configuration: Configuration, + pub products: BTreeMap, +} + +/// `expected.yaml`. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Expectations { + pub schema: String, + pub products: Vec, + pub configurations: BTreeMap, + pub rows: Vec, +} + +// --------------------------------------------------------------------------- +// Signer +// --------------------------------------------------------------------------- + +/// The issuer and audience of the product under test, which `bind` claims take. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Binding { + pub issuer: String, + pub audience: String, +} + +/// A signed token, or a synthetic opaque credential. Its `Debug` form shows no +/// token text. +#[derive(Clone)] +pub struct SignedToken { + text: String, + opaque: bool, +} + +impl SignedToken { + /// The credential as a product receives it in an `Authorization` header. + #[must_use] + pub fn expose(&self) -> &str { + &self.text + } + + #[must_use] + pub fn is_opaque(&self) -> bool { + self.opaque + } + + /// The same kind of credential with other text, for tampering tests. + #[must_use] + pub fn with_text(&self, text: String) -> Self { + Self { + text, + opaque: self.opaque, + } + } +} + +impl fmt::Debug for SignedToken { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SignedToken") + .field("opaque", &self.opaque) + .field("length", &self.text.len()) + .finish() + } +} + +/// Keys made when the signer is built, one per algorithm, held in memory only. +/// A product that verifies tokens is given [`TokenSigner::public_key_set`]. +pub struct TokenSigner { + rs256: PrivateJwk, + es256: PrivateJwk, + eddsa: PrivateJwk, + hs256: Vec, + hs512: Vec, +} + +impl fmt::Debug for TokenSigner { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TokenSigner").finish_non_exhaustive() + } +} + +impl Default for TokenSigner { + fn default() -> Self { + Self::new() + } +} + +impl TokenSigner { + /// Make a fresh key for every algorithm. + /// + /// # Panics + /// + /// Panics if a key cannot be generated. + #[must_use] + pub fn new() -> Self { + let mut rs256 = generate_private_jwk(GeneratedKeyAlgorithm::Rs384) + .expect("ephemeral RSA test key generates"); + rs256.alg = Some("RS256".to_owned()); + let es256 = generate_private_jwk(GeneratedKeyAlgorithm::Es256) + .expect("ephemeral ES256 test key generates"); + let eddsa = generate_private_jwk(GeneratedKeyAlgorithm::Ed25519) + .expect("ephemeral EdDSA test key generates"); + let mut hs256 = vec![0_u8; 32]; + let mut hs512 = vec![0_u8; 64]; + rand::rng().fill(hs256.as_mut_slice()); + rand::rng().fill(hs512.as_mut_slice()); + Self { + rs256, + es256, + eddsa, + hs256, + hs512, + } + } + + /// The public halves of the asymmetric keys as a key set. HMAC keys have no + /// public half and are never in it, so a product cannot verify an HS256 or + /// HS512 token from a key set. + /// + /// # Panics + /// + /// Panics if a public key cannot be serialised. + #[must_use] + pub fn public_key_set(&self) -> Value { + let keys: Vec = [&self.rs256, &self.es256, &self.eddsa] + .into_iter() + .map(|key| serde_json::to_value(key.public()).expect("public JWK serialises")) + .collect(); + json!({ "keys": keys }) + } + + fn asymmetric_key(&self, alg: &str) -> Option<&PrivateJwk> { + match alg { + "RS256" => Some(&self.rs256), + "ES256" => Some(&self.es256), + "EdDSA" => Some(&self.eddsa), + _ => None, + } + } + + fn hmac_key(&self, alg: &str) -> Option<(&[u8], Algorithm)> { + match alg { + "HS256" => Some((&self.hs256, Algorithm::HS256)), + "HS512" => Some((&self.hs512, Algorithm::HS512)), + _ => None, + } + } + + /// Sign a fixture now. Times are offsets from this moment, `bind` claims take + /// `binding`, and an opaque fixture yields its synthetic string. + pub fn sign( + &self, + fixture: &TokenFixture, + binding: &Binding, + ) -> Result { + let signing = |reason: String| TokenFixtureError::Signing { + fixture: fixture.id.clone(), + reason, + }; + if let Some(opaque) = &fixture.opaque { + return Ok(SignedToken { + text: opaque.clone(), + opaque: true, + }); + } + let header = fixture + .header + .as_ref() + .ok_or_else(|| signing("no header".to_owned()))?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| signing(error.to_string()))? + .as_secs(); + let now = i64::try_from(now).map_err(|error| signing(error.to_string()))?; + let mut claims = Map::new(); + for (name, claim) in &fixture.claims { + let value = match claim { + ClaimValue::Literal(value) => value.clone(), + ClaimValue::Bind(BindTarget::Issuer) => Value::String(binding.issuer.clone()), + ClaimValue::Bind(BindTarget::Audience) => Value::String(binding.audience.clone()), + ClaimValue::OffsetSeconds(seconds) => json!(now + seconds), + ClaimValue::Generated => Value::String(random_hex()), + }; + claims.insert(name.clone(), value); + } + let payload = serde_json::to_vec(&Value::Object(claims)) + .map_err(|error| signing(error.to_string()))?; + let mut extra_header = Map::new(); + if let Some(typ) = &header.typ { + extra_header.insert("typ".to_owned(), Value::String(typ.clone())); + } + let text = if let Some(key) = self.asymmetric_key(&header.alg) { + let signer = + LocalJwkSigner::new(key.clone()).map_err(|error| signing(error.to_string()))?; + // The signer is local, so its future is ready on the first poll. Polling it + // directly keeps signing usable from inside any executor. + sign_compact_jws(extra_header, &payload, &signer) + .now_or_never() + .ok_or_else(|| signing("the local signer did not complete at once".to_owned()))? + .map_err(|error| signing(error.to_string()))? + } else if let Some((secret, algorithm)) = self.hmac_key(&header.alg) { + extra_header.insert("alg".to_owned(), Value::String(header.alg.clone())); + extra_header.insert( + "kid".to_owned(), + Value::String(format!("test-hmac-{}", header.alg.to_lowercase())), + ); + let header_bytes = serde_json::to_vec(&Value::Object(extra_header)) + .map_err(|error| signing(error.to_string()))?; + let input = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(header_bytes), + URL_SAFE_NO_PAD.encode(&payload) + ); + let signature = crypto::sign( + input.as_bytes(), + &EncodingKey::from_secret(secret), + algorithm, + ) + .map_err(|error| signing(error.to_string()))?; + format!("{input}.{signature}") + } else { + return Err(signing(format!("no key for algorithm `{}`", header.alg))); + }; + Ok(SignedToken { + text, + opaque: false, + }) + } + + /// Check a signed token's signature with this signer's keys. An opaque + /// credential has no signature and passes. + pub fn verify_signature(&self, token: &SignedToken) -> Result<(), TokenFixtureError> { + let fail = |reason: &str| TokenFixtureError::Verification(reason.to_owned()); + if token.opaque { + return Ok(()); + } + let mut parts = token.text.split('.'); + let (Some(header), Some(payload), Some(signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(fail("not three segments")); + }; + let input = format!("{header}.{payload}"); + let header: Value = URL_SAFE_NO_PAD + .decode(header) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .ok_or_else(|| fail("header is not base64url JSON"))?; + let alg = header + .get("alg") + .and_then(Value::as_str) + .ok_or_else(|| fail("header has no alg"))?; + if let Some(key) = self.asymmetric_key(alg) { + if header.get("kid").and_then(Value::as_str) != key.kid.as_deref() { + return Err(fail("kid names no key of this signer")); + } + let signature = URL_SAFE_NO_PAD + .decode(signature) + .map_err(|_| fail("signature is not base64url"))?; + let public: PublicJwk = key.public(); + verify_with_public_jwk(input.as_bytes(), &signature, &public) + .map_err(|_| fail("signature does not verify")) + } else if let Some((secret, algorithm)) = self.hmac_key(alg) { + let expected_kid = format!("test-hmac-{}", alg.to_lowercase()); + if header.get("kid").and_then(Value::as_str) != Some(expected_kid.as_str()) { + return Err(fail("kid names no key of this signer")); + } + match crypto::verify( + signature, + input.as_bytes(), + &DecodingKey::from_secret(secret), + algorithm, + ) { + Ok(true) => Ok(()), + Ok(false) | Err(_) => Err(fail("signature does not verify")), + } + } else { + Err(fail("alg is not one this signer holds")) + } + } +} + +fn random_hex() -> String { + let mut bytes = [0_u8; 16]; + rand::rng().fill(&mut bytes); + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +// --------------------------------------------------------------------------- +// Corpus and driver +// --------------------------------------------------------------------------- + +/// What the product under test is given for one row. +#[derive(Debug, Clone)] +pub struct FixtureCase { + pub fixture: TokenFixture, + pub against: Against, + pub configuration: Configuration, + /// The product's issuer. + pub issuer: String, + /// The audience the product is configured with for this row. It is the + /// audience the driver was given, except for a positive fixture in the + /// `recipe` configuration that states a literal `aud`: the documented + /// recipe names that audience. + pub audience: String, + /// The credential to present. + pub token: SignedToken, + /// The public key set the product verifies against. + pub jwks: Value, +} + +/// Whether a product's result matched `expected.yaml` for a row. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Comparison { + Match, + Mismatch, + /// The expected value is `none` or `n-a`: nothing was run. + NotApplicable, + /// The expected value is `unknown`: the result was observed and not judged. + Unresolved, +} + +/// The outcome of one row for one product. It holds no token. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RowReport { + pub fixture: String, + pub against: Against, + pub configuration: Configuration, + pub expected: Outcome, + pub observed: Option, + pub comparison: Comparison, +} + +/// Every row of `expected.yaml` for one product column. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProductReport { + pub product: String, + pub rows: Vec, +} + +impl ProductReport { + #[must_use] + pub fn mismatches(&self) -> Vec<&RowReport> { + self.rows + .iter() + .filter(|row| row.comparison == Comparison::Mismatch) + .collect() + } + + /// # Panics + /// + /// Panics, listing each differing row, if any row mismatched. + pub fn assert_matches(&self) { + let mismatches = self.mismatches(); + assert!( + mismatches.is_empty(), + "{} rows of `{}` differ from expected.yaml:\n{}", + mismatches.len(), + self.product, + mismatches + .iter() + .map(|row| format!( + " {} / {:?} / {:?}: expected {}, observed {}", + row.fixture, + row.against, + row.configuration, + row.expected, + row.observed + .as_ref() + .map_or_else(|| "nothing".to_owned(), ToString::to_string), + )) + .collect::>() + .join("\n") + ); + } +} + +/// The fixtures and `expected.yaml`, loaded and cross-checked. +#[derive(Debug, Clone)] +pub struct TokenCorpus { + fixtures: Vec, + expectations: Expectations, +} + +struct PlannedRow { + report: RowReport, + case: Option, +} + +impl TokenCorpus { + /// The corpus directory, resolved from this crate's manifest directory. + #[must_use] + pub fn directory() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../products/platform/conformance/tokens") + } + + /// Load every fixture and `expected.yaml`, and check them against each other. + pub fn load() -> Result { + let root = Self::directory(); + let fixtures_dir = root.join("fixtures"); + let read_error = |path: &Path| { + let path = path.display().to_string(); + move |source| TokenFixtureError::Io { path, source } + }; + let mut paths = Vec::new(); + for entry in std::fs::read_dir(&fixtures_dir).map_err(read_error(&fixtures_dir))? { + let path = entry.map_err(read_error(&fixtures_dir))?.path(); + if path.extension().and_then(|e| e.to_str()) == Some("json") { + paths.push(path); + } + } + paths.sort(); + let mut fixtures = Vec::new(); + for path in &paths { + let text = std::fs::read_to_string(path).map_err(read_error(path))?; + let stem = path + .file_stem() + .and_then(|s| s.to_str()) + .ok_or_else(|| invalid(&path.display().to_string(), "file name is not UTF-8"))?; + fixtures.push(TokenFixture::parse(stem, &text)?); + } + let expected_path = root.join("expected.yaml"); + let text = std::fs::read_to_string(&expected_path).map_err(read_error(&expected_path))?; + let expectations: Expectations = Reader::new("expected.yaml") + .decode::(text.as_bytes(), &Expect::one(&EXPECTATIONS_FORMAT)) + .map_err(|report| { + TokenFixtureError::Expectations( + report + .diagnostics() + .iter() + .map(|diagnostic| format!("{}: {}", diagnostic.code, diagnostic.message)) + .collect::>() + .join("; "), + ) + })? + .value; + let corpus = Self { + fixtures, + expectations, + }; + corpus.check_expectations()?; + Ok(corpus) + } + + fn check_expectations(&self) -> Result<(), TokenFixtureError> { + let fail = |reason: String| Err(TokenFixtureError::Expectations(reason)); + let expectations = &self.expectations; + if expectations.schema != EXPECTATIONS_SCHEMA { + return fail(format!("schema must be `{EXPECTATIONS_SCHEMA}`")); + } + let products: BTreeSet<&str> = expectations.products.iter().map(String::as_str).collect(); + if products.len() != expectations.products.len() || products.is_empty() { + return fail("products must be a non-empty list without repeats".to_owned()); + } + let mut seen = BTreeSet::new(); + for row in &expectations.rows { + let Some(fixture) = self.fixture(&row.fixture) else { + return fail(format!("row names unknown fixture `{}`", row.fixture)); + }; + if !seen.insert((row.fixture.as_str(), row.against, row.configuration)) { + return fail(format!( + "row `{}` / {:?} / {:?} repeats", + row.fixture, row.against, row.configuration + )); + } + let row_products: BTreeSet<&str> = row.products.keys().map(String::as_str).collect(); + if row_products != products { + return fail(format!( + "row `{}` does not have exactly the product columns", + row.fixture + )); + } + for (product, cell) in &row.products { + if cell.landed.is_some() != cell.changed_by.is_some() { + return fail(format!( + "`{}` / `{product}`: landed appears exactly when changedBy is a milestone", + row.fixture + )); + } + let admitted = |outcome: &Outcome| matches!(outcome, Outcome::Admitted(_)); + if fixture.class == FixtureClass::Negative + && (admitted(&cell.main) || admitted(&cell.target)) + { + return fail(format!( + "negative fixture `{}` is admitted by `{product}`", + row.fixture + )); + } + } + } + for fixture in &self.fixtures { + if !expectations + .rows + .iter() + .any(|row| row.fixture == fixture.id) + { + return fail(format!("fixture `{}` has no row", fixture.id)); + } + } + Ok(()) + } + + #[must_use] + pub fn fixtures(&self) -> &[TokenFixture] { + &self.fixtures + } + + #[must_use] + pub fn fixture(&self, id: &str) -> Option<&TokenFixture> { + self.fixtures.iter().find(|fixture| fixture.id == id) + } + + #[must_use] + pub fn expectations(&self) -> &Expectations { + &self.expectations + } + + fn plan( + &self, + product: &str, + signer: &TokenSigner, + issuer: &str, + audience: &str, + ) -> Result, TokenFixtureError> { + if !self + .expectations + .products + .iter() + .any(|name| name == product) + { + return Err(TokenFixtureError::UnknownProduct(product.to_owned())); + } + let jwks = signer.public_key_set(); + let mut planned = Vec::new(); + for row in &self.expectations.rows { + let cell = row + .products + .get(product) + .ok_or_else(|| TokenFixtureError::UnknownProduct(product.to_owned()))?; + let expected = cell.expected().clone(); + let mut report = RowReport { + fixture: row.fixture.clone(), + against: row.against, + configuration: row.configuration, + expected: expected.clone(), + observed: None, + comparison: Comparison::NotApplicable, + }; + if matches!(expected, Outcome::None | Outcome::NotApplicable) { + planned.push(PlannedRow { report, case: None }); + continue; + } + let fixture = self + .fixture(&row.fixture) + .ok_or_else(|| invalid(&row.fixture, "no such fixture"))?; + let audience = configured_audience(fixture, row.configuration, audience); + let token = signer.sign( + fixture, + &Binding { + issuer: issuer.to_owned(), + audience: audience.clone(), + }, + )?; + report.comparison = Comparison::Unresolved; + planned.push(PlannedRow { + report, + case: Some(FixtureCase { + fixture: fixture.clone(), + against: row.against, + configuration: row.configuration, + issuer: issuer.to_owned(), + audience, + token, + jwks: jwks.clone(), + }), + }); + } + Ok(planned) + } + + /// Run every applicable row through `authenticate` and compare the results + /// with `expected.yaml` for `product`. Rows whose expected value is `none` + /// or `n-a` are not run. `issuer` and `audience` are the product's own. + pub fn run_product( + &self, + product: &str, + signer: &TokenSigner, + issuer: &str, + audience: &str, + mut authenticate: F, + ) -> Result + where + F: FnMut(&FixtureCase) -> Outcome, + { + let mut rows = Vec::new(); + for planned in self.plan(product, signer, issuer, audience)? { + let observed = planned.case.as_ref().map(&mut authenticate); + rows.push(finish(planned.report, observed)); + } + Ok(ProductReport { + product: product.to_owned(), + rows, + }) + } + + /// [`Self::run_product`] for an authenticator that is asynchronous. + pub async fn run_product_async( + &self, + product: &str, + signer: &TokenSigner, + issuer: &str, + audience: &str, + mut authenticate: F, + ) -> Result + where + F: FnMut(FixtureCase) -> Fut, + Fut: Future, + { + let mut rows = Vec::new(); + for planned in self.plan(product, signer, issuer, audience)? { + let observed = match planned.case { + Some(case) => Some(authenticate(case).await), + None => None, + }; + rows.push(finish(planned.report, observed)); + } + Ok(ProductReport { + product: product.to_owned(), + rows, + }) + } +} + +fn configured_audience( + fixture: &TokenFixture, + configuration: Configuration, + product_audience: &str, +) -> String { + if fixture.class == FixtureClass::Positive && configuration == Configuration::Recipe { + if let Some(ClaimValue::Literal(Value::String(literal))) = fixture.claims.get("aud") { + return literal.clone(); + } + } + product_audience.to_owned() +} + +fn finish(mut report: RowReport, observed: Option) -> RowReport { + if let Some(observed) = observed { + report.comparison = match report.expected { + Outcome::Unknown => Comparison::Unresolved, + ref expected if *expected == observed => Comparison::Match, + _ => Comparison::Mismatch, + }; + report.observed = Some(observed); + } + report +} diff --git a/crates/registry-platform-testing/tests/token_fixtures.rs b/crates/registry-platform-testing/tests/token_fixtures.rs new file mode 100644 index 0000000000..a406db43fa --- /dev/null +++ b/crates/registry-platform-testing/tests/token_fixtures.rs @@ -0,0 +1,586 @@ +#![cfg(feature = "token-fixtures")] +//! The token fixture corpus under `products/platform/conformance/tokens`: every +//! fixture loads and validates, signs and verifies, every expectation row names +//! a real fixture and product, and nothing in the corpus is a key or a live token. +//! The driver is exercised with stand-in authenticators. + +use std::collections::BTreeSet; + +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use registry_platform_testing::{ + Against, Binding, Comparison, Configuration, FixtureClass, Outcome, Stage, TokenCorpus, + TokenFixture, TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://issuer.example.test/realms/journey"; +const AUDIENCE: &str = "https://api.example.test"; +const PRIVATE_JWK_MEMBERS: [&str; 7] = ["d", "p", "q", "dp", "dq", "qi", "k"]; + +fn corpus() -> TokenCorpus { + TokenCorpus::load().expect("the corpus loads and validates") +} + +fn binding() -> Binding { + Binding { + issuer: ISSUER.to_owned(), + audience: AUDIENCE.to_owned(), + } +} + +fn decode_segment(segment: &str) -> Value { + let bytes = URL_SAFE_NO_PAD + .decode(segment) + .expect("segment is base64url"); + serde_json::from_slice(&bytes).expect("segment is JSON") +} + +fn minimal_fixture(extra: Value) -> String { + let mut base = json!({ + "schema": "registry.token-fixture/v1", + "id": "unit-fixture", + "class": "positive", + "provider": "synthetic", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { "basis": "constructed", "reason": "a unit test" }, + "header": { "alg": "ES256", "typ": "at+jwt", "kid": { "generated": true } }, + "claims": { + "iss": { "bind": "issuer" }, + "aud": { "bind": "audience" }, + "sub": "subject-1", + "iat": { "offsetSeconds": 0 }, + "exp": { "offsetSeconds": 300 } + } + }); + for (key, value) in extra.as_object().expect("extra is an object") { + base[key] = value.clone(); + } + base.to_string() +} + +fn parse_error(extra: Value) -> String { + TokenFixture::parse("unit-fixture", &minimal_fixture(extra)) + .expect_err("the fixture is refused") + .to_string() +} + +// --------------------------------------------------------------------------- +// The corpus as written +// --------------------------------------------------------------------------- + +#[test] +fn every_fixture_loads_and_validates() { + let corpus = corpus(); + assert_eq!(corpus.fixtures().len(), 21, "11 positive and 10 negative"); + let positive = corpus + .fixtures() + .iter() + .filter(|fixture| fixture.class == FixtureClass::Positive) + .count(); + assert_eq!(positive, 11); + let ids: BTreeSet<&str> = corpus.fixtures().iter().map(|f| f.id.as_str()).collect(); + assert_eq!(ids.len(), corpus.fixtures().len(), "ids are unique"); +} + +#[test] +fn every_fixture_signs_and_its_signature_verifies() { + let corpus = corpus(); + let signer = TokenSigner::new(); + for fixture in corpus.fixtures() { + let signed = signer + .sign(fixture, &binding()) + .unwrap_or_else(|error| panic!("{} signs: {error}", fixture.id)); + signer + .verify_signature(&signed) + .unwrap_or_else(|error| panic!("{} verifies: {error}", fixture.id)); + } +} + +#[test] +fn a_signed_token_carries_the_declared_header_and_the_bound_claims() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let fixture = corpus + .fixture("thunderid-user-access") + .expect("the fixture exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + let segments: Vec<&str> = signed.expose().split('.').collect(); + assert_eq!(segments.len(), 3); + let header = decode_segment(segments[0]); + assert_eq!(header["alg"], "RS256"); + assert_eq!(header["typ"], "at+jwt"); + assert!(header["kid"].as_str().is_some_and(|kid| !kid.is_empty())); + let claims = decode_segment(segments[1]); + assert_eq!(claims["iss"], ISSUER); + assert_eq!(claims["aud"], AUDIENCE); + let iat = claims["iat"].as_i64().expect("iat is an integer"); + let exp = claims["exp"].as_i64().expect("exp is an integer"); + assert_eq!(exp - iat, 3600, "the lifetime is the fixture's offset"); +} + +#[test] +fn a_fixture_without_typ_signs_a_header_without_typ() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let fixture = corpus.fixture("esignet-id-token").expect("exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + let header = decode_segment(signed.expose().split('.').next().expect("header")); + assert!(header.get("typ").is_none()); +} + +#[test] +fn each_declared_algorithm_signs_with_its_own_key() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let mut seen = BTreeSet::new(); + for fixture in corpus.fixtures() { + let Some(header) = &fixture.header else { + continue; + }; + let signed = signer.sign(fixture, &binding()).expect("signs"); + let signed_header = decode_segment(signed.expose().split('.').next().expect("header")); + assert_eq!(signed_header["alg"], header.alg.as_str()); + seen.insert(header.alg.clone()); + } + assert_eq!( + seen, + ["ES256", "HS256", "HS512", "RS256"] + .into_iter() + .map(str::to_owned) + .collect() + ); +} + +#[test] +fn the_opaque_fixture_signs_to_its_synthetic_string() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let fixture = corpus.fixture("supabase-api-key-opaque").expect("exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + assert!(signed.is_opaque()); + assert!(!signed.expose().contains('.')); + signer.verify_signature(&signed).expect("nothing to verify"); +} + +#[test] +fn the_public_key_set_holds_asymmetric_public_members_only() { + let signer = TokenSigner::new(); + let set = signer.public_key_set(); + let keys = set["keys"].as_array().expect("keys is an array"); + let algs: BTreeSet<&str> = keys.iter().filter_map(|k| k["alg"].as_str()).collect(); + assert_eq!(algs, BTreeSet::from(["ES256", "EdDSA", "RS256"])); + for key in keys { + for member in PRIVATE_JWK_MEMBERS { + assert!(key.get(member).is_none(), "public key set has `{member}`"); + } + } +} + +#[test] +fn two_signers_hold_different_keys() { + let corpus = corpus(); + let fixture = corpus.fixture("thunderid-user-access").expect("exists"); + let first = TokenSigner::new(); + let second = TokenSigner::new(); + assert_ne!(first.public_key_set(), second.public_key_set()); + let signed = first.sign(fixture, &binding()).expect("signs"); + assert!( + second.verify_signature(&signed).is_err(), + "a token from one run does not verify under another run's key" + ); +} + +#[test] +fn a_tampered_token_fails_verification() { + let corpus = corpus(); + let signer = TokenSigner::new(); + for id in ["thunderid-user-access", "supabase-api-key-anon"] { + let fixture = corpus.fixture(id).expect("exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + let mut segments: Vec = signed.expose().split('.').map(str::to_owned).collect(); + let mut claims = decode_segment(&segments[1]); + claims["sub"] = json!("someone-else"); + segments[1] = URL_SAFE_NO_PAD.encode(claims.to_string()); + let tampered = signed.with_text(segments.join(".")); + assert!(signer.verify_signature(&tampered).is_err(), "{id}"); + } +} + +#[test] +fn a_debug_print_of_a_signed_token_does_not_show_it() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let fixture = corpus.fixture("thunderid-user-access").expect("exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + let shown = format!("{signed:?}"); + assert!(!shown.contains(signed.expose())); + assert!(!shown.contains("eyJ")); +} + +#[test] +fn every_expectation_row_names_an_existing_fixture_and_a_known_product() { + let corpus = corpus(); + let expectations = corpus.expectations(); + let products: BTreeSet<&str> = expectations.products.iter().map(String::as_str).collect(); + assert_eq!(products.len(), 11); + let ids: BTreeSet<&str> = corpus.fixtures().iter().map(|f| f.id.as_str()).collect(); + assert!(!expectations.rows.is_empty()); + for row in &expectations.rows { + assert!( + ids.contains(row.fixture.as_str()), + "row names unknown fixture `{}`", + row.fixture + ); + for product in row.products.keys() { + assert!( + products.contains(product.as_str()), + "row for `{}` names unknown product `{product}`", + row.fixture + ); + } + let row_products: BTreeSet<&str> = row.products.keys().map(String::as_str).collect(); + assert_eq!(row_products, products, "row for `{}`", row.fixture); + } +} + +#[test] +fn every_fixture_has_a_row_and_no_row_repeats() { + let corpus = corpus(); + let rows = &corpus.expectations().rows; + let with_row: BTreeSet<&str> = rows.iter().map(|r| r.fixture.as_str()).collect(); + for fixture in corpus.fixtures() { + assert!(with_row.contains(fixture.id.as_str()), "{}", fixture.id); + } + let keys: BTreeSet<(String, Against, Configuration)> = rows + .iter() + .map(|r| (r.fixture.clone(), r.against, r.configuration)) + .collect(); + assert_eq!( + keys.len(), + rows.len(), + "a (fixture, against, configuration) repeats" + ); +} + +#[test] +fn no_negative_fixture_is_expected_to_be_admitted() { + let corpus = corpus(); + for row in &corpus.expectations().rows { + let fixture = corpus.fixture(&row.fixture).expect("exists"); + if fixture.class != FixtureClass::Negative { + continue; + } + for (product, cell) in &row.products { + for outcome in [&cell.main, &cell.target] { + assert!( + !matches!(outcome, Outcome::Admitted(_)), + "negative `{}` is admitted by `{product}`", + row.fixture + ); + } + } + } +} + +#[test] +fn landed_appears_exactly_when_a_milestone_changes_the_cell() { + let corpus = corpus(); + for row in &corpus.expectations().rows { + for (product, cell) in &row.products { + assert_eq!( + cell.landed.is_some(), + cell.changed_by.is_some(), + "`{}` / `{product}`", + row.fixture + ); + } + } +} + +#[test] +fn no_fixture_file_holds_a_private_jwk_member_or_a_live_looking_token() { + let dir = TokenCorpus::directory().join("fixtures"); + let mut checked = 0; + for entry in std::fs::read_dir(&dir).expect("fixtures directory reads") { + let path = entry.expect("entry").path(); + if path.extension().and_then(|e| e.to_str()) != Some("json") { + continue; + } + let text = std::fs::read_to_string(&path).expect("fixture reads"); + let value: Value = serde_json::from_str(&text).expect("fixture is JSON"); + walk(&value, &mut |node| match node { + Value::Object(map) => { + for member in PRIVATE_JWK_MEMBERS { + assert!( + !map.contains_key(member), + "{} holds member `{member}`", + path.display() + ); + } + } + Value::String(text) => { + assert!( + !text.starts_with("eyJ"), + "{} holds a string shaped like a JWT", + path.display() + ); + assert!( + !text.contains("PRIVATE KEY"), + "{} holds key material", + path.display() + ); + } + _ => {} + }); + checked += 1; + } + assert_eq!(checked, 21); +} + +fn walk(value: &Value, visit: &mut impl FnMut(&Value)) { + visit(value); + match value { + Value::Array(items) => items.iter().for_each(|item| walk(item, visit)), + Value::Object(map) => map.values().for_each(|item| walk(item, visit)), + _ => {} + } +} + +// --------------------------------------------------------------------------- +// Validation refuses a bad fixture +// --------------------------------------------------------------------------- + +#[test] +fn validation_accepts_the_minimal_fixture() { + TokenFixture::parse("unit-fixture", &minimal_fixture(json!({}))).expect("valid"); +} + +#[test] +fn validation_refuses_an_id_that_differs_from_the_file_name() { + let error = TokenFixture::parse("other-name", &minimal_fixture(json!({}))) + .expect_err("refused") + .to_string(); + assert!(error.contains("file name"), "{error}"); +} + +#[test] +fn validation_refuses_a_private_jwk_member() { + let error = parse_error(json!({ "notes": "x", "extra": { "kty": "EC", "d": "abc" } })); + assert!( + error.contains("private") || error.contains("unknown"), + "{error}" + ); + let mut text = minimal_fixture(json!({})); + text = text.replace( + "\"sub\":\"subject-1\"", + "\"sub\":\"subject-1\",\"jwk\":{\"kty\":\"oct\",\"k\":\"c2VjcmV0\"}", + ); + let error = TokenFixture::parse("unit-fixture", &text) + .expect_err("refused") + .to_string(); + assert!(error.contains("private"), "{error}"); +} + +#[test] +fn validation_refuses_a_string_shaped_like_a_jwt() { + let text = minimal_fixture(json!({})).replace( + "\"subject-1\"", + "\"eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiJ4In0.c2lnbmF0dXJl\"", + ); + let error = TokenFixture::parse("unit-fixture", &text) + .expect_err("refused") + .to_string(); + assert!(error.contains("JWT"), "{error}"); +} + +#[test] +fn validation_refuses_a_claim_named_in_omits() { + let error = parse_error(json!({ "omits": ["sub"] })); + assert!(error.contains("omits"), "{error}"); +} + +#[test] +fn validation_refuses_a_fixture_with_both_opaque_and_claims() { + let error = parse_error(json!({ "opaque": "synthetic-value" })); + assert!(error.contains("opaque"), "{error}"); +} + +#[test] +fn validation_refuses_missing_exp() { + let text = minimal_fixture(json!({})).replace(",\"exp\":{\"offsetSeconds\":300}", ""); + let error = TokenFixture::parse("unit-fixture", &text) + .expect_err("refused") + .to_string(); + assert!(error.contains("exp"), "{error}"); +} + +#[test] +fn validation_refuses_an_algorithm_outside_the_signer_set() { + let error = parse_error(json!({ "header": { "alg": "none", "kid": { "generated": true } } })); + assert!(error.contains("alg"), "{error}"); +} + +#[test] +fn validation_refuses_an_unknown_directive_member() { + let text = minimal_fixture(json!({})) + .replace("{\"bind\":\"issuer\"}", "{\"bind\":\"issuer\",\"extra\":1}"); + let error = TokenFixture::parse("unit-fixture", &text) + .expect_err("refused") + .to_string(); + assert!(error.contains("iss"), "{error}"); +} + +#[test] +fn validation_refuses_an_unknown_top_level_member() { + let error = parse_error(json!({ "surprise": true })); + assert!(error.contains("surprise"), "{error}"); +} + +// --------------------------------------------------------------------------- +// The driver +// --------------------------------------------------------------------------- + +#[test] +fn the_driver_runs_every_applicable_row_and_hands_the_closure_a_verifiable_token() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let mut calls = 0usize; + let report = corpus + .run_product("breg", &signer, ISSUER, AUDIENCE, |case| { + calls += 1; + signer + .verify_signature(&case.token) + .expect("token verifies"); + Outcome::Refused(Stage::Header) + }) + .expect("the run completes"); + assert_eq!(report.product, "breg"); + assert_eq!(report.rows.len(), corpus.expectations().rows.len()); + let skipped = report + .rows + .iter() + .filter(|row| matches!(row.comparison, Comparison::NotApplicable)) + .count(); + assert_eq!(calls + skipped, report.rows.len()); + assert!(calls > 0); + assert!( + !report.mismatches().is_empty(), + "a stand-in refusing everything differs" + ); +} + +#[test] +fn the_driver_compares_against_main_unless_the_cell_has_landed() { + let corpus = corpus(); + let signer = TokenSigner::new(); + // Answer each case with exactly what the expectation says, then compare. + let expected = corpus.expectations().clone(); + let report = corpus + .run_product("casework", &signer, ISSUER, AUDIENCE, |case| { + let row = expected + .rows + .iter() + .find(|row| { + row.fixture == case.fixture.id + && row.against == case.against + && row.configuration == case.configuration + }) + .expect("row exists"); + row.products["casework"].expected().clone() + }) + .expect("the run completes"); + assert!(report.mismatches().is_empty(), "{:?}", report.mismatches()); + // The report never carries a token. + assert!(!format!("{report:?}").contains("eyJ")); +} + +#[test] +fn a_literal_audience_is_the_configured_audience_only_for_a_positive_recipe_row() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let mut observed: Vec<(String, Configuration, String)> = Vec::new(); + corpus + .run_product("breg", &signer, ISSUER, AUDIENCE, |case| { + if case.fixture.id == "supabase-user-access" || case.fixture.id == "keycloak-id-token" { + observed.push(( + case.fixture.id.clone(), + case.configuration, + case.audience.clone(), + )); + } + Outcome::None + }) + .expect("the run completes"); + assert!(observed.contains(&( + "supabase-user-access".to_owned(), + Configuration::Default, + AUDIENCE.to_owned() + ))); + assert!(observed.contains(&( + "supabase-user-access".to_owned(), + Configuration::Recipe, + "authenticated".to_owned() + ))); + assert!(observed + .iter() + .filter(|(id, ..)| id == "keycloak-id-token") + .all(|(_, _, audience)| audience == AUDIENCE)); +} + +#[test] +fn the_driver_refuses_an_unknown_product() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let error = corpus + .run_product("nonesuch", &signer, ISSUER, AUDIENCE, |_| Outcome::None) + .expect_err("refused") + .to_string(); + assert!(error.contains("nonesuch"), "{error}"); +} + +#[test] +fn outcomes_parse_and_print_the_values_expected_yaml_uses() { + for text in [ + "admitted", + "admitted/human", + "admitted/unspecified", + "refused/token-type", + "refused/claims", + "none", + "n-a", + "unknown", + ] { + let outcome: Outcome = text.parse().expect("parses"); + assert_eq!(outcome.to_string(), text); + } + for text in ["refused", "refused/nowhere", "admitted/", "yes", ""] { + assert!(text.parse::().is_err(), "`{text}`"); + } +} + +#[test] +fn the_async_driver_gives_the_same_report_as_the_sync_driver() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let answer = |case: ®istry_platform_testing::FixtureCase| { + if case.fixture.class == FixtureClass::Negative { + Outcome::Refused(Stage::Header) + } else { + Outcome::Admitted(None) + } + }; + let sync = corpus + .run_product("messaging", &signer, ISSUER, AUDIENCE, |case| answer(case)) + .expect("sync run"); + let asynchronous = futures::executor::block_on(corpus.run_product_async( + "messaging", + &signer, + ISSUER, + AUDIENCE, + |case| async move { answer(&case) }, + )) + .expect("async run"); + assert_eq!(sync, asynchronous); +} diff --git a/crates/registry-render/Cargo.toml b/crates/registry-render/Cargo.toml index 5614340732..c0abdb5972 100644 --- a/crates/registry-render/Cargo.toml +++ b/crates/registry-render/Cargo.toml @@ -55,6 +55,7 @@ zeroize = { workspace = true } [dev-dependencies] async-trait = { workspace = true } +registry-platform-testing = { workspace = true, features = ["token-fixtures"] } registry-platform-crypto = { workspace = true, features = ["cms-signing", "test-support", "transit"] } registry-render-client.workspace = true tokio = { workspace = true, features = ["test-util"] } diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index 0682a4a26a..7ec23373d1 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -153,6 +153,9 @@ pub(crate) async fn authenticate( }) } +#[cfg(test)] +mod token_characterisation; + #[cfg(test)] pub(crate) mod tests { use super::*; diff --git a/crates/registry-render/src/auth/token_characterisation.rs b/crates/registry-render/src/auth/token_characterisation.rs new file mode 100644 index 0000000000..f7da0a2610 --- /dev/null +++ b/crates/registry-render/src/auth/token_characterisation.rs @@ -0,0 +1,133 @@ +//! Characterises which identity-provider tokens Render's real caller +//! authentication admits, against the token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Each row loads a runtime file the way `serve` does, builds the verifier +//! through `verifier`, and presents the fixture to `authenticate` for the +//! render scope, the call every render and document route makes. The module +//! sits under `auth` so it can also ask the verifier for the check that +//! refused a token, which `AuthenticationError` does not carry. +use super::*; +use registry_platform_oidc::OidcError; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::Value; +use std::path::Path; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "urn:render:test"; +const KEY_FILE: &str = "issuer-keys.json"; +const PLACEHOLDER_CLIENT: &str = "journey-app"; + +fn literal(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the token names, read the way the verifier reads it. +fn client_of(fixture: &TokenFixture) -> Option { + literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) +} + +fn stage_of(error: &OidcError) -> Outcome { + format!("refused/{}", error.authentication_stage().label()) + .parse() + .expect("every authentication stage label is a result value") +} + +/// A runtime file for one row. The recipe for a token that names no client +/// writes `unrestricted`, as the runtime allows; every other row lists +/// the fixture's client, or a placeholder when the token names none. +fn write_runtime(home: &Path, case: &FixtureCase) -> std::path::PathBuf { + let clients = match (client_of(&case.fixture), case.configuration) { + (Some(client), _) => format!("[{client}]"), + (None, Configuration::Recipe) => "unrestricted".to_owned(), + (None, _) => format!("[{PLACEHOLDER_CLIENT}]"), + }; + let runtime = format!( + "apiVersion: {}\nkind: {}\nlistener:\n bind: 127.0.0.1:18080\npackage:\n root: {}\nsecretProviders:\n file:\n root: {}\nauthentication:\n oidc:\n issuer: {}\n audience: {}\n allowedClients: {}\n jwksSource:\n type: static\n documentRef: secret:file/{KEY_FILE}\naudit:\n path: {}\n", + crate::runtime::RUNTIME_API_VERSION, + crate::runtime::RUNTIME_KIND, + home.join("bundle").display(), + home.display(), + case.issuer, + case.audience, + clients, + home.join("audit").join("render.jsonl").display(), + ); + let path = home.join("runtime.yaml"); + std::fs::write(&path, runtime).expect("write the runtime file"); + path +} + +async fn observe(verifier: &TokenVerifier, token: &str) -> Outcome { + let verdict = verifier.verify(token).await; + let admission = authenticate(verifier, token, RENDER_SCOPE).await; + match (admission, verdict) { + (Ok(_), Ok(_)) => Outcome::Admitted(None), + (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), + (Err(_), Err(error)) => stage_of(&error), + (Err(AuthenticationError::Forbidden { .. }), Ok(_)) => { + "refused/scope".parse().expect("result value") + } + (Err(AuthenticationError::Refused), Ok(_)) => { + "refused/claims".parse().expect("result value") + } + (Err(AuthenticationError::Unavailable), Ok(_)) => { + "refused/unavailable".parse().expect("result value") + } + } +} + +/// The corpus public keys a static key document may hold: it admits RSA and +/// EC keys only, so the corpus's EdDSA key is left out. +fn static_key_document(signer: &TokenSigner) -> String { + let mut keys = signer.public_key_set(); + keys["keys"] + .as_array_mut() + .expect("a key set lists keys") + .retain(|key| key["kty"] != "OKP"); + keys.to_string() +} + +#[tokio::test] +async fn caller_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let scratch = tempfile::tempdir().expect("home directory"); + let home = scratch + .path() + .canonicalize() + .expect("physical home directory"); + std::fs::create_dir(home.join("bundle")).expect("package directory"); + std::fs::create_dir(home.join("audit")).expect("audit directory"); + let key_file = home.join(KEY_FILE); + std::fs::write(&key_file, static_key_document(&signer)).expect("write the key set"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + } + let home = &home; + let report = corpus + .run_product_async("render", &signer, ISSUER, AUDIENCE, |case| async move { + let path = write_runtime(home, &case); + let (runtime, _) = + crate::runtime::load(&path).expect("the runtime file loads and validates"); + let verifier = verifier(&runtime) + .await + .expect("the verifier builds over the static key set") + .expect("the runtime declares oidc authentication"); + observe(&verifier, case.token.expose()).await + }) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran" + ); + report.assert_matches(); +} diff --git a/crates/registry-scheduling/Cargo.toml b/crates/registry-scheduling/Cargo.toml index 2fb8bbffad..9e81ef5156 100644 --- a/crates/registry-scheduling/Cargo.toml +++ b/crates/registry-scheduling/Cargo.toml @@ -68,7 +68,7 @@ uuid = { workspace = true, features = ["serde"] } [dev-dependencies] jsonschema.workspace = true -registry-platform-testing = { workspace = true, features = ["migration-pins"] } +registry-platform-testing = { workspace = true, features = ["migration-pins", "token-fixtures"] } reqwest.workspace = true serde_norway.workspace = true tempfile.workspace = true diff --git a/crates/registry-scheduling/tests/token_characterisation.rs b/crates/registry-scheduling/tests/token_characterisation.rs new file mode 100644 index 0000000000..edcc9c3f08 --- /dev/null +++ b/crates/registry-scheduling/tests/token_characterisation.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Characterisation of Scheduling's bearer authentication against the token +//! fixture corpus (`products/platform/conformance/tokens`). +//! +//! Every row of `expected.yaml` with a `scheduling` cell is run through the +//! authenticator the server builds: the verifier profile and the authenticator +//! settings come from a `RuntimeConfig` loaded from a runtime file, the keys +//! from that file's static key source, and the credential goes through +//! `SchedulingAuthenticator::authenticate_read`, the plain read. No database is +//! involved. +//! +//! The authenticator reports a verifier refusal as one error. The stage of that +//! refusal is read by running the same token through a second verifier built +//! from the same configuration and keys, so the stage is the shared verifier's +//! own label. + +use std::collections::BTreeMap; +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; + +use registry_platform_config::write_package; +use registry_platform_oidc::TokenVerifier; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenSigner, +}; +use registry_scheduling::auth::{AuthenticationError, SchedulingAuthenticator}; +use registry_scheduling::config::{package_limits, RuntimeConfig, PACKAGE_COMMAND}; +use registry_scheduling::runtime::secret_resolver; +use registry_scheduling_core::{ + AUTHORED_POLICY_FILE, SCHEDULING_RUNTIME_API_VERSION, SCHEDULING_RUNTIME_KIND, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://identity.example.test"; +const AUDIENCE: &str = "urn:example:scheduling"; +/// The client a fixture without a client claim is configured against: the +/// allowed list always holds one client, as the runtime requires. +const PLACEHOLDER_CLIENT: &str = "journey-app"; +const PLACEHOLDER_SCOPE: &str = "records:get"; +/// A scope no fixture carries, so the explain scope never equals the read scope. +const EXPLAIN_SCOPE: &str = "corpus:explain"; + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the fixture names, from `client_id` or `azp`. +fn fixture_client(case: &FixtureCase) -> String { + literal_string(case, "client_id") + .or_else(|| literal_string(case, "azp")) + .unwrap_or_else(|| PLACEHOLDER_CLIENT.to_owned()) +} + +/// The claim the configuration reads scopes from. +fn scope_claim(case: &FixtureCase) -> &'static str { + if case.configuration == Configuration::Recipe + && case.fixture.claims.contains_key("scp") + && !case.fixture.claims.contains_key("scope") + { + "scp" + } else { + "scope" + } +} + +/// The first scope the fixture carries in the claim the configuration names. +fn read_scope(case: &FixtureCase, claim: &str) -> String { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => text.split_whitespace().next(), + Some(ClaimValue::Literal(Value::Array(items))) => items.first().and_then(Value::as_str), + _ => None, + } + .unwrap_or(PLACEHOLDER_SCOPE) + .to_owned() +} + +fn write_private(path: &Path, bytes: &[u8]) { + fs::write(path, bytes).expect("write a private file"); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("restrict the file"); +} + +/// The key set a static key source accepts: it refuses a set holding any key +/// that is not RSA or EC, so the corpus's EdDSA key stays out of the file. No +/// admitted algorithm uses it. +fn static_key_set(jwks: &Value) -> Value { + let keys: Vec = jwks["keys"] + .as_array() + .expect("a key set with a keys array") + .iter() + .filter(|key| matches!(key["kty"].as_str(), Some("RSA" | "EC"))) + .cloned() + .collect(); + json!({ "keys": keys }) +} + +fn refusal(stage_label: &str) -> Outcome { + format!("refused/{stage_label}") + .parse() + .expect("a stage the corpus knows") +} + +async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a runtime directory"); + let secrets = root.path().join("secrets"); + fs::create_dir(&secrets).expect("a secrets directory"); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).expect("restrict secrets"); + write_private( + &secrets.join("issuer-jwks"), + &serde_json::to_vec(&static_key_set(&case.jwks)).expect("a key set"), + ); + let claim = scope_claim(&case); + let scope = read_scope(&case, claim); + let runtime_path = root.path().join("runtime.json"); + fs::write( + &runtime_path, + serde_json::to_vec(&json!({ + "apiVersion": SCHEDULING_RUNTIME_API_VERSION, + "kind": SCHEDULING_RUNTIME_KIND, + "identity": {"databaseId": "token-characterisation"}, + "package": {"root": package_root}, + "listener": {"bind": "127.0.0.1:0", "tlsTermination": "development-loopback", "networkExposure": "private-address"}, + "secretProviders": {"file": {"root": secrets}, "environment": {}}, + "database": { + "runtimeUrlRef": "secret:env/SCHEDULING_RUNTIME_URL", + "migrationUrlRef": "secret:env/SCHEDULING_MIGRATION_URL" + }, + "authentication": {"oidc": { + "issuer": case.issuer, + "audience": case.audience, + "jwksSource": {"type": "static", "documentRef": "secret:file/issuer-jwks"}, + "allowedClients": [fixture_client(&case)], + "scopeClaim": claim, + "readsScope": scope, + "explainScope": EXPLAIN_SCOPE + }}, + "taskGrantStatus": "unchecked-final-fifteen-minutes", + "audit": {"path": root.path().join("audit.jsonl"), "hashKeyRef": "secret:file/audit-key"}, + "destinations": {}, + "retention": {"receiptRetentionDays": 7} + })) + .expect("a runtime document"), + ) + .expect("write the runtime file"); + let config = RuntimeConfig::load(&runtime_path).expect("the runtime configuration loads"); + let resolver = secret_resolver(&config).expect("the secret resolver"); + let (verifier, keys) = config + .oidc_verifier(&resolver) + .await + .expect("the static key source"); + + let authenticator = + SchedulingAuthenticator::new(&config.authentication.oidc, verifier.clone(), keys.clone()); + let token = case.token.expose(); + match authenticator.authenticate_read(token).await { + Ok(caller) => Outcome::Admitted(Some(caller.actor_kind)), + Err(AuthenticationError::Claims) => refusal("claims"), + Err(AuthenticationError::Unavailable) => refusal("unavailable"), + Err(error @ (AuthenticationError::Refused | AuthenticationError::Profile)) => { + let reference = TokenVerifier::new(verifier, keys); + match reference.verify(token).await { + Err(failure) => refusal(failure.authentication_stage().label()), + Ok(verified) if error == AuthenticationError::Profile => { + if verified.scopes.iter().any(|held| held == &scope) { + refusal("profile") + } else { + refusal("scope") + } + } + // The credential is not a compact access token, so the + // verifier is never reached. + Ok(_) => refusal("header"), + } + } + } +} + +/// The standalone example policy, installed as a package the runtime file can name. +fn installed_example_package() -> tempfile::TempDir { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a package directory"); + write_package( + &root.path().join("package"), + &BTreeMap::from([( + AUTHORED_POLICY_FILE.to_owned(), + include_bytes!( + "../../../products/scheduling/examples/standalone-exact-time/scheduling.yaml" + ) + .to_vec(), + )]), + None, + &package_limits(), + PACKAGE_COMMAND, + ) + .expect("the installed example package"); + root +} + +#[tokio::test] +async fn scheduling_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let installed = installed_example_package(); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("scheduling", &signer, ISSUER, AUDIENCE, |case| { + observe(installed.path().join("package"), case) + }) + .await + .expect("every scheduling row is planned and signed"); + let run = report + .rows + .iter() + .filter(|row| row.observed.is_some()) + .count(); + assert!(run > 0, "no scheduling row ran"); + eprintln!( + "scheduling: {run} rows ran, {} differ", + report.mismatches().len() + ); + report.assert_matches(); +} diff --git a/products/platform/conformance/tokens/README.md b/products/platform/conformance/tokens/README.md new file mode 100644 index 0000000000..7d9e118158 --- /dev/null +++ b/products/platform/conformance/tokens/README.md @@ -0,0 +1,114 @@ +# Token fixtures + +This folder holds the tokens that real identity providers issue, reduced to their shape. Every product that verifies a caller's token is tested against them. The aim is to know, for each product and each kind of token, whether the token is admitted or refused, and at which check. + +A fixture is data. It has no signature and no key. The test loader signs it when a test runs. + +## What is here + +| Path | Content | +| --- | --- | +| `fixtures/.json` | One decoded token shape per file. | +| `expected.yaml` | The expected result for each fixture, product and configuration. | +| `token-fixture.schema.json` | The JSON Schema every fixture must satisfy. | + +The loader, the signer and the test driver live in `crates/registry-platform-testing`, behind the `token-fixtures` feature. Each product's test passes its own authenticator to that driver. + +## Two kinds of fixture + +A **positive** fixture is a token that a correctly configured product can admit for a plain read. It is here to show what a product must accept from a provider's stock output, or what it refuses today and why. + +A **negative** fixture is a token that every product must refuse, in every configuration. Examples are an ID token, a refresh token, an API key, and a token from an issuer that no product trusts. A negative fixture admitted by any product is a security defect. Report it through `SECURITY.md`. Do not open a public issue or pull request. + +## Providers covered + +Keycloak, ThunderID, Microsoft Entra ID, Supabase Auth and eSignet. One fixture, `rstack-dev-run-user`, holds the shape the development runner signs. One fixture, `identity-only`, is a token built to carry identity and nothing else. + +## What a fixture file holds + +```json +{ + "schema": "registry.token-fixture/v1", + "id": "keycloak-client-credentials", + "class": "positive", + "provider": "keycloak", + "kind": "client-access", + "tokenUse": "access", + "subjectKind": "service", + "source": { "basis": "observed", "...": "..." }, + "header": { "alg": "RS256", "typ": "JWT", "kid": { "generated": true } }, + "claims": { + "iss": { "bind": "issuer" }, + "aud": { "bind": "audience" }, + "azp": "journey-service", + "iat": { "offsetSeconds": 0 }, + "exp": { "offsetSeconds": 300 } + }, + "omits": ["registry_actor_kind"] +} +``` + +- `class` is `positive` or `negative`. +- `kind` and `tokenUse` say what the token is: an access token, an ID token, a refresh token or an API key. +- `subjectKind` says who the token stands for: a `user`, a `service` or `unspecified`. +- `header` and `claims` keep the header members and claim names that the provider issues. Values keep their JSON type. +- `omits` lists claims whose absence is the point. The loader checks they are absent. +- `opaque` replaces `header` and `claims` for a credential that is not a JWT. Its value is a synthetic string. +- `notes` explains a choice a reader would otherwise have to guess. + +### Values + +A claim value is plain JSON, or one of three directives. + +| Directive | Meaning | +| --- | --- | +| `{ "bind": "issuer" }` or `{ "bind": "audience" }` | Take the issuer or the audience of the product under test. The fixture then tests the token's shape, and not a mismatch the test set up. | +| `{ "offsetSeconds": 300 }` | Seconds after the moment of signing. A lifetime is part of the shape. | +| `{ "generated": true }` | A value the loader makes at signing time, such as a key identifier. | + +A literal `iss` or `aud` models a value the provider fixes. Keycloak's stock audience `account`, Supabase's `authenticated`, the client identifier in an ID token and the eSignet issuer are literals. + +All identifiers, addresses and names in a fixture are synthetic. Hosts use `example.test` or the documentation address block. + +## How a fixture is signed + +The loader makes one key for each algorithm once per test process. It serves the public half as a static key set and signs each fixture with the private half. The private half is never written to disk. This folder holds no private key and no live token. + +A corpus test fails on any string shaped like a compact JWT, and on any private JWK member name (`d`, `p`, `q`, `dp`, `dq`, `qi`, `k`). + +## Where a fixture comes from + +Every fixture states its source in `source.basis`. + +- `observed` with `observedFrom: capture`. The token was issued by a running provider. The fixture names the provider version, the container image digest, and the capture file. Only claim names, header members and value types were kept. +- `observed` with `observedFrom: code`. The shape was read from the code that signs it. +- `documentation`. The shape comes from the provider's public documentation. The fixture names the page. Replace a documentation fixture with an observed one as soon as you can capture a token. +- `constructed`. The token was built on purpose and the fixture says why. + +## expected.yaml + +`expected.yaml` has one row for each fixture, `against` value and configuration. Each row has one cell for every product that verifies a token. + +A cell holds: + +- `main`: the result today. +- `target`: the result the caller contract work aims for. +- `changedBy`: the milestone that changes the result, such as `M7`, or `none`. +- `landed`: present when `changedBy` is a milestone. It is `false` until that milestone makes `target` true. +- `basis`: `inferred` while `main` is a reading of the code, `observed` once a test has run the fixture through the product. +- `reason` and `targetReason`: why a `main` or a `target` is `unknown`, `n-a` or `none`, or why a product cannot follow one of the driver's choices listed at the head of `expected.yaml`. + +A result is `admitted`, `admitted/`, `admitted/unspecified`, `refused/`, `none`, `n-a` or `unknown`. A stage is one of the verifier's labels (`header`, `algorithm`, `token-type`, `key`, `signature`, `issuer`, `audience`, `time`, `client`, `scope`, `profile`, `unavailable`) or `claims`, which a product uses for its own claim checks. + +The test asserts `target` where `landed` is `true` and `main` everywhere else. Work on a milestone goes row by row. Set `landed: true`, watch the test fail, make the change, watch it pass. + +The head of `expected.yaml` lists the choices the driver makes for every row, such as which client list and which read scope a product is given. + +## Add a fixture + +1. Capture the token from a running provider. Decode it. Keep claim names, header members and value types. Never save the token itself. +2. Write `fixtures/.json`. The file name equals `id`. Replace every value that identifies a person, tenant, host or client with a synthetic one. Use `bind` for the issuer and the audience unless the provider fixes them. +3. Fill in `source`. Add `omits` for any claim whose absence matters. +4. Check the file against `token-fixture.schema.json`. +5. Add a row to `expected.yaml` for each configuration you want to cover, with a cell for every product. If you could not read a product's code to the end, write `unknown` and give the reason. Do not guess. +6. Run the corpus test. It checks that every fixture has a row, that every row has every product, and that no negative fixture has a `target` of `admitted`. diff --git a/products/platform/conformance/tokens/expected.yaml b/products/platform/conformance/tokens/expected.yaml new file mode 100644 index 0000000000..8e079989fd --- /dev/null +++ b/products/platform/conformance/tokens/expected.yaml @@ -0,0 +1,604 @@ +# Expected results of the token fixture corpus, per product. +# +# A cell with `basis: inferred` is a reading of the product's authentication code. +# A cell with `basis: observed` was run through the product's own verifier by its +# characterisation test (`token_characterisation` in each product crate), and +# `main` holds the result that test observed. +# +# Cell fields +# main the result at the commit the corpus was written against. It changes only +# when a characterisation test observes a different result, and then the +# cell's `basis` becomes `observed` +# target the result the caller-contract work is meant to give +# changedBy the milestone that changes the result, or `none` +# landed false until that milestone makes `target` true. A test asserts `target` +# where `landed` is true and `main` otherwise +# basis inferred or observed +# reason why `main` is `unknown` or `n-a` +# targetReason why `target` is `unknown` +# +# Values +# admitted, admitted/, admitted/unspecified (the token names no kind +# and the product admits that), refused/, none (the configuration needs a +# setting the product does not have), n-a (the product has no such concept), +# unknown (not determined, with a reason). +# Stages: header, algorithm, token-type, key, signature, issuer, audience, time, +# client, scope, profile, unavailable (the shared verifier's labels) and claims +# (a product's own claim extraction). +# +# How the fixtures are run (what a driver sets up for each row) +# 1. Issuer and audience are the product's own. A fixture with a literal aud is +# checked against that literal only in the `recipe` configuration of a +# positive fixture, where the configured audience line names it. +# 2. Every product holds an allowed client list that names the fixture's client. +# The `recipe` configuration of a fixture with no client claim leaves the list +# unrestricted where the product allows it. +# 3. The product's read scope is the first scope the fixture carries, read from +# the scope claim the configuration names. +# 4. The principal claim is `sub`. Every lifetime the fixtures use is within each +# product's maximum. +# 5. Algorithm settings, where a product has one, are set to the fixture's. +# 6. `against: human-only-profile` selects a profile that admits only people. + +schema: registry.token-fixture-expectations/v1 +products: [breg, casework, messaging, scheduling, documents, coordinator, adapter, evidence, render, mcp-edge, evidence-oid4vci] +configurations: + default: the issuer block as the product's starter writes it + recipe: the documented lines for the fixture's provider, which name the token type, the scope claim, the client rule and an audience that a fixture states literally. none where main has no such setting + jwt-accepted: the default block with token type JWT accepted, for the ID token fixtures. none where main has no such setting +rows: + - fixture: thunderid-user-access + against: plain-read + configuration: default + products: + breg: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } + casework: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + messaging: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } + scheduling: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } + documents: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } + coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence: { main: refused/claims, basis: observed, target: admitted/human, changedBy: M7, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } + - fixture: thunderid-user-access + against: plain-read + configuration: recipe + products: + breg: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } + casework: { main: admitted, basis: observed, target: admitted, changedBy: none } + messaging: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } + scheduling: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } + documents: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } + coordinator: { main: admitted, basis: observed, target: admitted, changedBy: none } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence: { main: refused/claims, basis: observed, target: admitted/human, changedBy: M7, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } + - fixture: thunderid-client-credentials + against: plain-read + configuration: default + products: + breg: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } + casework: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + messaging: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } + scheduling: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } + documents: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } + coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence: { main: refused/claims, basis: observed, target: admitted/service, changedBy: M7, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } + - fixture: thunderid-client-credentials + against: plain-read + configuration: recipe + products: + breg: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } + casework: { main: admitted, basis: observed, target: admitted, changedBy: none } + messaging: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } + scheduling: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } + documents: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } + coordinator: { main: admitted, basis: observed, target: admitted, changedBy: none } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence: { main: refused/claims, basis: observed, target: admitted/service, changedBy: M7, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } + - fixture: keycloak-user-access + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: keycloak-user-access + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + coordinator: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + adapter: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + render: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + - fixture: keycloak-client-credentials + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: keycloak-client-credentials + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + coordinator: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + adapter: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + render: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + - fixture: keycloak-client-credentials-stock + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/audience, changedBy: none } + - fixture: supabase-user-access + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: supabase-user-access + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + messaging: { main: none, basis: inferred, target: none, changedBy: none } + scheduling: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + documents: { main: none, basis: inferred, target: none, changedBy: none } + coordinator: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + adapter: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + mcp-edge: { main: none, basis: inferred, target: refused/client, changedBy: none } + evidence-oid4vci: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + - fixture: supabase-oauth-server-user-access + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: supabase-oauth-server-user-access + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + messaging: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + scheduling: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + documents: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + coordinator: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + adapter: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + mcp-edge: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence-oid4vci: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + - fixture: entra-v2-user-access + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: entra-v2-user-access + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + coordinator: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + adapter: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + render: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + - fixture: entra-v2-app-access + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: entra-v2-app-access + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + coordinator: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + adapter: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } + render: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + - fixture: identity-only + against: plain-read + configuration: default + products: + breg: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + casework: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + messaging: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + scheduling: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + documents: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + coordinator: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + adapter: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + evidence: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + render: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + mcp-edge: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + evidence-oid4vci: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + - fixture: identity-only + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + messaging: { main: none, basis: inferred, target: none, changedBy: none } + scheduling: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + documents: { main: none, basis: inferred, target: none, changedBy: none } + coordinator: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + adapter: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + mcp-edge: { main: refused/client, basis: observed, target: refused/client, changedBy: none } + evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + - fixture: rstack-dev-run-user + against: plain-read + configuration: default + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + messaging: { main: admitted/unspecified, basis: observed, target: admitted/unspecified, changedBy: none } + scheduling: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + documents: { main: refused/profile, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided in M7" } + coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } + - fixture: thunderid-client-credentials + against: human-only-profile + configuration: recipe + products: + breg: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } + casework: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } + messaging: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } + scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } + documents: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } + coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence: { main: refused/claims, basis: observed, target: refused/profile, changedBy: M7, landed: false } + render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + - fixture: keycloak-client-credentials + against: human-only-profile + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: refused/profile, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } + documents: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + - fixture: identity-only + against: human-only-profile + configuration: recipe + products: + breg: { main: none, basis: observed, target: refused/profile, changedBy: M7, landed: false, reason: "BReg does not start: a profile that names requester clients cannot be combined with allowedClients unrestricted" } + casework: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } + documents: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence: { main: refused/scope, basis: observed, target: refused/profile, changedBy: M7, landed: false } + render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + - fixture: thunderid-id-token + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: thunderid-id-token + against: plain-read + configuration: jwt-accepted + products: + breg: { main: refused/audience, basis: observed, target: refused/audience, changedBy: none } + casework: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + adapter: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + render: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + - fixture: keycloak-id-token + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: keycloak-id-token + against: plain-read + configuration: jwt-accepted + products: + breg: { main: refused/audience, basis: observed, target: refused/audience, changedBy: none } + casework: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + adapter: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + render: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + - fixture: supabase-id-token + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: supabase-id-token + against: plain-read + configuration: jwt-accepted + products: + breg: { main: refused/audience, basis: observed, target: refused/audience, changedBy: none } + casework: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + adapter: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + render: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + - fixture: entra-id-token + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: entra-id-token + against: plain-read + configuration: jwt-accepted + products: + breg: { main: refused/client, basis: observed, target: refused/token-type, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + messaging: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + scheduling: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + coordinator: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + adapter: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + render: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + mcp-edge: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + - fixture: keycloak-refresh-token + against: plain-read + configuration: default + products: + breg: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + casework: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + messaging: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + scheduling: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + documents: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + coordinator: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + adapter: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + evidence: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + render: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + mcp-edge: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + evidence-oid4vci: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + - fixture: supabase-api-key-anon + against: plain-read + configuration: default + products: + breg: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + casework: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + messaging: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + scheduling: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + documents: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + coordinator: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + adapter: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + evidence: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + render: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + mcp-edge: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + evidence-oid4vci: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + - fixture: supabase-api-key-service-role + against: plain-read + configuration: default + products: + breg: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + casework: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + messaging: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + scheduling: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + documents: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + coordinator: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + adapter: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + evidence: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + render: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + mcp-edge: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + evidence-oid4vci: { main: refused/algorithm, basis: observed, target: refused/algorithm, changedBy: none } + - fixture: supabase-api-key-opaque + against: plain-read + configuration: default + products: + breg: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + casework: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + messaging: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + scheduling: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + documents: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + coordinator: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + adapter: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + evidence: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + render: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + mcp-edge: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + evidence-oid4vci: { main: refused/header, basis: observed, target: refused/header, changedBy: none } + - fixture: esignet-access-token + against: plain-read + configuration: default + products: + breg: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + casework: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + messaging: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + scheduling: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + documents: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + coordinator: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + adapter: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + evidence: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + render: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + mcp-edge: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + evidence-oid4vci: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + - fixture: esignet-id-token + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } diff --git a/products/platform/conformance/tokens/fixtures/entra-id-token.json b/products/platform/conformance/tokens/fixtures/entra-id-token.json new file mode 100644 index 0000000000..5d83dc567f --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/entra-id-token.json @@ -0,0 +1,50 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "entra-id-token", + "class": "negative", + "provider": "entra", + "kind": "user-id", + "tokenUse": "id", + "subjectKind": "user", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://learn.microsoft.com/en-us/entra/identity-platform/id-token-claims-reference", + "note": "The header typ is JWT and alg is RS256, the same as an access token. aud is the application's own ID. It has a nonce and no scp or roles." + }, + "header": { + "alg": "RS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "iss": { + "bind": "issuer" + }, + "aud": { + "bind": "audience" + }, + "sub": "00000000-0000-4000-8000-000000000001", + "nonce": "synthetic-nonce", + "ver": "2.0", + "iat": { + "offsetSeconds": 0 + }, + "nbf": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 3600 + } + }, + "omits": [ + "scope", + "scp", + "roles", + "client_id", + "azp" + ], + "notes": "aud is bound to the product's audience on purpose. When a client and an API share one app registration the ID token's aud equals the API's audience, so aud alone cannot refuse it. This is the hardest case for a check that refuses ID tokens when the token type JWT is accepted." +} diff --git a/products/platform/conformance/tokens/fixtures/entra-v2-app-access.json b/products/platform/conformance/tokens/fixtures/entra-v2-app-access.json new file mode 100644 index 0000000000..6e59185dd5 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/entra-v2-app-access.json @@ -0,0 +1,53 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "entra-v2-app-access", + "class": "positive", + "provider": "entra", + "kind": "client-access", + "tokenUse": "access", + "subjectKind": "service", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://learn.microsoft.com/en-us/entra/identity-platform/access-token-claims-reference", + "note": "An application token (client credentials) carries roles and no scp." + }, + "header": { + "alg": "RS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "iss": { + "bind": "issuer" + }, + "aud": { + "bind": "audience" + }, + "sub": "00000000-0000-4000-8000-000000000002", + "azp": "journey-service", + "roles": [ + "journey.read" + ], + "ver": "2.0", + "iat": { + "offsetSeconds": 0 + }, + "nbf": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 3600 + } + }, + "omits": [ + "scope", + "scp", + "client_id", + "appid", + "registry_actor_kind" + ], + "notes": "The documentation gives no lifetime. 3600 seconds is a test choice." +} diff --git a/products/platform/conformance/tokens/fixtures/entra-v2-user-access.json b/products/platform/conformance/tokens/fixtures/entra-v2-user-access.json new file mode 100644 index 0000000000..e3e08e7a6c --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/entra-v2-user-access.json @@ -0,0 +1,51 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "entra-v2-user-access", + "class": "positive", + "provider": "entra", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://learn.microsoft.com/en-us/entra/identity-platform/access-token-claims-reference", + "note": "Header typ is always JWT. The version 2.0 token carries azp and scp. aud is the API's own client ID, written here as the bound audience." + }, + "header": { + "alg": "RS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "iss": { + "bind": "issuer" + }, + "aud": { + "bind": "audience" + }, + "sub": "00000000-0000-4000-8000-000000000001", + "azp": "journey-app", + "scp": "journey.read", + "ver": "2.0", + "iat": { + "offsetSeconds": 0 + }, + "nbf": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 3600 + } + }, + "omits": [ + "scope", + "roles", + "client_id", + "appid", + "registry_actor_kind" + ], + "notes": "The documentation gives no lifetime. 3600 seconds is a test choice." +} diff --git a/products/platform/conformance/tokens/fixtures/esignet-access-token.json b/products/platform/conformance/tokens/fixtures/esignet-access-token.json new file mode 100644 index 0000000000..160500222d --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/esignet-access-token.json @@ -0,0 +1,42 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "esignet-access-token", + "class": "negative", + "provider": "esignet", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://docs.esignet.io/home/esignet-2.x/readme/standards.md", + "note": "eSignet 2.x documentation, no lab run. The access token follows RFC 9068 with sub, iss, aud, exp, iat, client_id and scope. The header typ is not stated. at+jwt is inferred from the RFC and is not documented." + }, + "header": { + "alg": "RS256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "iss": "https://esignet.example.test", + "aud": { + "bind": "audience" + }, + "sub": "00000000-0000-4000-8000-000000000001", + "client_id": "journey-app", + "scope": "journey.read", + "iat": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 3600 + } + }, + "omits": [ + "azp", + "registry_actor_kind" + ], + "notes": "The issuer is a literal. A product trusts one configured issuer and never an eSignet issuer." +} diff --git a/products/platform/conformance/tokens/fixtures/esignet-id-token.json b/products/platform/conformance/tokens/fixtures/esignet-id-token.json new file mode 100644 index 0000000000..46f1c2ac3b --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/esignet-id-token.json @@ -0,0 +1,44 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "esignet-id-token", + "class": "negative", + "provider": "esignet", + "kind": "user-id", + "tokenUse": "id", + "subjectKind": "user", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://docs.esignet.io/home/esignet-2.x/readme/standards.md", + "note": "eSignet 2.x documentation, no lab run. The ID token has iss, sub, aud (the relying party's client ID), exp, iat, auth_time, nonce, acr and at_hash. The header typ is not stated, so it is omitted." + }, + "header": { + "alg": "RS256", + "kid": { + "generated": true + } + }, + "claims": { + "iss": "https://esignet.example.test", + "sub": "00000000-0000-4000-8000-000000000001", + "aud": "journey-app", + "exp": { + "offsetSeconds": 3600 + }, + "iat": { + "offsetSeconds": 0 + }, + "auth_time": { + "offsetSeconds": 0 + }, + "nonce": "synthetic-nonce", + "acr": "synthetic-acr", + "at_hash": "synthetic-at-hash" + }, + "omits": [ + "scope", + "client_id", + "azp" + ], + "notes": "A relying party holds this token after sign-in, so it is the one most likely to be forwarded by mistake." +} diff --git a/products/platform/conformance/tokens/fixtures/identity-only.json b/products/platform/conformance/tokens/fixtures/identity-only.json new file mode 100644 index 0000000000..0759682c9a --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/identity-only.json @@ -0,0 +1,45 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "identity-only", + "class": "positive", + "provider": "synthetic", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "constructed", + "reason": "A token that proves who the caller is and nothing else, built to isolate the lack of a scope and of a client claim from the other differences of a provider's token." + }, + "header": { + "alg": "RS256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "iss": { + "bind": "issuer" + }, + "aud": { + "bind": "audience" + }, + "sub": "00000000-0000-4000-8000-000000000001", + "iat": { + "offsetSeconds": 0 + }, + "nbf": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 300 + } + }, + "omits": [ + "scope", + "scp", + "client_id", + "azp", + "registry_actor_kind" + ] +} diff --git a/products/platform/conformance/tokens/fixtures/keycloak-client-credentials-stock.json b/products/platform/conformance/tokens/fixtures/keycloak-client-credentials-stock.json new file mode 100644 index 0000000000..1d0667fd6c --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/keycloak-client-credentials-stock.json @@ -0,0 +1,58 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "keycloak-client-credentials-stock", + "class": "positive", + "provider": "keycloak", + "kind": "client-access", + "tokenUse": "access", + "subjectKind": "service", + "source": { + "basis": "observed", + "observedFrom": "capture", + "observedOn": "2026-11-27", + "version": "26.8.2", + "image": "quay.io/keycloak/keycloak:26.8.2@sha256:7e66a96e4739239070aeaf72e4c5decf0f7f682cfc725b9f7ea2b336eaba38b3", + "captureFile": "keycloak-client-access.json" + }, + "header": { + "alg": "RS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "exp": { + "offsetSeconds": 300 + }, + "iat": { + "offsetSeconds": 0 + }, + "jti": "synthetic-jti-0004", + "iss": { + "bind": "issuer" + }, + "sub": "00000000-0000-4000-8000-000000000002", + "typ": "Bearer", + "azp": "journey-service", + "acr": "1", + "realm_access": { + "roles": [ + "journey-role" + ] + }, + "resource_access": {}, + "scope": "email profile", + "clientHost": "192.0.2.10", + "email_verified": false, + "preferred_username": "service-account-journey-service", + "clientAddress": "192.0.2.10", + "client_id": "journey-service", + "aud": "account" + }, + "omits": [ + "scp", + "registry_actor_kind" + ], + "notes": "The token as a stock realm issues it, with no realm configuration at all. The literal aud account names no API." +} diff --git a/products/platform/conformance/tokens/fixtures/keycloak-client-credentials.json b/products/platform/conformance/tokens/fixtures/keycloak-client-credentials.json new file mode 100644 index 0000000000..9a3d633318 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/keycloak-client-credentials.json @@ -0,0 +1,60 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "keycloak-client-credentials", + "class": "positive", + "provider": "keycloak", + "kind": "client-access", + "tokenUse": "access", + "subjectKind": "service", + "source": { + "basis": "observed", + "observedFrom": "capture", + "observedOn": "2026-11-27", + "version": "26.8.2", + "image": "quay.io/keycloak/keycloak:26.8.2@sha256:7e66a96e4739239070aeaf72e4c5decf0f7f682cfc725b9f7ea2b336eaba38b3", + "captureFile": "keycloak-client-access.json" + }, + "header": { + "alg": "RS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "exp": { + "offsetSeconds": 300 + }, + "iat": { + "offsetSeconds": 0 + }, + "jti": "synthetic-jti-0004", + "iss": { + "bind": "issuer" + }, + "sub": "00000000-0000-4000-8000-000000000002", + "typ": "Bearer", + "azp": "journey-service", + "acr": "1", + "realm_access": { + "roles": [ + "journey-role" + ] + }, + "resource_access": {}, + "scope": "email profile", + "clientHost": "192.0.2.10", + "email_verified": false, + "preferred_username": "service-account-journey-service", + "clientAddress": "192.0.2.10", + "client_id": "journey-service", + "aud": { + "bind": "audience" + } + }, + "omits": [ + "scp", + "registry_actor_kind" + ], + "notes": "The capture's aud was the stock value account. Here aud is bound, which models a realm that names the API as the audience. The lifetime is a test choice, the capture did not record one." +} diff --git a/products/platform/conformance/tokens/fixtures/keycloak-id-token.json b/products/platform/conformance/tokens/fixtures/keycloak-id-token.json new file mode 100644 index 0000000000..90a1754b53 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/keycloak-id-token.json @@ -0,0 +1,55 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "keycloak-id-token", + "class": "negative", + "provider": "keycloak", + "kind": "user-id", + "tokenUse": "id", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "capture", + "observedOn": "2026-11-27", + "version": "26.8.2", + "image": "quay.io/keycloak/keycloak:26.8.2@sha256:7e66a96e4739239070aeaf72e4c5decf0f7f682cfc725b9f7ea2b336eaba38b3", + "captureFile": "keycloak-user-id.json" + }, + "header": { + "alg": "RS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "exp": { + "offsetSeconds": 300 + }, + "iat": { + "offsetSeconds": 0 + }, + "jti": "synthetic-jti-0022", + "iss": { + "bind": "issuer" + }, + "aud": "journey-app", + "sub": "00000000-0000-4000-8000-000000000001", + "typ": "ID", + "azp": "journey-app", + "sid": "synthetic-sid", + "at_hash": "synthetic-at-hash", + "acr": "1", + "email_verified": true, + "name": "Journey User", + "preferred_username": "journey-user", + "given_name": "Journey", + "family_name": "User", + "email": "journey-user@example.test" + }, + "omits": [ + "scope", + "realm_access", + "resource_access" + ], + "notes": "The header equals an access token's header. The payload typ ID and the client audience tell it apart." +} diff --git a/products/platform/conformance/tokens/fixtures/keycloak-refresh-token.json b/products/platform/conformance/tokens/fixtures/keycloak-refresh-token.json new file mode 100644 index 0000000000..c0a2a88976 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/keycloak-refresh-token.json @@ -0,0 +1,47 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "keycloak-refresh-token", + "class": "negative", + "provider": "keycloak", + "kind": "user-refresh", + "tokenUse": "refresh", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "capture", + "observedOn": "2026-11-27", + "version": "26.8.2", + "image": "quay.io/keycloak/keycloak:26.8.2@sha256:7e66a96e4739239070aeaf72e4c5decf0f7f682cfc725b9f7ea2b336eaba38b3", + "captureFile": "keycloak-user-refresh.json" + }, + "header": { + "alg": "HS512", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "exp": { + "offsetSeconds": 1800 + }, + "iat": { + "offsetSeconds": 0 + }, + "jti": "synthetic-jti-0024", + "iss": { + "bind": "issuer" + }, + "aud": { + "bind": "issuer" + }, + "sub": "00000000-0000-4000-8000-000000000001", + "typ": "Refresh", + "azp": "journey-app", + "sid": "synthetic-sid", + "scope": "openid acr web-origins roles email profile basic", + "aud_x": "synthetic-aud-x", + "prov": "synthetic-prov" + }, + "notes": "Signed with a symmetric algorithm, so a key set cannot verify it. aud is the issuer URL, written here as the bound issuer." +} diff --git a/products/platform/conformance/tokens/fixtures/keycloak-user-access.json b/products/platform/conformance/tokens/fixtures/keycloak-user-access.json new file mode 100644 index 0000000000..6dd31f354c --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/keycloak-user-access.json @@ -0,0 +1,63 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "keycloak-user-access", + "class": "positive", + "provider": "keycloak", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "capture", + "observedOn": "2026-11-27", + "version": "26.8.2", + "image": "quay.io/keycloak/keycloak:26.8.2@sha256:7e66a96e4739239070aeaf72e4c5decf0f7f682cfc725b9f7ea2b336eaba38b3", + "captureFile": "keycloak-user-access.json" + }, + "header": { + "alg": "RS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "exp": { + "offsetSeconds": 300 + }, + "iat": { + "offsetSeconds": 0 + }, + "jti": "synthetic-jti-0003", + "iss": { + "bind": "issuer" + }, + "aud": { + "bind": "audience" + }, + "sub": "00000000-0000-4000-8000-000000000001", + "typ": "Bearer", + "azp": "journey-app", + "sid": "synthetic-sid", + "acr": "1", + "realm_access": { + "roles": [ + "journey-role" + ] + }, + "resource_access": {}, + "scope": "openid email profile", + "email_verified": true, + "name": "Journey User", + "preferred_username": "journey-user", + "given_name": "Journey", + "family_name": "User", + "email": "journey-user@example.test" + }, + "omits": [ + "client_id", + "scp", + "registry_actor_kind" + ], + "notes": "The capture's aud was the stock value account. Here aud is bound, which models a realm that names the API as the audience. The lifetime is the stock access token lifetime of 300 seconds, a test choice, the capture did not record one." +} diff --git a/products/platform/conformance/tokens/fixtures/rstack-dev-run-user.json b/products/platform/conformance/tokens/fixtures/rstack-dev-run-user.json new file mode 100644 index 0000000000..fded73c42c --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/rstack-dev-run-user.json @@ -0,0 +1,46 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "rstack-dev-run-user", + "class": "positive", + "provider": "rstack-dev", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "code", + "path": "crates/registry-rstack-dev/src/issuer.rs", + "lines": "232-244", + "observedOn": "2026-11-27" + }, + "header": { + "alg": "ES256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "iss": { + "bind": "issuer" + }, + "aud": { + "bind": "audience" + }, + "sub": "00000000-0000-4000-8000-000000000001", + "client_id": "journey-service", + "scope": "records:get", + "iat": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 300 + }, + "jti": "synthetic-jti-0011" + }, + "omits": [ + "azp", + "registry_actor_kind" + ], + "notes": "The shape the development runner signs for a product it starts, read from the signing code. Its lifetime constant is 300 seconds. No capture exists because the runner was read, not run." +} diff --git a/products/platform/conformance/tokens/fixtures/supabase-api-key-anon.json b/products/platform/conformance/tokens/fixtures/supabase-api-key-anon.json new file mode 100644 index 0000000000..2bdf6fb3d9 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/supabase-api-key-anon.json @@ -0,0 +1,32 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "supabase-api-key-anon", + "class": "negative", + "provider": "supabase-auth", + "kind": "api-key", + "tokenUse": "api-key", + "subjectKind": "unspecified", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://supabase.com/docs/guides/api/api-keys", + "note": "The page lists the legacy anon and service_role keys as long-lived JWTs and does not document their claims. The role claim is named on the JWT fields page. The claim set here is the minimum. Replace with an observed shape when one exists." + }, + "header": { + "alg": "HS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "role": "anon", + "iat": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 315360000 + } + }, + "notes": "The expiry models a long-lived key, a test choice." +} diff --git a/products/platform/conformance/tokens/fixtures/supabase-api-key-opaque.json b/products/platform/conformance/tokens/fixtures/supabase-api-key-opaque.json new file mode 100644 index 0000000000..3c86ab043b --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/supabase-api-key-opaque.json @@ -0,0 +1,16 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "supabase-api-key-opaque", + "class": "negative", + "provider": "supabase-auth", + "kind": "api-key", + "tokenUse": "api-key", + "subjectKind": "unspecified", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://supabase.com/docs/guides/api/api-keys", + "note": "Publishable and secret keys are short strings, not JWTs. The value is synthetic and not a key." + }, + "opaque": "sb_publishable_synthetic-test-value-not-a-key" +} diff --git a/products/platform/conformance/tokens/fixtures/supabase-api-key-service-role.json b/products/platform/conformance/tokens/fixtures/supabase-api-key-service-role.json new file mode 100644 index 0000000000..7c5a14d31f --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/supabase-api-key-service-role.json @@ -0,0 +1,32 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "supabase-api-key-service-role", + "class": "negative", + "provider": "supabase-auth", + "kind": "api-key", + "tokenUse": "api-key", + "subjectKind": "unspecified", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://supabase.com/docs/guides/api/api-keys", + "note": "See supabase-api-key-anon." + }, + "header": { + "alg": "HS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "role": "service_role", + "iat": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 315360000 + } + }, + "notes": "The expiry models a long-lived key, a test choice." +} diff --git a/products/platform/conformance/tokens/fixtures/supabase-id-token.json b/products/platform/conformance/tokens/fixtures/supabase-id-token.json new file mode 100644 index 0000000000..037c5832d3 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/supabase-id-token.json @@ -0,0 +1,41 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "supabase-id-token", + "class": "negative", + "provider": "supabase-auth", + "kind": "user-id", + "tokenUse": "id", + "subjectKind": "user", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://supabase.com/docs/guides/auth/oauth-server/getting-started", + "note": "The page says an ID token is issued when openid is requested and that asymmetric signing is required. It lists no ID token claims. The claim set here is the OpenID Connect Core minimum. Replace with an observed shape when one exists." + }, + "header": { + "alg": "ES256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "iss": { + "bind": "issuer" + }, + "aud": "journey-app", + "sub": "00000000-0000-4000-8000-000000000001", + "nonce": "synthetic-nonce", + "iat": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 3600 + } + }, + "omits": [ + "scope", + "client_id", + "azp" + ] +} diff --git a/products/platform/conformance/tokens/fixtures/supabase-oauth-server-user-access.json b/products/platform/conformance/tokens/fixtures/supabase-oauth-server-user-access.json new file mode 100644 index 0000000000..12ef1d2411 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/supabase-oauth-server-user-access.json @@ -0,0 +1,54 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "supabase-oauth-server-user-access", + "class": "positive", + "provider": "supabase-auth", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://supabase.com/docs/guides/auth/oauth-server/token-security", + "note": "The OAuth server token security page lists these claims. It shows no scope claim and does not describe the header. Replace with an observed shape when one exists." + }, + "header": { + "alg": "ES256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "iss": { + "bind": "issuer" + }, + "aud": "authenticated", + "sub": "00000000-0000-4000-8000-000000000001", + "role": "authenticated", + "user_id": "00000000-0000-4000-8000-000000000001", + "email": "journey-user@example.test", + "aal": "aal1", + "amr": [ + { + "method": "password", + "timestamp": 1700000000 + } + ], + "session_id": "synthetic-session", + "client_id": "journey-app", + "iat": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 3600 + } + }, + "omits": [ + "scope", + "scp", + "azp", + "registry_actor_kind" + ], + "notes": "Stands in for a Supabase client credentials token. The documentation describes no client credentials grant for Supabase Auth, only the authorization code and refresh flows of its OAuth server." +} diff --git a/products/platform/conformance/tokens/fixtures/supabase-user-access.json b/products/platform/conformance/tokens/fixtures/supabase-user-access.json new file mode 100644 index 0000000000..d0f9d216e1 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/supabase-user-access.json @@ -0,0 +1,55 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "supabase-user-access", + "class": "positive", + "provider": "supabase-auth", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "documentation", + "consultedOn": "2026-11-27", + "url": "https://supabase.com/docs/guides/auth/jwt-fields", + "note": "Header and claim names from the JWT fields page. The signing keys page lists ES256 as an asymmetric option, which is the one a verifier can check from a key set. Replace with an observed shape when one exists." + }, + "header": { + "alg": "ES256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "iss": { + "bind": "issuer" + }, + "aud": "authenticated", + "sub": "00000000-0000-4000-8000-000000000001", + "role": "authenticated", + "session_id": "synthetic-session", + "aal": "aal1", + "amr": [ + { + "method": "password", + "timestamp": 1700000000 + } + ], + "is_anonymous": false, + "email": "journey-user@example.test", + "phone": "", + "iat": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 3600 + } + }, + "omits": [ + "scope", + "scp", + "client_id", + "azp", + "registry_actor_kind" + ], + "notes": "The documentation defines no scope claim and no client claim for a user access token." +} diff --git a/products/platform/conformance/tokens/fixtures/thunderid-client-credentials.json b/products/platform/conformance/tokens/fixtures/thunderid-client-credentials.json new file mode 100644 index 0000000000..694323ed19 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-client-credentials.json @@ -0,0 +1,51 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-client-credentials", + "class": "positive", + "provider": "thunderid", + "kind": "client-access", + "tokenUse": "access", + "subjectKind": "service", + "source": { + "basis": "observed", + "observedFrom": "capture", + "observedOn": "2026-11-27", + "version": "1.0.1", + "image": "ghcr.io/thunder-id/thunderid:1.0.1@sha256:d3c0613ff447a551fd440768a15bdfb6668948e80809cbb50f82d6752f22ab3e", + "captureFile": "thunderid-client-access.json" + }, + "header": { + "alg": "RS256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "aud": { + "bind": "audience" + }, + "client_id": "journey-service", + "exp": { + "offsetSeconds": 3600 + }, + "grant_type": "client_credentials", + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0002", + "nbf": { + "offsetSeconds": 0 + }, + "registry_actor_kind": "service", + "scope": "records:get", + "sub": "00000000-0000-4000-8000-000000000002" + }, + "omits": [ + "azp" + ], + "notes": "The capture recorded claim names and value types only. String values are synthetic. The lifetime is a test choice, the capture did not record one." +} diff --git a/products/platform/conformance/tokens/fixtures/thunderid-id-token.json b/products/platform/conformance/tokens/fixtures/thunderid-id-token.json new file mode 100644 index 0000000000..de7f635201 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-id-token.json @@ -0,0 +1,51 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-id-token", + "class": "negative", + "provider": "thunderid", + "kind": "user-id", + "tokenUse": "id", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "capture", + "observedOn": "2026-11-27", + "version": "1.0.1", + "image": "ghcr.io/thunder-id/thunderid:1.0.1@sha256:d3c0613ff447a551fd440768a15bdfb6668948e80809cbb50f82d6752f22ab3e", + "captureFile": "thunderid-user-id.json" + }, + "header": { + "alg": "RS256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "aud": "journey-app", + "auth_time": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 3600 + }, + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0021", + "nbf": { + "offsetSeconds": 0 + }, + "nonce": "synthetic-nonce", + "sub": "00000000-0000-4000-8000-000000000001" + }, + "omits": [ + "scope", + "client_id", + "azp" + ], + "notes": "aud is the client, as in the capture. The lifetime is a test choice." +} diff --git a/products/platform/conformance/tokens/fixtures/thunderid-user-access.json b/products/platform/conformance/tokens/fixtures/thunderid-user-access.json new file mode 100644 index 0000000000..0af5df2345 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-user-access.json @@ -0,0 +1,53 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-user-access", + "class": "positive", + "provider": "thunderid", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "capture", + "observedOn": "2026-11-27", + "version": "1.0.1", + "image": "ghcr.io/thunder-id/thunderid:1.0.1@sha256:d3c0613ff447a551fd440768a15bdfb6668948e80809cbb50f82d6752f22ab3e", + "captureFile": "thunderid-user-access.json" + }, + "header": { + "alg": "RS256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "aci": "synthetic-aci", + "aud": { + "bind": "audience" + }, + "client_id": "journey-app", + "exp": { + "offsetSeconds": 3600 + }, + "grant_type": "authorization_code", + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0001", + "nbf": { + "offsetSeconds": 0 + }, + "registry_actor_kind": "human", + "scope": "openid records:get", + "sub": "00000000-0000-4000-8000-000000000001", + "tfid": "synthetic-tfid" + }, + "omits": [ + "azp" + ], + "notes": "The capture recorded claim names and value types only. String values are synthetic. The lifetime is a test choice, the capture did not record one." +} diff --git a/products/platform/conformance/tokens/token-fixture.schema.json b/products/platform/conformance/tokens/token-fixture.schema.json new file mode 100644 index 0000000000..20e7d65e01 --- /dev/null +++ b/products/platform/conformance/tokens/token-fixture.schema.json @@ -0,0 +1,143 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "registry.token-fixture/v1", + "title": "Token fixture", + "description": "One decoded token shape. The test loader signs it with a test key. A fixture holds no signature and no key.", + "type": "object", + "additionalProperties": false, + "required": ["schema", "id", "class", "provider", "kind", "tokenUse", "subjectKind", "source"], + "properties": { + "schema": { "const": "registry.token-fixture/v1" }, + "id": { "type": "string", "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" }, + "class": { + "enum": ["positive", "negative"], + "description": "A positive fixture is one a correctly configured product can admit for a plain read. A negative fixture is one every product must refuse." + }, + "provider": { "enum": ["keycloak", "thunderid", "entra", "supabase-auth", "esignet", "rstack-dev", "synthetic"] }, + "kind": { "enum": ["user-access", "client-access", "user-id", "user-refresh", "api-key"] }, + "tokenUse": { "enum": ["access", "id", "refresh", "api-key"] }, + "subjectKind": { "enum": ["user", "service", "unspecified"] }, + "source": { "$ref": "#/$defs/source" }, + "header": { "$ref": "#/$defs/header" }, + "claims": { "$ref": "#/$defs/claims" }, + "opaque": { + "type": "string", + "minLength": 1, + "description": "A credential that is not a JWT, as a synthetic string. A fixture holds either opaque or header with claims." + }, + "omits": { + "type": "array", + "items": { "type": "string", "minLength": 1 }, + "uniqueItems": true, + "description": "Claim names whose absence is the point. The loader asserts they are absent." + }, + "notes": { "type": "string", "minLength": 1 } + }, + "oneOf": [ + { "required": ["opaque"], "not": { "anyOf": [{ "required": ["header"] }, { "required": ["claims"] }, { "required": ["omits"] }] } }, + { "required": ["header", "claims"], "not": { "required": ["opaque"] } } + ], + "$defs": { + "source": { + "type": "object", + "required": ["basis"], + "properties": { + "basis": { "enum": ["observed", "documentation", "constructed"] } + }, + "oneOf": [ + { + "properties": { + "basis": { "const": "observed" }, + "observedFrom": { "const": "capture" }, + "observedOn": { "type": "string", "format": "date" }, + "version": { "type": "string", "minLength": 1 }, + "image": { "type": "string", "pattern": "^[^\\s@]+@sha256:[0-9a-f]{64}$" }, + "captureFile": { "type": "string", "pattern": "^[a-z0-9-]+\\.json$" } + }, + "required": ["basis", "observedFrom", "observedOn", "version", "image", "captureFile"], + "additionalProperties": false + }, + { + "properties": { + "basis": { "const": "observed" }, + "observedFrom": { "const": "code" }, + "observedOn": { "type": "string", "format": "date" }, + "path": { "type": "string", "minLength": 1 }, + "lines": { "type": "string", "pattern": "^[0-9]+-[0-9]+$" } + }, + "required": ["basis", "observedFrom", "observedOn", "path", "lines"], + "additionalProperties": false + }, + { + "properties": { + "basis": { "const": "documentation" }, + "consultedOn": { "type": "string", "format": "date" }, + "url": { "type": "string", "pattern": "^https://" }, + "note": { "type": "string", "minLength": 1 } + }, + "required": ["basis", "consultedOn", "url"], + "additionalProperties": false + }, + { + "properties": { + "basis": { "const": "constructed" }, + "reason": { "type": "string", "minLength": 1 } + }, + "required": ["basis", "reason"], + "additionalProperties": false + } + ] + }, + "header": { + "type": "object", + "required": ["alg", "kid"], + "additionalProperties": false, + "properties": { + "alg": { "enum": ["RS256", "ES256", "EdDSA", "HS256", "HS512"] }, + "typ": { "type": "string", "minLength": 1 }, + "kid": { "$ref": "#/$defs/generated" } + } + }, + "claims": { + "type": "object", + "required": ["exp"], + "minProperties": 1, + "additionalProperties": { + "if": { + "type": "object", + "anyOf": [{ "required": ["bind"] }, { "required": ["offsetSeconds"] }, { "required": ["generated"] }] + }, + "then": { "$ref": "#/$defs/directive" } + }, + "properties": { + "exp": { "$ref": "#/$defs/offset" }, + "iat": { "$ref": "#/$defs/offset" }, + "nbf": { "$ref": "#/$defs/offset" } + } + }, + "directive": { + "oneOf": [{ "$ref": "#/$defs/bind" }, { "$ref": "#/$defs/offset" }, { "$ref": "#/$defs/generated" }] + }, + "bind": { + "type": "object", + "required": ["bind"], + "additionalProperties": false, + "properties": { "bind": { "enum": ["issuer", "audience"] } }, + "description": "Takes the issuer or the audience of the product under test, so the fixture tests a token's shape and not a mismatch the test set up." + }, + "offset": { + "type": "object", + "required": ["offsetSeconds"], + "additionalProperties": false, + "properties": { "offsetSeconds": { "type": "integer", "minimum": 0 } }, + "description": "Seconds after the moment of signing." + }, + "generated": { + "type": "object", + "required": ["generated"], + "additionalProperties": false, + "properties": { "generated": { "const": true } }, + "description": "A value the loader generates at signing time." + } + } +} From 8d9f3434d11b98886f5256961fca209a191516b3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 01:59:09 +0100 Subject: [PATCH 003/136] feat(platform): check every static key set with one public-key rule Eleven products load an operator-pinned key set, and BReg kept its own member list. public_jwks_document is the one rule: private and symmetric members are refused on every key type, repeated member names are refused, and members it does not name are ignored as RFC 7517 requires, so a stock provider key set with x5c or ext loads. Signed-off-by: Jeremi Joslin --- crates/registry-platform-crypto/src/lib.rs | 29 ++- .../registry-platform-oidc/src/diagnostics.rs | 1 + crates/registry-platform-oidc/src/lib.rs | 63 +++-- .../registry-platform-oidc/src/static_jwks.rs | 219 ++++++++++++++++++ products/platform/CHANGELOG.md | 9 + 5 files changed, 295 insertions(+), 26 deletions(-) create mode 100644 crates/registry-platform-oidc/src/static_jwks.rs diff --git a/crates/registry-platform-crypto/src/lib.rs b/crates/registry-platform-crypto/src/lib.rs index 1e3bfbea2a..10336f60e0 100644 --- a/crates/registry-platform-crypto/src/lib.rs +++ b/crates/registry-platform-crypto/src/lib.rs @@ -116,6 +116,10 @@ pub fn domain_separated_sha256(domain: &[u8], canonical_payload: &[u8]) -> [u8; /// Maximum raw JSON bytes accepted by the JWK parsing boundaries. pub const MAX_JWK_JSON_BYTES: usize = 64 * 1024; + +/// JWK members that carry private or symmetric key material. +pub const PRIVATE_JWK_MEMBERS: [&str; 8] = ["k", "d", "p", "q", "dp", "dq", "qi", "oth"]; + const MAX_DID_JWK_IDENTIFIER_BYTES: usize = MAX_JWK_JSON_BYTES.div_ceil(3) * 4; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -505,7 +509,7 @@ impl<'de> Visitor<'de> for PublicJwkVisitor { "y" => deserialize_optional_jwk_field(&mut map, &mut y, "y")?, "n" => deserialize_optional_jwk_field(&mut map, &mut n, "n")?, "e" => deserialize_optional_jwk_field(&mut map, &mut e, "e")?, - "k" | "d" | "p" | "q" | "dp" | "dq" | "qi" | "oth" => { + name if PRIVATE_JWK_MEMBERS.contains(&name) => { let _: IgnoredAny = map.next_value()?; return Err(de::Error::custom("public JWK contains private material")); } @@ -2129,8 +2133,7 @@ fn algorithm_from_fields( } fn reject_private_members(value: &Value) -> Result<(), JwkError> { - const PRIVATE_MEMBERS: [&str; 8] = ["k", "d", "p", "q", "dp", "dq", "qi", "oth"]; - if PRIVATE_MEMBERS + if PRIVATE_JWK_MEMBERS .iter() .any(|member| value.get(member).is_some()) { @@ -4020,6 +4023,26 @@ mod tests { assert!(matches!(err, JwkError::Invalid(_))); } + #[test] + fn the_private_member_list_is_complete_and_every_member_is_refused_by_parse() { + assert_eq!( + PRIVATE_JWK_MEMBERS, + ["k", "d", "p", "q", "dp", "dq", "qi", "oth"] + ); + for member in PRIVATE_JWK_MEMBERS { + let mut value: Value = serde_json::from_str(&rsa_public_json()).expect("public json"); + value + .as_object_mut() + .expect("object") + .insert(member.to_string(), json!("not-allowed-on-public")); + let json = serde_json::to_string(&value).expect("json serializes"); + assert!( + matches!(PublicJwk::parse(&json), Err(JwkError::Invalid(_))), + "{member} must be refused" + ); + } + } + #[test] fn rsa_private_public_drops_private_members() { let public = PrivateJwk::parse(RSA_JWK) diff --git a/crates/registry-platform-oidc/src/diagnostics.rs b/crates/registry-platform-oidc/src/diagnostics.rs index 98af2a060b..3641df2af1 100644 --- a/crates/registry-platform-oidc/src/diagnostics.rs +++ b/crates/registry-platform-oidc/src/diagnostics.rs @@ -64,6 +64,7 @@ impl OidcError { | Self::Parse | Self::InvalidJwk | Self::EmptyKeySet + | Self::StaticKeySet(_) | Self::MissingIssuer | Self::ConflictingEndpointConfiguration | Self::InsecureHttpRequiresOptIn diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index 820476fa45..2dded540d9 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -8,7 +8,9 @@ mod access_token_algorithm; mod authorization_claims; mod diagnostics; +mod static_jwks; pub use diagnostics::{AuthenticationDiagnostics, AuthenticationStage}; +pub use static_jwks::{public_jwks_document, StaticJwksError}; #[doc(hidden)] pub use tracing as __tracing; pub mod task_grant; @@ -470,26 +472,21 @@ impl fmt::Debug for JwksFetcher { /// Parse an operator-supplied static JWKS document for /// [`JwksFetcher::new_static`]: a non-empty key set of RSA or elliptic-curve -/// keys, each with a non-empty `kid` no other key in the set repeats. A -/// symmetric key or an unnamed key is refused here, at startup, rather than -/// when a token first selects it. +/// public keys, each with a non-empty `kid` no other key in the set repeats. +/// A symmetric key, a private-key member or an unnamed key is refused here, +/// at startup, rather than when a token first selects it. The rule on members +/// is [`public_jwks_document`]. An OKP key passes that rule and is refused +/// here with [`OidcError::InvalidJwk`]. pub fn parse_static_jwks(bytes: &[u8]) -> Result { - let jwks: JwkSet = serde_json::from_slice(bytes).map_err(|_| OidcError::Parse)?; - if jwks.keys.is_empty() { - return Err(OidcError::EmptyKeySet); - } - let mut kids = BTreeSet::new(); - let all_named_asymmetric = jwks.keys.iter().all(|key| { + let document = public_jwks_document(bytes)?; + let jwks: JwkSet = serde_json::from_value(document).map_err(|_| OidcError::Parse)?; + let all_asymmetric = jwks.keys.iter().all(|key| { matches!( key.algorithm, AlgorithmParameters::RSA(_) | AlgorithmParameters::EllipticCurve(_) - ) && key - .common - .key_id - .as_deref() - .is_some_and(|kid| !kid.is_empty() && kids.insert(kid)) + ) }); - if all_named_asymmetric { + if all_asymmetric { Ok(jwks) } else { Err(OidcError::InvalidJwk) @@ -1798,6 +1795,8 @@ pub enum OidcError { InvalidJwk, #[error("key set contains no usable keys")] EmptyKeySet, + #[error("static key set refused: {0}")] + StaticKeySet(#[from] StaticJwksError), #[error("token is expired")] TokenExpired, #[error("token is not yet valid")] @@ -4587,6 +4586,15 @@ mod tests { assert_eq!(document.jwks_uri, "http://127.0.0.1/jwks"); } + #[test] + fn a_static_key_set_with_unknown_public_members_loads() { + let keys = parse_static_jwks( + br#"{"issuer":"x","keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","ext":true,"x5c":["AA"],"x5t":"a","x5t#S256":"b","x5u":"https://x.example/c","use":"enc","future":1}]}"#, + ) + .expect("unknown public members are ignored"); + assert_eq!(keys.keys.len(), 1); + } + #[test] fn a_static_key_set_requires_unique_named_asymmetric_keys() { let keys = parse_static_jwks( @@ -4596,34 +4604,43 @@ mod tests { assert_eq!(keys.keys.len(), 2); for (reason, invalid, expected) in [ - ("no keys member", br#"{}"#.as_slice(), "parse"), - ("not JSON", b"not-json", "parse"), - ("an empty key set", br#"{"keys":[]}"#, "empty"), + ("no keys member", br#"{}"#.as_slice(), "static"), + ("not JSON", b"not-json", "static"), + ("an empty key set", br#"{"keys":[]}"#, "static"), ( "a symmetric key", br#"{"keys":[{"kty":"oct","kid":"one","k":"AA"}]}"#, - "jwk", + "static", ), ( "a key without kid", br#"{"keys":[{"kty":"RSA","n":"AQAB","e":"AQAB"}]}"#, - "jwk", + "static", ), ( "an empty kid", br#"{"keys":[{"kty":"RSA","kid":"","n":"AQAB","e":"AQAB"}]}"#, - "jwk", + "static", ), ( "a repeated kid", br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + "static", + ), + ( + "a private member", + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","d":"AA"}]}"#, + "static", + ), + ( + "an OKP key", + br#"{"keys":[{"kty":"OKP","kid":"one","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]}"#, "jwk", ), ] { let error = parse_static_jwks(invalid).expect_err(reason); let kind = match error { - OidcError::Parse => "parse", - OidcError::EmptyKeySet => "empty", + OidcError::StaticKeySet(_) => "static", OidcError::InvalidJwk => "jwk", other => panic!("{reason}: unexpected {other:?}"), }; diff --git a/crates/registry-platform-oidc/src/static_jwks.rs b/crates/registry-platform-oidc/src/static_jwks.rs new file mode 100644 index 0000000000..d05d8f8b2a --- /dev/null +++ b/crates/registry-platform-oidc/src/static_jwks.rs @@ -0,0 +1,219 @@ +//! Public-key rule for operator-pinned JSON Web Key Sets. +//! +//! One rule for every product that loads a static key set. Members this +//! module does not name are ignored, as RFC 7517 sections 4 and 5 require. +//! A refusal names the position of the key and the rule it broke, never a +//! `kid` or a member value. + +use std::collections::BTreeSet; + +use registry_platform_crypto::{parse_json_strict, PRIVATE_JWK_MEMBERS}; +use serde_json::Value; + +/// Why a static key set was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum StaticJwksError { + #[error("the document is not JSON, or repeats a member name")] + NotJson, + #[error("the document is not a JSON Web Key Set: it needs a top-level \"keys\" array")] + NotAKeySet, + #[error("the key set holds no keys")] + Empty, + #[error("key {key} is not a JSON object")] + KeyNotAnObject { key: usize }, + #[error( + "key {key} is a symmetric key (\"kty\": \"oct\"); a static key set holds public keys only" + )] + SymmetricKey { key: usize }, + #[error("key {key} has no \"kty\", or a key type that is not RSA, EC or OKP")] + UnsupportedKeyType { key: usize }, + #[error("key {key} carries the private-key member \"{member}\"; a static key set holds public keys only, so export the public key and replace this document")] + PrivateKeyMember { key: usize, member: &'static str }, + #[error("key {key} has no \"kid\"; give every key a non-empty \"kid\"")] + MissingKeyId { key: usize }, + #[error("key {key} repeats the \"kid\" of an earlier key; give every key its own \"kid\"")] + RepeatedKeyId { key: usize }, +} + +/// Check that `bytes` is a JSON Web Key Set that holds public keys only. +/// Returns the parsed document. Members this function does not name are not +/// inspected. The caller bounds the size of `bytes`. +pub fn public_jwks_document(bytes: &[u8]) -> Result { + let document = parse_json_strict(bytes).map_err(|_| StaticJwksError::NotJson)?; + let keys = document + .get("keys") + .and_then(Value::as_array) + .ok_or(StaticJwksError::NotAKeySet)?; + if keys.is_empty() { + return Err(StaticJwksError::Empty); + } + let mut key_ids = BTreeSet::new(); + for (key, member) in keys.iter().enumerate() { + let member = member + .as_object() + .ok_or(StaticJwksError::KeyNotAnObject { key })?; + match member.get("kty").and_then(Value::as_str) { + Some("oct") => return Err(StaticJwksError::SymmetricKey { key }), + Some("RSA" | "EC" | "OKP") => {} + _ => return Err(StaticJwksError::UnsupportedKeyType { key }), + } + if let Some(private) = PRIVATE_JWK_MEMBERS + .iter() + .find(|name| member.contains_key(**name)) + { + return Err(StaticJwksError::PrivateKeyMember { + key, + member: private, + }); + } + let kid = member + .get("kid") + .and_then(Value::as_str) + .filter(|kid| !kid.is_empty()) + .ok_or(StaticJwksError::MissingKeyId { key })?; + if !key_ids.insert(kid) { + return Err(StaticJwksError::RepeatedKeyId { key }); + } + } + Ok(document) +} + +#[cfg(test)] +mod tests { + use super::*; + use registry_platform_crypto::PRIVATE_JWK_MEMBERS; + use serde_json::json; + + const RSA: &str = r#"{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}"#; + + fn set(keys: &str) -> Vec { + format!(r#"{{"keys":[{keys}]}}"#).into_bytes() + } + + fn refusal(bytes: &[u8]) -> StaticJwksError { + public_jwks_document(bytes).expect_err("document must be refused") + } + + #[test] + fn unknown_members_on_keys_and_on_the_set_are_ignored() { + let key = r#"{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","ext":true,"x5c":["AA"],"x5t":"a","x5t#S256":"b","x5u":"https://x.example/c","use":"sig","key_ops":["verify"],"future":{"a":1}}"#; + let bytes = format!(r#"{{"issuer":"x","keys":[{key}]}}"#); + let document = public_jwks_document(bytes.as_bytes()).expect("loads"); + assert_eq!(document["keys"].as_array().expect("keys").len(), 1); + } + + #[test] + fn a_keycloak_shaped_set_loads() { + let sig = r#"{"kid":"sig","kty":"RSA","alg":"RS256","use":"sig","n":"AQAB","e":"AQAB","x5c":["MIIC"],"x5t":"aa","x5t#S256":"bb"}"#; + let enc = r#"{"kid":"enc","kty":"RSA","alg":"RSA-OAEP","use":"enc","n":"AQAB","e":"AQAB","x5c":["MIIC"],"x5t":"aa","x5t#S256":"bb"}"#; + public_jwks_document(&set(&format!("{sig},{enc}"))).expect("loads"); + } + + #[test] + fn every_private_member_is_refused_on_every_key_type() { + let shapes = [ + r#""kty":"RSA","n":"AQAB","e":"AQAB""#, + r#""kty":"EC","crv":"P-256","x":"AQAB","y":"AQAB""#, + r#""kty":"OKP","crv":"Ed25519","x":"AQAB""#, + ]; + for shape in shapes { + for member in PRIVATE_JWK_MEMBERS { + let bytes = set(&format!(r#"{{{shape},"kid":"one","{member}":"canary"}}"#)); + let error = refusal(&bytes); + assert_eq!( + error, + StaticJwksError::PrivateKeyMember { key: 0, member }, + "{shape} {member}" + ); + } + } + } + + #[test] + fn the_first_private_member_in_list_order_is_reported() { + let bytes = set(r#"{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","dq":"x","d":"y"}"#); + assert_eq!( + refusal(&bytes), + StaticJwksError::PrivateKeyMember { + key: 0, + member: "d" + } + ); + } + + #[test] + fn symmetric_and_unsupported_key_types_are_refused() { + assert_eq!( + refusal(&set(r#"{"kty":"oct","kid":"one","k":"AA"}"#)), + StaticJwksError::SymmetricKey { key: 0 } + ); + for key in [ + r#"{"kty":"DSA","kid":"one"}"#, + r#"{"kid":"one"}"#, + r#"{"kty":5,"kid":"one"}"#, + ] { + assert_eq!( + refusal(&set(key)), + StaticJwksError::UnsupportedKeyType { key: 0 }, + "{key}" + ); + } + } + + #[test] + fn structural_refusals() { + assert_eq!(refusal(b"not-json"), StaticJwksError::NotJson); + assert_eq!( + refusal(br#"{"keys":[],"keys":[]}"#), + StaticJwksError::NotJson + ); + assert_eq!( + refusal(br#"{"keys":[{"kty":"RSA","kty":"RSA","kid":"one"}]}"#), + StaticJwksError::NotJson + ); + assert_eq!(refusal(b"{}"), StaticJwksError::NotAKeySet); + assert_eq!(refusal(b"[]"), StaticJwksError::NotAKeySet); + assert_eq!(refusal(br#"{"keys":{}}"#), StaticJwksError::NotAKeySet); + assert_eq!(refusal(br#"{"keys":[]}"#), StaticJwksError::Empty); + assert_eq!( + refusal(&set(&format!("{RSA},3"))), + StaticJwksError::KeyNotAnObject { key: 1 } + ); + } + + #[test] + fn key_id_rules() { + assert_eq!( + refusal(&set(r#"{"kty":"RSA","n":"AQAB","e":"AQAB"}"#)), + StaticJwksError::MissingKeyId { key: 0 } + ); + assert_eq!( + refusal(&set(r#"{"kty":"RSA","kid":"","n":"AQAB","e":"AQAB"}"#)), + StaticJwksError::MissingKeyId { key: 0 } + ); + assert_eq!( + refusal(&set(r#"{"kty":"RSA","kid":7,"n":"AQAB","e":"AQAB"}"#)), + StaticJwksError::MissingKeyId { key: 0 } + ); + assert_eq!( + refusal(&set(&format!("{RSA},{RSA}"))), + StaticJwksError::RepeatedKeyId { key: 1 } + ); + } + + #[test] + fn refusal_text_carries_no_key_material_or_kid() { + let canary = "canary-secret-value"; + let documents = [ + json!({"keys":[{"kty":"RSA","kid":canary,"n":"AQAB","e":"AQAB","d":canary}]}), + json!({"keys":[{"kty":"oct","kid":canary,"k":canary}]}), + json!({"keys":[{"kty":canary,"kid":canary}]}), + json!({"keys":[{"kty":"RSA","kid":canary},{"kty":"RSA","kid":canary}]}), + ]; + for document in documents { + let text = refusal(document.to_string().as_bytes()).to_string(); + assert!(!text.contains(canary), "{text}"); + } + } +} diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index c1ad0a4dd3..0ff7e11546 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- One rule for a static key set, in `registry-platform-oidc` + (`public_jwks_document`, behind `parse_static_jwks`). A key set that holds + a private or symmetric member (`d`, `k`, `p`, `q`, `dp`, `dq`, `qi`, + `oth`) is refused whatever the key type, and a repeated member name is + refused. Members the rule does not name (`ext`, `x5c`, `x5t`, `x5u` and + others) are ignored. A refusal is `OidcError::StaticKeySet` and names the + key position and the rule, never a `kid` or a value. The member list is + `registry_platform_crypto::PRIVATE_JWK_MEMBERS`. + ## 0.48.0 - 2026-11-23 - No user-visible product changes in this release. From 8e2806942c5e0cfd16715e42525f7a7b2f1c1f7d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:16:40 +0100 Subject: [PATCH 004/136] feat(platform): give loopback one definition and name the probe paths once feat(platform): give loopback one definition and an empty range list one meaning Loopback was spelled several ways across the shared HTTP crates, and an empty private range list admitted every private address under one profile. registry-platform-httpsec::loopback is now the one definition: numeric loopback literals, and the exact name localhost only when every address it resolves to is loopback. An empty list admits no private address, and the shared outbound builder pins localhost to loopback itself. feat(platform): name the probe paths and bodies once Services answer liveness and readiness probes with different paths and bodies. registry-platform-httputil::probe holds the one shape most of them already use, /health and /ready with a small JSON status body, so products and their clients take it from one place. feat(platform): use the one loopback definition in the shared crates and default the delivery window The issuer policy, the JWKS address check, hook destinations and the object store each kept their own loopback test. They now call registry-platform-httpsec::loopback. Signed hook receivers gain DEFAULT_DELIVERY_SKEW, 300 seconds either way, for callers that name no window of their own. fix(platform): treat a mapped loopback literal as loopback for a development fetch The issuer policy and the JWKS check accept http://[::ffff:127.0.0.1]/ through the one loopback definition, while the development fetch policy refused it, so a check passed and the fetch failed. The fetch now uses the same definition. Mapped forms of any other address stay refused. Signed-off-by: Jeremi Joslin --- Cargo.lock | 2 + crates/registry-platform-config/Cargo.toml | 1 + crates/registry-platform-config/src/blocks.rs | 10 +- .../src/blocks_tests.rs | 28 ++++ .../src/delivery/destination.rs | 42 +++++- .../registry-platform-hooks/src/receiver.rs | 33 +++++ crates/registry-platform-httpsec/src/lib.rs | 1 + .../registry-platform-httpsec/src/loopback.rs | 140 ++++++++++++++++++ .../registry-platform-httpsec/src/server.rs | 6 +- crates/registry-platform-httputil/Cargo.toml | 1 + .../src/client/outbound.rs | 46 ++++-- .../src/destination.rs | 46 +++--- crates/registry-platform-httputil/src/lib.rs | 107 +++++++++++-- .../registry-platform-httputil/src/probe.rs | 36 +++++ .../registry-platform-objectstore/src/s3.rs | 4 +- .../src/s3_tests.rs | 19 +++ .../src/verifier.rs | 6 +- .../src/verifier_tests.rs | 19 +++ crates/registry-platform-oidc/src/lib.rs | 39 ++++- 19 files changed, 517 insertions(+), 69 deletions(-) create mode 100644 crates/registry-platform-httpsec/src/loopback.rs create mode 100644 crates/registry-platform-httputil/src/probe.rs diff --git a/Cargo.lock b/Cargo.lock index 2ee2299196..449febe216 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7839,6 +7839,7 @@ name = "registry-platform-config" version = "0.49.0" dependencies = [ "registry-platform-canonical-json", + "registry-platform-httpsec", "registry-platform-yaml", "rustix 1.1.6", "schemars", @@ -7963,6 +7964,7 @@ dependencies = [ "registry-platform-authcommon", "registry-platform-canonical-json", "registry-platform-crypto", + "registry-platform-httpsec", "reqwest 0.12.28", "rustls-native-certs", "serde", diff --git a/crates/registry-platform-config/Cargo.toml b/crates/registry-platform-config/Cargo.toml index 3a1df14a0c..968c0fb52c 100644 --- a/crates/registry-platform-config/Cargo.toml +++ b/crates/registry-platform-config/Cargo.toml @@ -15,6 +15,7 @@ schema = ["dep:schemars", "registry-platform-yaml/schema"] [dependencies] registry-platform-canonical-json = { workspace = true } +registry-platform-httpsec.workspace = true registry-platform-yaml.workspace = true rustix.workspace = true schemars = { workspace = true, optional = true } diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 6b656da136..11139df63e 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -426,12 +426,10 @@ fn valid_jwks_uri(value: &Url, allow_loopback_http: bool, allow_insecure_http: b "http" => { allow_insecure_http || (allow_loopback_http - && match parsed.host() { - Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), - Some(url::Host::Ipv4(address)) => address.is_loopback(), - Some(url::Host::Ipv6(address)) => address.is_loopback(), - None => false, - }) + && parsed + .host_str() + .and_then(registry_platform_httpsec::loopback::loopback_host) + .is_some()) } _ => false, } diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 212de6a5fb..9f000454c8 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -174,6 +174,34 @@ fn jwks_source_has_three_types_and_defaults_to_discovery() { } } +#[test] +fn jwks_uri_loopback_follows_the_shared_definition() { + let check = |uri: &str| { + JwksSource::Uri { + uri: Url::new(uri).unwrap(), + } + .check("authentication.oidc.jwksSource", true) + }; + for uri in [ + "http://127.0.0.1:1/jwks", + "http://127.0.0.2:1/jwks", + "http://[::1]:1/jwks", + "http://[::ffff:127.0.0.1]:1/jwks", + "http://localhost:1/jwks", + "http://LOCALHOST:1/jwks", + ] { + check(uri).unwrap_or_else(|error| panic!("{uri}: {error:?}")); + } + for uri in [ + "http://localhost.:1/jwks", + "http://issuer.localhost:1/jwks", + "http://0.0.0.0:1/jwks", + "http://[::ffff:10.0.0.1]:1/jwks", + ] { + assert!(check(uri).is_err(), "{uri}"); + } +} + #[test] fn issuer_and_jwks_uri_are_checked_urls_when_read() { for text in [ diff --git a/crates/registry-platform-hooks/src/delivery/destination.rs b/crates/registry-platform-hooks/src/delivery/destination.rs index cb57025b27..b18f6b86b5 100644 --- a/crates/registry-platform-hooks/src/delivery/destination.rs +++ b/crates/registry-platform-hooks/src/delivery/destination.rs @@ -22,6 +22,7 @@ use registry_platform_httputil::destination::{ EventDestinationRequestTemplate, MAX_DESTINATION_REQUEST_HEADER_BYTES, MAX_DESTINATION_TARGET_BYTES, }; +use registry_platform_httputil::loopback::loopback_host; use url::Url; use super::seams::{ @@ -305,12 +306,7 @@ pub fn url_destination_address( } let profile = match parsed.scheme() { "https" => DestinationProfile::ProductionHttps, - "http" - if matches!( - parsed.host_str(), - Some("127.0.0.1") | Some("localhost") | Some("[::1]") - ) => - { + "http" if parsed.host_str().and_then(loopback_host).is_some() => { DestinationProfile::LoopbackDevelopmentHttp } _ => return Err(UrlDestinationError::InvalidBinding), @@ -475,4 +471,38 @@ mod tests { ); } } + + #[test] + fn url_address_follows_the_shared_loopback_definition() { + for admitted in [ + "http://127.0.0.1:9000/in", + "http://127.0.0.2:9000/in", + "http://[::1]:9000/in", + "http://[::ffff:127.0.0.1]:9000/in", + "http://localhost:9000/in", + "http://LOCALHOST:9000/in", + ] { + let address = url_destination_address(admitted).expect(admitted); + assert_eq!( + address.profile, + DestinationProfile::LoopbackDevelopmentHttp, + "{admitted}" + ); + } + for refused in [ + "http://localhost.:9000/in", + "http://hooks.localhost:9000/in", + "http://127.0.0.1.example:9000/in", + "http://0.0.0.0:9000/in", + "http://[::]:9000/in", + "http://10.0.0.1:9000/in", + "http://[::ffff:10.0.0.1]:9000/in", + ] { + assert_eq!( + url_destination_address(refused), + Err(UrlDestinationError::InvalidBinding), + "{refused}" + ); + } + } } diff --git a/crates/registry-platform-hooks/src/receiver.rs b/crates/registry-platform-hooks/src/receiver.rs index 37a7d02146..b67f861bdb 100644 --- a/crates/registry-platform-hooks/src/receiver.rs +++ b/crates/registry-platform-hooks/src/receiver.rs @@ -41,6 +41,10 @@ const HEADERS: [&str; 12] = [ "x-registry-signature", ]; +/// How far a signed delivery time may be from the receiver clock, in either +/// direction, when the receiver names no window of its own. +pub const DEFAULT_DELIVERY_SKEW: Duration = Duration::from_secs(300); + /// How the receiver bounds the signed delivery time. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DeliveryFreshness { @@ -53,6 +57,17 @@ pub enum DeliveryFreshness { CallerEnforced, } +impl DeliveryFreshness { + /// The default window around `now`. + #[must_use] + pub const fn default_at(now: SystemTime) -> Self { + Self::Within { + now, + skew: DEFAULT_DELIVERY_SKEW, + } + } +} + /// Exact request material of one received delivery. /// /// `headers` yields every received header as its name and raw value bytes, @@ -381,6 +396,24 @@ mod tests { ); } + #[test] + fn the_default_window_is_300_seconds_in_both_directions() { + assert_eq!(DEFAULT_DELIVERY_SKEW, Duration::from_secs(300)); + let headers = headers(); + let at = |now: SystemTime| verify(&headers, BODY, DeliveryFreshness::default_at(now)); + let delivered = delivery_instant(); + assert!(at(delivered + Duration::from_secs(300)).is_ok()); + assert_eq!( + at(delivered + Duration::from_secs(301)), + Err(ReceiverError::Stale) + ); + assert!(at(delivered - Duration::from_secs(300)).is_ok()); + assert_eq!( + at(delivered - Duration::from_secs(301)), + Err(ReceiverError::Stale) + ); + } + #[test] fn every_signed_header_is_required_and_bound() { for name in HEADERS { diff --git a/crates/registry-platform-httpsec/src/lib.rs b/crates/registry-platform-httpsec/src/lib.rs index ac050841db..4ce09c66f5 100644 --- a/crates/registry-platform-httpsec/src/lib.rs +++ b/crates/registry-platform-httpsec/src/lib.rs @@ -1,6 +1,7 @@ //! HTTP security primitives shared by Registry Stack servers and clients. mod client; +pub mod loopback; pub use client::{ response_trace_id, ProblemDocument, ProblemDocumentError, ResponseTraceError, TraceId, diff --git a/crates/registry-platform-httpsec/src/loopback.rs b/crates/registry-platform-httpsec/src/loopback.rs new file mode 100644 index 0000000000..9d5aaedf07 --- /dev/null +++ b/crates/registry-platform-httpsec/src/loopback.rs @@ -0,0 +1,140 @@ +//! The one definition of "loopback" for outbound and bind decisions. +//! +//! A host is loopback when it is an address literal in `127.0.0.0/8`, `::1`, or an +//! IPv4-mapped IPv6 form of an address in `127.0.0.0/8`, or when it is the exact +//! name `localhost` and the connection is made only to loopback addresses the +//! caller has checked. `*.localhost`, `localhost.` and every other name are never +//! loopback. + +use std::net::IpAddr; + +/// The one name that may stand for the loopback interface. +const LOCALHOST: &str = "localhost"; + +/// True for `127.0.0.0/8`, `::1`, and IPv4-mapped IPv6 forms of `127.0.0.0/8`. +#[must_use] +pub fn loopback_address(ip: IpAddr) -> bool { + ip.to_canonical().is_loopback() +} + +/// How a host text claims to be loopback. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LoopbackHost { + /// An address literal that is loopback. + Literal(IpAddr), + /// The exact name `localhost`. It is loopback only when + /// [`LoopbackHost::pinned_by`] holds for the addresses the connection uses. + LocalhostName, +} + +impl LoopbackHost { + /// `Literal` is always pinned. `LocalhostName` is pinned when `resolved` is not + /// empty and every address in it is a loopback address. + #[must_use] + pub fn pinned_by(self, resolved: &[IpAddr]) -> bool { + match self { + Self::Literal(_) => true, + Self::LocalhostName => { + !resolved.is_empty() && resolved.iter().all(|ip| loopback_address(*ip)) + } + } + } +} + +/// Classify a URL host. `[::1]` and `::1` are both accepted. Returns `None` for every +/// other host. +#[must_use] +pub fn loopback_host(host: &str) -> Option { + if host.eq_ignore_ascii_case(LOCALHOST) { + return Some(LoopbackHost::LocalhostName); + } + loopback_literal(host).map(LoopbackHost::Literal) +} + +/// The literal arm alone, for a site that cannot pin a name. +#[must_use] +pub fn loopback_literal(host: &str) -> Option { + let bare = host + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + .unwrap_or(host); + let ip: IpAddr = bare.parse().ok()?; + loopback_address(ip).then_some(ip) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn loopback_claims_are_exactly_the_literals_and_the_name() { + for host in [ + "127.0.0.1", + "127.255.255.254", + "::1", + "[::1]", + "::ffff:127.0.0.1", + "[::ffff:127.0.0.1]", + "localhost", + "LOCALHOST", + ] { + assert!(loopback_host(host).is_some(), "{host} is a loopback claim"); + } + for host in [ + "localhost.", + "a.localhost", + "127.0.0.1.example", + "0.0.0.0", + "::", + "10.0.0.1", + "169.254.169.254", + "[::ffff:10.0.0.1]", + "[::1", + "::1]", + "", + ] { + assert!( + loopback_host(host).is_none(), + "{host:?} is not a loopback claim" + ); + } + } + + #[test] + fn the_name_is_a_name_claim_and_the_rest_are_literals() { + assert_eq!( + loopback_host("LocalHost"), + Some(LoopbackHost::LocalhostName) + ); + assert_eq!( + loopback_host("127.0.0.2"), + Some(LoopbackHost::Literal("127.0.0.2".parse().unwrap())) + ); + assert!(loopback_literal("localhost").is_none()); + assert!(loopback_literal("[::1]").is_some()); + } + + #[test] + fn a_name_claim_needs_every_resolved_address_to_be_loopback() { + let name = LoopbackHost::LocalhostName; + let v4: IpAddr = "127.0.0.1".parse().unwrap(); + let v6: IpAddr = "::1".parse().unwrap(); + let mapped: IpAddr = "::ffff:127.0.0.1".parse().unwrap(); + let other: IpAddr = "10.0.0.1".parse().unwrap(); + assert!(!name.pinned_by(&[])); + assert!(name.pinned_by(&[v4, v6, mapped])); + assert!(!name.pinned_by(&[v4, other])); + assert!(!name.pinned_by(&[other, v6])); + assert!(LoopbackHost::Literal(v4).pinned_by(&[])); + } + + #[test] + fn loopback_address_covers_the_block_and_mapped_forms() { + for ip in ["127.0.0.1", "127.9.9.9", "::1", "::ffff:127.0.0.1"] { + assert!(loopback_address(ip.parse().unwrap()), "{ip}"); + } + for ip in ["0.0.0.0", "::", "10.0.0.1", "::ffff:10.0.0.1", "fe80::1"] { + assert!(!loopback_address(ip.parse().unwrap()), "{ip}"); + } + } +} diff --git a/crates/registry-platform-httpsec/src/server.rs b/crates/registry-platform-httpsec/src/server.rs index 3b52a6ecb4..fa7b9e4e75 100644 --- a/crates/registry-platform-httpsec/src/server.rs +++ b/crates/registry-platform-httpsec/src/server.rs @@ -739,11 +739,7 @@ fn is_loopback_origin(url: &url::Url) -> bool { let Some(host) = url.host() else { return false; }; - match host { - url::Host::Domain(domain) => domain.eq_ignore_ascii_case("localhost"), - url::Host::Ipv4(ip) => ip.is_loopback(), - url::Host::Ipv6(ip) => ip.is_loopback(), - } + crate::loopback::loopback_host(&host.to_string()).is_some() } #[cfg(test)] diff --git a/crates/registry-platform-httputil/Cargo.toml b/crates/registry-platform-httputil/Cargo.toml index be5d793624..0d07d717c8 100644 --- a/crates/registry-platform-httputil/Cargo.toml +++ b/crates/registry-platform-httputil/Cargo.toml @@ -27,6 +27,7 @@ ipnet.workspace = true registry-platform-authcommon.workspace = true registry-platform-canonical-json.workspace = true registry-platform-crypto.workspace = true +registry-platform-httpsec.workspace = true reqwest.workspace = true rustls-native-certs.workspace = true serde.workspace = true diff --git a/crates/registry-platform-httputil/src/client/outbound.rs b/crates/registry-platform-httputil/src/client/outbound.rs index a1b935c193..4fc2239ed2 100644 --- a/crates/registry-platform-httputil/src/client/outbound.rs +++ b/crates/registry-platform-httputil/src/client/outbound.rs @@ -11,10 +11,6 @@ use url::Url; use super::TransportKind; -/// The one host name a cleartext URL may carry. It is reserved for the loopback -/// interface, so a credential sent to it cannot leave the host. -const LOOPBACK_NAME: &str = "localhost"; - /// What a caller may vary about an outbound client. Everything else is fixed by /// [`build_client`]. #[derive(Debug, Clone, Copy)] @@ -47,17 +43,17 @@ pub fn build_client(options: OutboundOptions<'_>) -> Result bool { match url.scheme() { "https" => true, - "http" => url.host().is_some_and(|host| match host { - url::Host::Ipv4(ip) => ip.is_loopback(), - url::Host::Ipv6(ip) => ip.is_loopback(), - url::Host::Domain(name) => name == LOOPBACK_NAME, - }), + "http" => url + .host() + .is_some_and(|host| crate::loopback::loopback_host(&host.to_string()).is_some()), _ => false, } } @@ -159,6 +155,32 @@ mod tests { (address, listener, held) } + #[test] + fn cleartext_is_protected_only_on_loopback() { + for raw in [ + "http://127.0.0.1/", + "http://127.9.9.9:8080/", + "http://[::1]/", + "http://localhost:8080/", + "http://LOCALHOST/", + "https://example.org/", + ] { + let url = Url::parse(raw).expect("url"); + assert!(transport_protects_the_credential(&url), "{raw}"); + } + for raw in [ + "http://a.localhost/", + "http://localhost./", + "http://10.0.0.1/", + "http://0.0.0.0/", + "http://example.org/", + "ftp://127.0.0.1/", + ] { + let url = Url::parse(raw).expect("url"); + assert!(!transport_protects_the_credential(&url), "{raw}"); + } + } + #[tokio::test] async fn a_connect_timeout_is_a_connection_failure() { let (address, _listener, _held) = unanswered_address().await; diff --git a/crates/registry-platform-httputil/src/destination.rs b/crates/registry-platform-httputil/src/destination.rs index 02acc1243f..4814825086 100644 --- a/crates/registry-platform-httputil/src/destination.rs +++ b/crates/registry-platform-httputil/src/destination.rs @@ -925,11 +925,10 @@ impl FixedDestinationPolicy { if !is_eligible_private_address(ip) { return Err(DestinationSendError::PrivateAddressNotAllowed); } - if self.allowed_private_cidrs.is_empty() - || self - .allowed_private_cidrs - .iter() - .any(|cidr| cidr.contains(&ip)) + if self + .allowed_private_cidrs + .iter() + .any(|cidr| cidr.contains(&ip)) { Ok(()) } else { @@ -4665,12 +4664,9 @@ fn validate_response_headers(headers: &HeaderMap) -> Result<(), DestinationSendE } fn origin_explicitly_denotes_loopback(origin: &Url) -> bool { - match origin.host() { - Some(::url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), - Some(::url::Host::Ipv4(ip)) => ip.is_loopback(), - Some(::url::Host::Ipv6(ip)) => is_loopback(normalize_ipv4_mapped(IpAddr::V6(ip))), - None => false, - } + origin + .host() + .is_some_and(|host| crate::loopback::loopback_host(&host.to_string()).is_some()) } /// RFC 6761 reserves `localhost.` and every name below it for loopback. A @@ -4708,10 +4704,7 @@ fn private_cidr_is_exact_host(cidr: IpNet, address: IpAddr) -> bool { } fn is_loopback(ip: IpAddr) -> bool { - match normalize_ipv4_mapped(ip) { - IpAddr::V4(ip) => ip.is_loopback(), - IpAddr::V6(ip) => ip.is_loopback(), - } + crate::loopback::loopback_address(ip) } fn is_always_denied_in_production(ip: IpAddr) -> bool { @@ -5678,8 +5671,13 @@ mod tests { &[], ) .expect("private service destination validates"); - assert_eq!(classify(&policy, &["10.89.0.4"]), Ok(())); - assert_eq!(classify(&policy, &["fd42::4"]), Ok(())); + for address in ["10.89.0.4", "fd42::4"] { + assert_eq!( + classify(&policy, &[address]), + Err(DestinationSendError::PrivateAddressNotAllowed), + "an empty private range list admits no private address: {address}" + ); + } for address in ["127.0.0.1", "169.254.169.254", "8.8.8.8", "::1"] { assert!( classify(&policy, &[address]).is_err(), @@ -5687,6 +5685,20 @@ mod tests { ); } + let listed = DataDestinationPolicy::new( + "private-service", + "http://registry-service:8080/", + DestinationProfile::PrivateServiceHttp, + &[cidr("10.0.0.0/8")], + ) + .expect("listed private service destination validates"); + assert_eq!(classify(&listed, &["10.0.0.5"]), Ok(())); + assert_eq!( + classify(&listed, &["169.254.169.254"]), + Err(DestinationSendError::CloudMetadataDenied), + "a metadata address stays refused beside a listed range" + ); + let narrowed = DataDestinationPolicy::new( "private-service", "http://registry-service:8080/", diff --git a/crates/registry-platform-httputil/src/lib.rs b/crates/registry-platform-httputil/src/lib.rs index 305a78274e..4345b57d28 100644 --- a/crates/registry-platform-httputil/src/lib.rs +++ b/crates/registry-platform-httputil/src/lib.rs @@ -8,6 +8,8 @@ use thiserror::Error; pub mod client; pub mod destination; +pub mod probe; +pub use registry_platform_httpsec::loopback; pub use client::{ exchange_authorization_from_json, valid_resource_uri, valid_scope_token, @@ -85,6 +87,9 @@ pub const DEFAULT_VALIDATED_FETCH_TIMEOUT: Duration = Duration::from_secs(30); pub const DEFAULT_VALIDATED_FETCH_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); pub const DEFAULT_OUTBOUND_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +/// The one host name pinned to the loopback addresses in every built client. +const LOCALHOST_NAME: &str = "localhost"; + /// Builder for outbound HTTP clients used by platform fetchers. #[derive(Clone)] pub struct OutboundClientBuilder { @@ -199,6 +204,16 @@ impl OutboundClientBuilder { } builder = builder.tls_built_in_root_certs(false); } + // The name `localhost` is pinned to the loopback addresses, so no resolver + // is asked for it and a cleartext credential sent to it cannot leave the + // host. The port 0 takes the port of each request URL. + builder = builder.resolve_to_addrs( + LOCALHOST_NAME, + &[ + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0), + SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 0), + ], + ); if let Some((host, addrs)) = self.resolved_host { builder = builder.resolve_to_addrs(&host, &addrs); } @@ -735,12 +750,11 @@ fn resolve_host(url: &reqwest::Url) -> Result, FetchUrlError> { fn host_is_allowed_localhost(host: ::url::Host<&str>, resolved: &[IpAddr]) -> bool { match host { - ::url::Host::Ipv4(ip) => ip.is_loopback(), - ::url::Host::Ipv6(ip) => ip == Ipv6Addr::LOCALHOST, - ::url::Host::Domain(host) if host.eq_ignore_ascii_case("localhost") => { - resolved.iter().all(|ip| is_loopback_ip(*ip)) + ::url::Host::Ipv4(ip) => loopback::loopback_address(IpAddr::V4(ip)), + ::url::Host::Ipv6(ip) => loopback::loopback_address(IpAddr::V6(ip)), + ::url::Host::Domain(name) => { + loopback::loopback_host(name).is_some_and(|claim| claim.pinned_by(resolved)) } - ::url::Host::Domain(_) => false, } } @@ -762,10 +776,7 @@ pub fn is_cloud_metadata_ip(ip: IpAddr) -> bool { } fn is_loopback_ip(ip: IpAddr) -> bool { - match normalize_ipv4_mapped(ip) { - IpAddr::V4(ip) => ip.is_loopback(), - IpAddr::V6(ip) => ip.is_loopback(), - } + loopback::loopback_address(ip) } fn is_private_or_link_local_ip(ip: IpAddr) -> bool { @@ -1047,6 +1058,78 @@ mod tests { assert_eq!(response.status(), StatusCode::FOUND); } + /// Serve one route on `address` and return its URL with the host name + /// `localhost` and the bound port. + async fn serve_on(address: &str) -> String { + let listener = TcpListener::bind(address).await.expect("bind test server"); + let port = listener.local_addr().expect("read listener addr").port(); + let router = Router::new().route("/", get(|| async { "ok" })); + tokio::spawn(async move { + axum::serve(listener, router).await.expect("serve"); + }); + format!("http://localhost:{port}/") + } + + async fn reaches(client: &reqwest::Client, url: &str) -> bool { + match client.get(url).send().await { + Ok(response) => response.status() == StatusCode::OK, + Err(_) => false, + } + } + + #[tokio::test] + async fn an_override_with_port_zero_follows_the_url_port_and_only_the_listed_addresses() { + let v4_only = serve_on("127.0.0.1:0").await; + let v6_only = serve_on("[::1]:0").await; + let pinned_v4 = OutboundClientBuilder::new() + .resolve_to_addrs( + "localhost".to_string(), + vec!["127.0.0.1:0".parse().unwrap()], + ) + .try_build() + .expect("client"); + assert!( + reaches(&pinned_v4, &v4_only).await, + "port 0 takes the URL port" + ); + assert!( + !reaches(&pinned_v4, &v6_only).await, + "an address outside the override is never tried" + ); + } + + #[tokio::test] + async fn the_service_client_reaches_localhost_on_either_loopback_family() { + let v4_only = serve_on("127.0.0.1:0").await; + let v6_only = serve_on("[::1]:0").await; + let client = OutboundClientBuilder::new().try_build().expect("client"); + assert!(reaches(&client, &v4_only).await, "IPv4-only listener"); + assert!(reaches(&client, &v6_only).await, "IPv6-only listener"); + } + + #[test] + fn the_localhost_name_is_allowed_only_when_every_answer_is_loopback() { + let name = ::url::Host::Domain("localhost"); + let other: IpAddr = "10.0.0.1".parse().unwrap(); + let v4: IpAddr = "127.0.0.1".parse().unwrap(); + assert!(host_is_allowed_localhost(name.clone(), &[v4])); + assert!(!host_is_allowed_localhost(name.clone(), &[v4, other])); + assert!(!host_is_allowed_localhost(name, &[])); + assert!(!host_is_allowed_localhost( + ::url::Host::Domain("a.localhost"), + &[v4] + )); + } + + #[test] + fn an_ipv4_mapped_loopback_literal_is_loopback_for_a_dev_fetch_only() { + let url = reqwest::Url::parse("http://[::ffff:127.0.0.1]:8080/jwks").expect("url parses"); + FetchUrlPolicy::dev() + .validate(&url) + .expect("a mapped loopback literal is loopback"); + assert!(FetchUrlPolicy::strict().validate(&url).is_err()); + } + #[test] fn outbound_clients_ignore_ambient_proxy_variables_in_an_isolated_process() { if std::env::var_os("REGISTRY_HTTP_PROXY_CHILD").is_some() { @@ -1513,6 +1596,7 @@ mod tests { "http://127.42.0.1/jwks", "http://[::1]/jwks", "http://localhost/jwks", + "http://[::ffff:127.0.0.1]/jwks", ] { let url = reqwest::Url::parse(raw).expect("url parses"); FetchUrlPolicy::dev() @@ -1523,7 +1607,10 @@ mod tests { for raw in [ "http://93.184.216.34/jwks", "http://10.0.0.1/jwks", - "http://[::ffff:127.0.0.1]/jwks", + "http://[::ffff:10.0.0.1]/jwks", + "http://[::ffff:93.184.216.34]/jwks", + "http://[::ffff:169.254.169.254]/jwks", + "http://[::ffff:0.0.0.0]/jwks", ] { let url = reqwest::Url::parse(raw).expect("url parses"); assert!( diff --git a/crates/registry-platform-httputil/src/probe.rs b/crates/registry-platform-httputil/src/probe.rs new file mode 100644 index 0000000000..f5bd8dd546 --- /dev/null +++ b/crates/registry-platform-httputil/src/probe.rs @@ -0,0 +1,36 @@ +//! Paths and bodies of the liveness and readiness probes every Registry Stack +//! service answers. + +/// Path of the liveness probe. It needs no authentication and does no I/O. +pub const HEALTH_PATH: &str = "/health"; +/// Path of the readiness probe. It needs no authentication. +pub const READY_PATH: &str = "/ready"; +/// Body of a successful liveness probe, served as `application/json`. +pub const HEALTH_BODY: &str = r#"{"status":"ok"}"#; +/// Body of a successful readiness probe, served as `application/json`. +pub const READY_BODY: &str = r#"{"status":"ready"}"#; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_are_the_documented_probe_routes() { + assert_eq!(HEALTH_PATH, "/health"); + assert_eq!(READY_PATH, "/ready"); + } + + #[test] + fn bodies_are_json_objects_with_the_status_word() { + let health: serde_json::Value = serde_json::from_str(HEALTH_BODY).unwrap(); + let ready: serde_json::Value = serde_json::from_str(READY_BODY).unwrap(); + assert_eq!(health, serde_json::json!({"status": "ok"})); + assert_eq!(ready, serde_json::json!({"status": "ready"})); + } + + #[test] + fn bodies_are_compact_so_they_compare_byte_for_byte() { + assert_eq!(HEALTH_BODY, r#"{"status":"ok"}"#); + assert_eq!(READY_BODY, r#"{"status":"ready"}"#); + } +} diff --git a/crates/registry-platform-objectstore/src/s3.rs b/crates/registry-platform-objectstore/src/s3.rs index 530e1a540a..1ac14a7f9e 100644 --- a/crates/registry-platform-objectstore/src/s3.rs +++ b/crates/registry-platform-objectstore/src/s3.rs @@ -100,8 +100,8 @@ impl S3Settings { let mut url = Url::parse(text).map_err(|_| ObjectStoreError::InvalidConfiguration)?; let loopback = url .host_str() - .and_then(|host| host.trim_matches(['[', ']']).parse::().ok()) - .is_some_and(|ip| ip.is_loopback()); + .and_then(registry_platform_httputil::loopback::loopback_literal) + .is_some(); let bucket = config.bucket.as_str(); let region = config.region.as_str(); if text.len() > MAXIMUM_URL_BYTES diff --git a/crates/registry-platform-objectstore/src/s3_tests.rs b/crates/registry-platform-objectstore/src/s3_tests.rs index c07f87b04f..c6ae010064 100644 --- a/crates/registry-platform-objectstore/src/s3_tests.rs +++ b/crates/registry-platform-objectstore/src/s3_tests.rs @@ -337,6 +337,25 @@ fn strict_storage_configuration_and_debug_are_value_free() { settings(input).unwrap_err(), ObjectStoreError::InvalidConfiguration ); + for url in [ + "http://127.0.0.2:1234", + "http://[::1]:1234", + "http://[::ffff:127.0.0.1]:1234", + ] { + settings(raw(url)).unwrap_or_else(|error| panic!("{url}: {error:?}")); + } + for url in [ + "http://localhost:1234", + "http://storage.localhost:1234", + "http://0.0.0.0:1234", + "http://[::ffff:10.0.0.1]:1234", + ] { + assert_eq!( + settings(raw(url)).unwrap_err(), + ObjectStoreError::InvalidConfiguration, + "{url}" + ); + } let accepted = settings(raw("https://storage.example")).unwrap(); assert_eq!( accepted.bucket_url.as_str(), diff --git a/crates/registry-platform-objectstore/src/verifier.rs b/crates/registry-platform-objectstore/src/verifier.rs index 527f8333c5..e4b52dc079 100644 --- a/crates/registry-platform-objectstore/src/verifier.rs +++ b/crates/registry-platform-objectstore/src/verifier.rs @@ -13,7 +13,7 @@ //! scanner and rules generation the operator bound the URL to, and enters //! only the binding digest a product records beside each verdict. -use std::{fmt, net::IpAddr, time::Duration}; +use std::{fmt, time::Duration}; use registry_platform_config::{ AttachmentVerifierConfig, ProtectedSecret, SecretReference, SecretResolver, @@ -106,8 +106,8 @@ impl HttpVerifierSettings { let url = Url::parse(text).map_err(|_| VerifierError::InvalidConfiguration)?; let loopback = url .host_str() - .and_then(|host| host.trim_matches(['[', ']']).parse::().ok()) - .is_some_and(|ip| ip.is_loopback()); + .and_then(registry_platform_httputil::loopback::loopback_literal) + .is_some(); let policy_id = config.policy_id.as_str(); if text.len() > MAXIMUM_URL_BYTES || text.trim() != text diff --git a/crates/registry-platform-objectstore/src/verifier_tests.rs b/crates/registry-platform-objectstore/src/verifier_tests.rs index 9da8e14ab7..1ff1704327 100644 --- a/crates/registry-platform-objectstore/src/verifier_tests.rs +++ b/crates/registry-platform-objectstore/src/verifier_tests.rs @@ -143,6 +143,25 @@ fn verifier_config_is_strict_and_redacted() { "{url}" ); } + for url in [ + "http://127.0.0.2/verify", + "http://[::1]/verify", + "http://[::ffff:127.0.0.1]/verify", + ] { + settings(raw(url)).unwrap_or_else(|error| panic!("{url}: {error:?}")); + } + for url in [ + "http://localhost/verify", + "http://verifier.localhost/verify", + "http://0.0.0.0/verify", + "http://[::ffff:10.0.0.1]/verify", + ] { + assert_eq!( + settings(raw(url)).unwrap_err(), + VerifierError::InvalidConfiguration, + "{url}" + ); + } // The shared block's `Url` already refuses these at decode. for url in [ "https://user:secret@example/verify", diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index 2dded540d9..76520515f1 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -92,14 +92,10 @@ impl IssuerNetworkPolicy { { return Err(OidcError::InvalidUrl); } - let loopback = issuer.host_str().is_some_and(|host| { - host.eq_ignore_ascii_case("localhost") - || host - .trim_start_matches('[') - .trim_end_matches(']') - .parse::() - .is_ok_and(|address| address.is_loopback()) - }); + let loopback = issuer + .host_str() + .and_then(registry_platform_httputil::loopback::loopback_host) + .is_some(); if issuer.scheme() == "http" && !loopback && !allow_insecure_http { return Err(OidcError::InsecureHttpRequiresOptIn); } @@ -1926,6 +1922,33 @@ mod tests { .expect("IPv6 loopback keeps the same development behavior"); } + #[test] + fn issuer_loopback_follows_the_shared_definition() { + for issuer in [ + "http://127.0.0.1:8080", + "http://127.0.0.2:8080", + "http://[::1]:8080", + "http://[::ffff:127.0.0.1]:8080", + "http://localhost:8080", + "http://LOCALHOST:8080", + ] { + IssuerNetworkPolicy::new(issuer, false) + .unwrap_or_else(|error| panic!("{issuer}: {error:?}")); + } + for issuer in [ + "http://localhost.:8080", + "http://issuer.localhost:8080", + "http://0.0.0.0:8080", + "http://[::ffff:10.0.0.1]:8080", + ] { + let error = IssuerNetworkPolicy::new(issuer, false).expect_err(issuer); + assert!( + matches!(error, OidcError::InsecureHttpRequiresOptIn), + "{issuer}" + ); + } + } + #[test] fn a_cross_origin_jwks_must_use_https_even_under_the_http_opt_in() { let network = IssuerNetworkPolicy::new("http://93.184.216.34:8080", true).unwrap(); From bf0fcac60ac59560b1889859bd4cf6d3d0778f59 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:19:18 +0100 Subject: [PATCH 005/136] feat(platform): add the provisioning command, its print mode and its report Each product tool will offer the same provision command. The cli feature of registry-platform-provision parses its flags, prints the plan as SQL with password placeholders and no connection, or runs it against an administrator connection read from a file or a variable, and answers with a typed JSON report whose schema is generated and registered. Signed-off-by: Jeremi Joslin --- Cargo.lock | 7 + crates/registry-platform-provision/Cargo.toml | 25 +- .../example/provision-report.json | 38 + .../examples/provision-report-schema.rs | 40 + .../schema/provision-report.schema.json | 329 +++ crates/registry-platform-provision/src/cli.rs | 1916 +++++++++++++++++ crates/registry-platform-provision/src/lib.rs | 5 + .../identifiers/contracts/catalog-source.json | 8 + .../identifiers/generated/catalog.v1.json | 18 + products/platform/config-formats.yaml | 31 + 10 files changed, 2416 insertions(+), 1 deletion(-) create mode 100644 crates/registry-platform-provision/example/provision-report.json create mode 100644 crates/registry-platform-provision/examples/provision-report-schema.rs create mode 100644 crates/registry-platform-provision/schema/provision-report.schema.json create mode 100644 crates/registry-platform-provision/src/cli.rs diff --git a/Cargo.lock b/Cargo.lock index 449febe216..7dfada62c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8035,10 +8035,17 @@ dependencies = [ name = "registry-platform-provision" version = "0.49.0" dependencies = [ + "clap", "getrandom 0.4.3", "postgres-protocol", + "registry-cli-report", "registry-platform-activation", + "registry-platform-yaml", "rustls", + "schemars", + "serde", + "serde_json", + "tempfile", "thiserror 2.0.21", "tokio", "tokio-postgres", diff --git a/crates/registry-platform-provision/Cargo.toml b/crates/registry-platform-provision/Cargo.toml index 1daa1c7cb5..8f63e1de03 100644 --- a/crates/registry-platform-provision/Cargo.toml +++ b/crates/registry-platform-provision/Cargo.toml @@ -16,17 +16,39 @@ default = [] # Runs tests/postgres.rs against the disposable PostgreSQL superuser named by # PROVISION_TEST_DATABASE_URL, over TLS verified with PROVISION_TEST_DATABASE_CA. # It also needs PROVISION_TEST_OLD_DATABASE_URL, a server older than the floor. -# With the feature on, a missing variable fails the suite. +# With the feature on, a missing variable fails the suite. With `cli` on too, +# src/cli.rs also runs the `provision` command against the first server. postgres-test = [] +# The shared `provision` command: clap arguments, the runner and the report. +cli = [ + "dep:clap", + "dep:registry-cli-report", + "dep:registry-platform-yaml", + "dep:serde", + "dep:serde_json", +] +# Renders the report's JSON Schema from its Rust type. +schema = ["cli", "dep:schemars", "registry-platform-yaml/schema"] + [[test]] name = "postgres" required-features = ["postgres-test"] +[[example]] +name = "provision-report-schema" +required-features = ["schema"] + [dependencies] +clap = { workspace = true, optional = true } postgres-protocol.workspace = true +registry-cli-report = { workspace = true, optional = true } registry-platform-activation.workspace = true +registry-platform-yaml = { workspace = true, optional = true } rustls.workspace = true +schemars = { workspace = true, optional = true } +serde = { workspace = true, optional = true } +serde_json = { workspace = true, optional = true } thiserror.workspace = true tokio = { workspace = true, features = ["rt", "time"] } tokio-postgres.workspace = true @@ -36,4 +58,5 @@ zeroize.workspace = true [dev-dependencies] getrandom.workspace = true +tempfile.workspace = true tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } diff --git a/crates/registry-platform-provision/example/provision-report.json b/crates/registry-platform-provision/example/provision-report.json new file mode 100644 index 0000000000..c51a030d17 --- /dev/null +++ b/crates/registry-platform-provision/example/provision-report.json @@ -0,0 +1,38 @@ +{ + "ok": true, + "command": "provision", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1", + "kind": "PlatformCliDatabaseProvisionReport", + "version": "0.49.0", + "product": "casework", + "executed": true, + "roleMode": "split", + "database": "casework", + "migrationRole": "casework_migration", + "runtimeRole": "casework_runtime", + "statements": [ + { + "step": "role.migration", + "scope": "server", + "needs": "createrole", + "outcome": "created", + "sql": "CREATE ROLE \"casework_migration\" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS" + }, + { + "step": "database.create", + "scope": "server", + "needs": "createdb", + "outcome": "present", + "sql": "CREATE DATABASE \"casework\" WITH ALLOW_CONNECTIONS false" + }, + { + "step": "database.revoke-public", + "scope": "server", + "needs": "database-owner", + "outcome": "applied", + "sql": "REVOKE ALL ON DATABASE \"casework\" FROM PUBLIC" + } + ], + "diagnostics": [] +} diff --git a/crates/registry-platform-provision/examples/provision-report-schema.rs b/crates/registry-platform-provision/examples/provision-report-schema.rs new file mode 100644 index 0000000000..5034db380e --- /dev/null +++ b/crates/registry-platform-provision/examples/provision-report-schema.rs @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 + +#[cfg(feature = "schema")] +fn main() -> std::process::ExitCode { + let usage = "usage: provision-report-schema --output "; + let mut arguments = std::env::args_os().skip(1); + let (Some(flag), Some(output), None) = (arguments.next(), arguments.next(), arguments.next()) + else { + eprintln!("{usage}"); + return std::process::ExitCode::from(2); + }; + if flag != "--output" { + eprintln!("{usage}"); + return std::process::ExitCode::from(2); + } + let output = std::path::PathBuf::from(output); + let document = match registry_platform_provision::cli::report_schema_document() { + Ok(document) => document, + Err(error) => { + eprintln!("provision report schema generation failed: {error}"); + return std::process::ExitCode::FAILURE; + } + }; + let written = match output.parent() { + Some(parent) => std::fs::create_dir_all(parent), + None => Ok(()), + } + .and_then(|()| std::fs::write(&output, document)); + if let Err(error) = written { + eprintln!("provision report schema generation failed: {error}"); + return std::process::ExitCode::FAILURE; + } + std::process::ExitCode::SUCCESS +} + +#[cfg(not(feature = "schema"))] +fn main() -> std::process::ExitCode { + eprintln!("provision-report-schema requires the schema feature"); + std::process::ExitCode::from(2) +} diff --git a/crates/registry-platform-provision/schema/provision-report.schema.json b/crates/registry-platform-provision/schema/provision-report.schema.json new file mode 100644 index 0000000000..91864c303d --- /dev/null +++ b/crates/registry-platform-provision/schema/provision-report.schema.json @@ -0,0 +1,329 @@ +{ + "$defs": { + "CheckScope": { + "additionalProperties": false, + "description": "A source file relative to the project and the resource path a check reports.", + "properties": { + "file": { + "minLength": 1, + "type": "string" + }, + "path": { + "description": "A pointer whose list positions use existing unique identifiers when available.", + "type": "string" + } + }, + "required": [ + "file", + "path" + ], + "type": "object" + }, + "Diagnostic": { + "additionalProperties": false, + "description": "One problem, in the shape every checking command reports (CFG-DIAG-1).\n\nMessages name keys, paths, accepted values, bounds, and the expected\nenvelope without repeating rejected scalar values (CFG-SEC-3). Warning\nacceptance metadata separately identifies the resource and carries the\nproject's deliberately authored reason.", + "properties": { + "acceptedReason": { + "description": "The project's reason for accepting this advisory warning.", + "type": [ + "string", + "null" + ] + }, + "artifact": { + "description": "The document's `kind`, or the expected kind when the document's own is\nabsent or wrong and the reader expected exactly one.", + "type": [ + "string", + "null" + ] + }, + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "RFC 6901 JSON pointer into the document as written; `\"\"` is the root.", + "type": "string" + }, + "related": { + "items": { + "$ref": "#/$defs/Related" + }, + "type": "array" + }, + "scope": { + "anyOf": [ + { + "$ref": "#/$defs/CheckScope" + }, + { + "type": "null" + } + ], + "description": "Project-relative identity copied into a check acceptance." + }, + "severity": { + "$ref": "#/$defs/Severity" + }, + "source": { + "anyOf": [ + { + "$ref": "#/$defs/Source" + }, + { + "type": "null" + } + ] + }, + "suggestedAction": { + "type": "string" + } + }, + "required": [ + "severity", + "code", + "path", + "message", + "suggestedAction" + ], + "type": "object" + }, + "Related": { + "additionalProperties": false, + "description": "A second place that explains a diagnostic, such as the first occurrence\nof a duplicate. Human output prints it as a `note:` line.", + "properties": { + "column": { + "format": "uint", + "maximum": 18446744073709551615, + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 18446744073709551615, + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "message": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "file", + "path", + "message" + ], + "type": "object" + }, + "ReportNeeds": { + "enum": [ + "createrole", + "createdb", + "database-owner", + "superuser" + ], + "type": "string" + }, + "ReportOutcome": { + "enum": [ + "created", + "present", + "applied", + "not-run" + ], + "type": "string" + }, + "ReportScope": { + "enum": [ + "server", + "database" + ], + "type": "string" + }, + "ReportStatement": { + "additionalProperties": false, + "description": "One planned statement. `sql` is the printable form, never a password or a\nverifier.", + "properties": { + "needs": { + "$ref": "#/$defs/ReportNeeds" + }, + "outcome": { + "$ref": "#/$defs/ReportOutcome" + }, + "scope": { + "$ref": "#/$defs/ReportScope" + }, + "sql": { + "type": "string" + }, + "step": { + "type": "string" + } + }, + "required": [ + "step", + "scope", + "needs", + "outcome", + "sql" + ], + "type": "object" + }, + "ReportStatus": { + "description": "Result class of a run, as in every other verb's report.", + "enum": [ + "complete", + "domain-refusal", + "usage-error", + "operational-failure" + ], + "type": "string" + }, + "RoleMode": { + "enum": [ + "split", + "single" + ], + "type": "string" + }, + "Severity": { + "description": "Whether a diagnostic refuses the input.", + "enum": [ + "error", + "warning" + ], + "type": "string" + }, + "Source": { + "additionalProperties": false, + "description": "Where a diagnostic points. `file` is the path exactly as the caller gave\nit; `line` and `column` are 1-based and absent when the problem concerns\nthe file as a whole.", + "properties": { + "column": { + "format": "uint", + "maximum": 18446744073709551615, + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 18446744073709551615, + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "file" + ], + "type": "object" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/cli-database-provision-report/cli-database-provision-report.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Machine-readable result of `provision` for every database-backed tool.\nThe identity members are absent when the run stopped before the product's\nruntime file could name them.", + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1" + }, + "command": { + "const": "provision" + }, + "database": { + "type": [ + "string", + "null" + ] + }, + "diagnostics": { + "items": { + "$ref": "#/$defs/Diagnostic" + }, + "type": "array" + }, + "executed": { + "type": "boolean" + }, + "kind": { + "const": "PlatformCliDatabaseProvisionReport" + }, + "migrationRole": { + "type": [ + "string", + "null" + ] + }, + "ok": { + "type": "boolean" + }, + "product": { + "type": [ + "string", + "null" + ] + }, + "roleMode": { + "anyOf": [ + { + "$ref": "#/$defs/RoleMode" + }, + { + "type": "null" + } + ] + }, + "runtimeRole": { + "type": [ + "string", + "null" + ] + }, + "statements": { + "items": { + "$ref": "#/$defs/ReportStatement" + }, + "type": "array" + }, + "status": { + "$ref": "#/$defs/ReportStatus" + }, + "version": { + "type": "string" + } + }, + "required": [ + "ok", + "command", + "status", + "apiVersion", + "kind", + "version", + "executed", + "statements", + "diagnostics" + ], + "title": "Registry Stack CLI database provision report", + "type": "object" +} diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs new file mode 100644 index 0000000000..4681f715dd --- /dev/null +++ b/crates/registry-platform-provision/src/cli.rs @@ -0,0 +1,1916 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The `provision` command every database-backed tool shares: its arguments, +//! its runner and its report. +//! +//! A product supplies a loader that turns its runtime file into a +//! [`ProvisionInput`]. The runner takes role and database names and passwords +//! from the two product URLs, so each credential is stored once. It never +//! prints a password, a verifier or a URL. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::str::FromStr; + +use registry_platform_yaml::Diagnostic; +use serde::Serialize; +use tokio_postgres::config::Host; +use tokio_postgres::Config; +use url::Url; +use zeroize::Zeroizing; + +use crate::{ + admin_config, execute, render_script, verify_logins, AdminConfig, AdminConfigError, Mode, + Needs, Outcome, Plan, ProductDatabase, ProvisionError, ProvisionTarget, RoleCredential, Scope, + StatementOutcome, +}; + +pub const REPORT_API_VERSION: &str = + "id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1"; +pub const REPORT_KIND: &str = "PlatformCliDatabaseProvisionReport"; + +/// How the command writes its result. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)] +pub enum OutputFormat { + #[default] + Text, + Json, +} + +/// The flags of ` provision`. +#[derive(clap::Args, Debug, Clone)] +pub struct ProvisionArgs { + /// The product's runtime file, the one `apply` reads + #[arg(long, value_name = "FILE")] + pub runtime_config: PathBuf, + /// File holding the administrator PostgreSQL URL + #[arg( + long, + value_name = "ADMIN_URL_FILE", + conflicts_with_all = ["admin_url_env", "print_sql"], + required_unless_present_any = ["admin_url_env", "print_sql"] + )] + pub admin_url_file: Option, + /// Name of the environment variable holding the administrator PostgreSQL URL + #[arg( + long, + value_name = "ADMIN_URL_ENV", + conflicts_with = "print_sql", + required_unless_present_any = ["admin_url_file", "print_sql"] + )] + pub admin_url_env: Option, + /// Print the SQL script and connect to nothing + #[arg(long)] + pub print_sql: bool, + /// Output format + #[arg(long, value_enum, default_value_t)] + pub format: OutputFormat, +} + +/// What a product's loader hands the runner. A loader refuses with one +/// diagnostic, boxed because the diagnostic is large. +pub struct ProvisionInput { + pub product: ProductDatabase, + pub migration_url: Zeroizing, + pub runtime_url: Zeroizing, + /// The CA behind `database.caBundleRef`, for the administrator connection. + pub ca_pem: Option>, +} + +/// Result class of a run, as in every other verb's report. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReportStatus { + Complete, + DomainRefusal, + UsageError, + OperationalFailure, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum RoleMode { + Split, + Single, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReportScope { + Server, + Database, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum ReportNeeds { + #[serde(rename = "createrole")] + CreateRole, + #[serde(rename = "createdb")] + CreateDb, + #[serde(rename = "database-owner")] + DatabaseOwner, + #[serde(rename = "superuser")] + Superuser, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReportOutcome { + Created, + Present, + Applied, + NotRun, +} + +/// One planned statement. `sql` is the printable form, never a password or a +/// verifier. +#[derive(Clone, Debug, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase")] +pub struct ReportStatement { + pub step: String, + pub scope: ReportScope, + pub needs: ReportNeeds, + pub outcome: ReportOutcome, + pub sql: String, +} + +/// Machine-readable result of `provision` for every database-backed tool. +/// The identity members are absent when the run stopped before the product's +/// runtime file could name them. +#[derive(Clone, Debug, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase")] +pub struct PlatformCliDatabaseProvisionReport { + pub ok: bool, + pub command: String, + pub status: ReportStatus, + pub api_version: String, + pub kind: String, + pub version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option, + pub executed: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub role_mode: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub database: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub migration_role: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_role: Option, + pub statements: Vec, + pub diagnostics: Vec, +} + +/// Runs the plan and then checks that each product role can log in. A test +/// replaces it, so the report logic needs no server. +type Backend<'a> = + &'a dyn Fn(&AdminConfig, &Plan, &ProvisionTarget) -> Result; + +/// The most bytes read from the administrator URL file. +const MAXIMUM_ADMIN_URL_BYTES: u64 = 8192; +const DEFAULT_PORT: u16 = 5432; + +/// A product URL reduced to what provisioning takes from it. +struct Endpoint { + user: String, + password: Zeroizing, + database: String, + host: String, + port: u16, +} + +/// The query keys that would change which server, role or database a URL names. +const ENDPOINT_QUERY_KEYS: [&str; 6] = ["host", "hostaddr", "port", "user", "password", "dbname"]; + +/// Reads the role, password, database and endpoint out of a product URL. +/// The query is dropped after the keys that override the endpoint are refused: +/// the product's own reader validates the rest (`sslmode` and so on). +fn parse_endpoint(url: &str) -> Option { + let parsed = Url::parse(url).ok()?; + if !matches!(parsed.scheme(), "postgres" | "postgresql") + || parsed.cannot_be_a_base() + || parsed.fragment().is_some() + || parsed + .query_pairs() + .any(|(key, _)| ENDPOINT_QUERY_KEYS.contains(&key.as_ref())) + { + return None; + } + let mut bare = parsed; + bare.set_query(None); + let config = Config::from_str(bare.as_str()).ok()?; + let host = match config.get_hosts() { + [Host::Tcp(host)] => host.clone(), + _ => return None, + }; + let user = config.get_user().filter(|user| !user.is_empty())?; + let password = config + .get_password() + .filter(|password| !password.is_empty()) + .and_then(|password| String::from_utf8(password.to_vec()).ok())?; + let database = config.get_dbname().filter(|name| !name.is_empty())?; + Some(Endpoint { + user: user.to_owned(), + password: Zeroizing::new(password), + database: database.to_owned(), + host, + port: config.get_ports().first().copied().unwrap_or(DEFAULT_PORT), + }) +} + +/// How a run ended before any report could be written. +struct Refusal { + status: ReportStatus, + diagnostic: Box, +} + +fn refuse( + status: ReportStatus, + code: &str, + path: &str, + message: impl Into, + action: impl Into, +) -> Refusal { + Refusal { + status, + diagnostic: Box::new(Diagnostic::error(code, path, message, action)), + } +} + +fn target_invalid(message: &str) -> Refusal { + refuse( + ReportStatus::UsageError, + "platform.provision.target-invalid", + "", + message, + "Correct database.migrationUrlRef and database.runtimeUrlRef in the runtime file, then \ + run provision again.", + ) +} + +fn target_mismatch(message: String) -> Refusal { + refuse( + ReportStatus::DomainRefusal, + "platform.provision.target-mismatch", + "", + message, + "Point the URLs at one server and one database, then run provision again.", + ) +} + +/// The first of host, port and database that two endpoints disagree on. +fn first_difference(left: &Endpoint, right: &Endpoint) -> Option<&'static str> { + if !left.host.eq_ignore_ascii_case(&right.host) { + Some("host") + } else if left.port != right.port { + Some("port") + } else if left.database != right.database { + Some("database") + } else { + None + } +} + +fn read_admin_url(args: &ProvisionArgs) -> Result, Refusal> { + let unusable = |message: String, action: &str| { + refuse( + ReportStatus::UsageError, + "platform.provision.admin-url-invalid", + "", + message, + action, + ) + }; + let raw = match (&args.admin_url_file, &args.admin_url_env) { + (Some(path), None) => { + let read = std::fs::File::open(path).and_then(|file| { + let mut text = String::new(); + file.take(MAXIMUM_ADMIN_URL_BYTES + 1) + .read_to_string(&mut text) + .map(|_| text) + }); + match read { + Ok(text) if text.len() as u64 <= MAXIMUM_ADMIN_URL_BYTES => Zeroizing::new(text), + Ok(_) => { + return Err(unusable( + "the administrator URL file is larger than 8 KiB".to_owned(), + "Put only the administrator PostgreSQL URL in the file.", + )) + } + Err(_) => { + return Err(unusable( + "the administrator URL file could not be read".to_owned(), + "Check that --admin-url-file names a readable file holding the \ + administrator PostgreSQL URL.", + )) + } + } + } + (None, Some(name)) => match std::env::var(name) { + Ok(value) => Zeroizing::new(value), + Err(_) => { + return Err(unusable( + format!("the environment variable {name} is not set or is not UTF-8 text"), + "Export the administrator PostgreSQL URL in the variable that \ + --admin-url-env names.", + )) + } + }, + _ => { + return Err(unusable( + "exactly one administrator URL source is required".to_owned(), + "Pass --admin-url-file or --admin-url-env, or --print-sql.", + )) + } + }; + let url = raw.trim(); + if url.is_empty() { + return Err(unusable( + "the administrator URL is empty".to_owned(), + "Put the administrator PostgreSQL URL in the file or variable.", + )); + } + Ok(Zeroizing::new(url.to_owned())) +} + +fn admin_refusal(error: AdminConfigError) -> Refusal { + let url_rule = error.code() == "platform.provision.admin-url-invalid"; + refuse( + if url_rule { + ReportStatus::UsageError + } else { + ReportStatus::DomainRefusal + }, + error.code(), + "", + error.to_string(), + if url_rule { + "Correct the administrator URL, then run provision again." + } else { + "Correct database.caBundleRef in the runtime file, or install the CA in the system \ + trust store, then run provision again." + }, + ) +} + +/// What the report says about a refusal from the executor, with the exit +/// class of its code. +fn execution_refusal(tool: &str, error: &ProvisionError) -> Refusal { + use ProvisionError as E; + let (status, action) = match error { + E::AdminConnectFailed { .. } => ( + ReportStatus::OperationalFailure, + "Check the host, port, credentials and TLS certificate of the administrator URL, \ + then run provision again." + .to_owned(), + ), + E::UnsupportedPostgres => ( + ReportStatus::DomainRefusal, + "Provision a PostgreSQL 17 or newer server, then run provision again.".to_owned(), + ), + E::StatementNeedsPrivilege { .. } => ( + ReportStatus::DomainRefusal, + format!( + "run this statement as a role that has it, or run \"{tool} provision \ + --print-sql\" and give the script to the database administrator, then run \ + provision again" + ), + ), + E::RoleAttributesDiffer { .. } => ( + ReportStatus::DomainRefusal, + "Use another role name in the product URLs, or correct the role as an administrator, \ + then run provision again." + .to_owned(), + ), + E::DatabaseOwnerDiffers { .. } => ( + ReportStatus::DomainRefusal, + "Use another database name, or run provision as the database owner or a role that \ + can act as it." + .to_owned(), + ), + E::SchemaOwnerDiffers { .. } => ( + ReportStatus::DomainRefusal, + "Make the migration role the owner of the schema as an administrator, or use \ + another database, then run provision again." + .to_owned(), + ), + E::ExtensionTooOld { .. } => ( + ReportStatus::DomainRefusal, + "Upgrade the extension as a superuser, then run provision again.".to_owned(), + ), + E::RoleLoginFailed { .. } => ( + ReportStatus::DomainRefusal, + "The role exists with a different password. Set its password to the one in its \ + product URL as an administrator, or correct the URL, then run provision again." + .to_owned(), + ), + E::EffectUnconfirmed { .. } => ( + ReportStatus::OperationalFailure, + "Run provision again.".to_owned(), + ), + E::StatementFailed { .. } => ( + ReportStatus::OperationalFailure, + "Read the PostgreSQL server log for that statement, fix the cause, then run \ + provision again." + .to_owned(), + ), + }; + refuse( + status, + error.code(), + error.step().unwrap_or(""), + error.to_string(), + action, + ) +} + +const fn exit_code(status: ReportStatus) -> u8 { + match status { + ReportStatus::Complete => 0, + ReportStatus::DomainRefusal => 1, + ReportStatus::UsageError => 2, + ReportStatus::OperationalFailure => 3, + } +} + +fn report_scope(scope: Scope) -> ReportScope { + match scope { + Scope::Server => ReportScope::Server, + Scope::Database => ReportScope::Database, + } +} + +fn report_needs(needs: Needs) -> ReportNeeds { + match needs { + Needs::CreateRole => ReportNeeds::CreateRole, + Needs::CreateDb => ReportNeeds::CreateDb, + Needs::DatabaseOwner => ReportNeeds::DatabaseOwner, + Needs::Superuser => ReportNeeds::Superuser, + } +} + +fn report_outcome(outcome: StatementOutcome) -> ReportOutcome { + match outcome { + StatementOutcome::Created => ReportOutcome::Created, + StatementOutcome::Present => ReportOutcome::Present, + StatementOutcome::Applied => ReportOutcome::Applied, + } +} + +fn outcome_word(outcome: ReportOutcome) -> &'static str { + match outcome { + ReportOutcome::Created => "created", + ReportOutcome::Present => "present", + ReportOutcome::Applied => "applied", + ReportOutcome::NotRun => "not-run", + } +} + +/// The plan's statements with the outcome of each, `not-run` when no +/// executor outcome is given. +fn report_statements(plan: &Plan, outcome: Option<&Outcome>) -> Vec { + plan.statements() + .iter() + .enumerate() + .map(|(index, statement)| ReportStatement { + step: statement.step.to_owned(), + scope: report_scope(statement.scope), + needs: report_needs(statement.needs), + outcome: outcome + .and_then(|outcome| outcome.statements.get(index)) + .map_or(ReportOutcome::NotRun, |(_, outcome)| { + report_outcome(*outcome) + }), + sql: statement.printable.clone(), + }) + .collect() +} + +/// Writes the finished report and returns the exit code. +struct Output<'a> { + format: OutputFormat, + version: &'static str, + stdout: &'a mut dyn Write, + stderr: &'a mut dyn Write, +} + +impl Output<'_> { + /// Last resort when the streams themselves fail: the exit code carries it. + fn write_failed(&mut self, ok: bool) -> u8 { + if ok { + 0 + } else { + let _ = writeln!(self.stderr, "provision could not write its output"); + 3 + } + } + + fn json(&mut self, report: &PlatformCliDatabaseProvisionReport) -> bool { + let Ok(value) = serde_json::to_value(report) else { + return false; + }; + let Ok(envelope) = registry_cli_report::Report::new(&value, self.version) else { + return false; + }; + serde_json::to_writer_pretty(&mut *self.stdout, &envelope).is_ok() + && writeln!(self.stdout).is_ok() + } + + /// A refusal: the JSON report on stdout, or the diagnostics on stderr. + fn refusal(&mut self, report: &PlatformCliDatabaseProvisionReport) -> u8 { + let written = match self.format { + OutputFormat::Json => self.json(report), + OutputFormat::Text => report + .diagnostics + .iter() + .all(|diagnostic| write!(self.stderr, "{}", diagnostic.render_human()).is_ok()), + }; + let exit = exit_code(report.status); + match self.write_failed(written) { + 0 => exit, + failed => failed, + } + } +} + +fn run_with( + tool: &'static str, + version: &'static str, + args: &ProvisionArgs, + load: impl FnOnce(&Path) -> Result>, + backend: Backend<'_>, + stdout: &mut dyn Write, + stderr: &mut dyn Write, +) -> u8 { + let mut output = Output { + format: args.format, + version, + stdout, + stderr, + }; + let mut report = PlatformCliDatabaseProvisionReport { + ok: false, + command: "provision".to_owned(), + status: ReportStatus::DomainRefusal, + api_version: REPORT_API_VERSION.to_owned(), + kind: REPORT_KIND.to_owned(), + version: version.to_owned(), + product: None, + executed: false, + role_mode: None, + database: None, + migration_role: None, + runtime_role: None, + statements: Vec::new(), + diagnostics: Vec::new(), + }; + let refused = |report: &mut PlatformCliDatabaseProvisionReport, refusal: Refusal| { + report.status = refusal.status; + report.diagnostics = vec![*refusal.diagnostic]; + }; + + let input = match load(&args.runtime_config) { + Ok(input) => input, + Err(diagnostic) => { + refused( + &mut report, + Refusal { + status: ReportStatus::DomainRefusal, + diagnostic, + }, + ); + return output.refusal(&report); + } + }; + report.product = Some(input.product.product.to_owned()); + let (Some(migration), Some(runtime)) = ( + parse_endpoint(&input.migration_url), + parse_endpoint(&input.runtime_url), + ) else { + refused( + &mut report, + target_invalid( + "the migration and runtime URLs must each be a postgres:// URL with a host, \ + role, password and database, and no host, port, user, password or dbname \ + in the query", + ), + ); + return output.refusal(&report); + }; + report.database = Some(migration.database.clone()); + report.migration_role = Some(migration.user.clone()); + report.runtime_role = Some(runtime.user.clone()); + report.role_mode = Some(if migration.user == runtime.user { + RoleMode::Single + } else { + RoleMode::Split + }); + if let Some(what) = first_difference(&migration, &runtime) { + refused( + &mut report, + target_mismatch(format!( + "the migration and runtime URLs name different {what}s" + )), + ); + return output.refusal(&report); + } + + let target = ProvisionTarget { + database: migration.database.clone(), + migration: RoleCredential::new(migration.user.as_str(), migration.password.as_str()), + runtime: RoleCredential::new(runtime.user.as_str(), runtime.password.as_str()), + }; + let plan = match crate::plan(&input.product, &target) { + Ok(plan) => plan, + Err(error) => { + refused(&mut report, target_invalid(&error.to_string())); + return output.refusal(&report); + } + }; + report.statements = report_statements(&plan, None); + + if args.print_sql { + report.ok = true; + report.status = ReportStatus::Complete; + let written = match args.format { + OutputFormat::Text => output + .stdout + .write_all(render_script(&plan).as_bytes()) + .is_ok(), + OutputFormat::Json => output.json(&report), + }; + return output.write_failed(written); + } + + let admin_url = match read_admin_url(args) { + Ok(url) => url, + Err(refusal) => { + refused(&mut report, refusal); + return output.refusal(&report); + } + }; + let admin = match admin_config(&admin_url, input.ca_pem.as_deref()) { + Ok(admin) => admin, + Err(error) => { + refused(&mut report, admin_refusal(error)); + return output.refusal(&report); + } + }; + let admin_endpoint = Endpoint { + user: admin.user().to_owned(), + password: Zeroizing::new(String::new()), + database: migration.database.clone(), + host: admin.host().to_owned(), + port: admin.port(), + }; + if let Some(what) = first_difference(&admin_endpoint, &migration) { + refused( + &mut report, + target_mismatch(format!( + "the administrator URL names a different {what} than the product URLs" + )), + ); + return output.refusal(&report); + } + + report.executed = true; + match backend(&admin, &plan, &target) { + Ok(outcome) => { + report.ok = true; + report.status = ReportStatus::Complete; + report.statements = report_statements(&plan, Some(&outcome)); + let written = match args.format { + OutputFormat::Json => output.json(&report), + OutputFormat::Text => write_summary(output.stdout, &report, outcome.single_role), + }; + output.write_failed(written) + } + Err(error) => { + refused(&mut report, execution_refusal(tool, &error)); + output.refusal(&report) + } + } +} + +/// One line per statement, then the roles and the database. +fn write_summary( + out: &mut dyn Write, + report: &PlatformCliDatabaseProvisionReport, + single_role: bool, +) -> bool { + let mut text = String::new(); + for statement in &report.statements { + text.push_str(&format!( + "{} {}\n", + outcome_word(statement.outcome), + statement.step + )); + } + let name = |value: &Option| value.clone().unwrap_or_default(); + text.push_str(&format!("database: {}\n", name(&report.database))); + if single_role { + text.push_str(&format!("role: {}\n", name(&report.migration_role))); + text.push_str(registry_platform_activation::SINGLE_ROLE_STATEMENT); + text.push('\n'); + } else { + text.push_str(&format!( + "migration role: {}\n", + name(&report.migration_role) + )); + text.push_str(&format!("runtime role: {}\n", name(&report.runtime_role))); + } + out.write_all(text.as_bytes()).is_ok() +} + +/// Converges the server, then opens a session as each product role. +fn server_backend( + runtime: &tokio::runtime::Runtime, +) -> impl Fn(&AdminConfig, &Plan, &ProvisionTarget) -> Result + '_ { + move |admin, plan, target| { + runtime.block_on(async { + let outcome = execute(admin, plan, Mode::Converge).await?; + verify_logins(admin, target).await?; + Ok(outcome) + }) + } +} + +/// Runs ` provision`. `version` is the tool's own build version and goes +/// into the report. The exit code is 0 on success, 1 for a refusal, 2 for a +/// usage error and 3 for an operational failure. +pub fn run_provision( + tool: &'static str, + version: &'static str, + args: &ProvisionArgs, + load: impl FnOnce(&Path) -> Result>, +) -> ExitCode { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(_) => { + eprintln!("{tool} provision could not start its async runtime"); + return ExitCode::from(3); + } + }; + let exit = run_with( + tool, + version, + args, + load, + &server_backend(&runtime), + &mut std::io::stdout().lock(), + &mut std::io::stderr().lock(), + ); + ExitCode::from(exit) +} + +/// The JSON Schema of [`PlatformCliDatabaseProvisionReport`]. +#[cfg(feature = "schema")] +pub fn report_schema_document() -> Result { + const SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/cli-database-provision-report/cli-database-provision-report.v1alpha1.schema.json"; + let mut settings = schemars::generate::SchemaSettings::draft2020_12(); + settings.contract = schemars::generate::Contract::Serialize; + let schema = settings + .into_generator() + .into_root_schema_for::(); + let mut value = serde_json::to_value(schema)?; + value["$id"] = serde_json::Value::String(SCHEMA_ID.to_owned()); + value["title"] = + serde_json::Value::String("Registry Stack CLI database provision report".to_owned()); + value["properties"]["apiVersion"] = serde_json::json!({"const": REPORT_API_VERSION}); + value["properties"]["kind"] = serde_json::json!({"const": REPORT_KIND}); + value["properties"]["command"] = serde_json::json!({"const": "provision"}); + close_direct_output_structs(&mut value); + state_native_integer_bounds(&mut value); + Ok(serde_json::to_string_pretty(&value)? + "\n") +} + +/// Close the structs this module emits directly and the shared diagnostic DTOs. +#[cfg(feature = "schema")] +fn close_direct_output_structs(schema: &mut serde_json::Value) { + use serde_json::Value; + fn close(node: &mut Value) { + let Value::Object(object) = node else { + return; + }; + if object.get("type") == Some(&Value::String("object".to_owned())) + && object.contains_key("properties") + && !object.contains_key("additionalProperties") + { + object.insert("additionalProperties".to_owned(), Value::Bool(false)); + } + } + if let Some(Value::Object(definitions)) = schema.get_mut("$defs") { + definitions.values_mut().for_each(close); + } + close(schema); +} + +/// State the native range of the `usize` positions a diagnostic's source carries. +#[cfg(feature = "schema")] +fn state_native_integer_bounds(schema: &mut serde_json::Value) { + use serde_json::Value; + match schema { + Value::Object(object) => { + let bounds = object + .get("format") + .and_then(Value::as_str) + .and_then(native_integer_bounds); + if let Some((minimum, maximum)) = bounds { + object.entry("minimum").or_insert(minimum); + object.entry("maximum").or_insert(maximum); + } + object.values_mut().for_each(state_native_integer_bounds); + } + Value::Array(items) => items.iter_mut().for_each(state_native_integer_bounds), + _ => {} + } +} + +#[cfg(feature = "schema")] +fn native_integer_bounds(format: &str) -> Option<(serde_json::Value, serde_json::Value)> { + use serde_json::Value; + match format { + "uint" => Some((Value::from(0), Value::from(usize::MAX as u64))), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{SchemaLayout, Spatial}; + use clap::Parser; + use serde_json::Value; + + const MIGRATION_PASSWORD: &str = "mig-secret-7f3a"; + const RUNTIME_PASSWORD: &str = "run-secret-91bc"; + const ADMIN_PASSWORD: &str = "adm-secret-55de"; + + #[derive(Parser)] + struct Harness { + #[command(flatten)] + args: ProvisionArgs, + } + + fn parse(arguments: &[&str]) -> Result { + Harness::try_parse_from(std::iter::once("tool").chain(arguments.iter().copied())) + .map(|harness| harness.args) + } + + fn input_with(migration: &str, runtime: &str, product: ProductDatabase) -> ProvisionInput { + ProvisionInput { + product, + migration_url: Zeroizing::new(migration.to_owned()), + runtime_url: Zeroizing::new(runtime.to_owned()), + ca_pem: None, + } + } + + fn owned_product() -> ProductDatabase { + ProductDatabase { + product: "casework", + layout: SchemaLayout::Owned(vec!["casework".to_owned()]), + btree_gist: true, + spatial: None, + } + } + + fn split_input() -> ProvisionInput { + input_with( + &format!("postgres://app_migration:{MIGRATION_PASSWORD}@db.example:5432/app?sslmode=verify-full"), + &format!("postgres://app_runtime:{RUNTIME_PASSWORD}@db.example:5432/app?sslmode=verify-full"), + owned_product(), + ) + } + + fn admin_url(host: &str, port: u16) -> String { + format!("postgres://admin:{ADMIN_PASSWORD}@{host}:{port}/postgres?sslmode=verify-full") + } + + struct Run { + exit: u8, + stdout: String, + stderr: String, + } + + impl Run { + fn json(&self) -> Value { + serde_json::from_str(&self.stdout).expect("stdout is one JSON report") + } + fn all_output(&self) -> String { + format!("{}{}", self.stdout, self.stderr) + } + } + + fn execute_run( + arguments: &[&str], + admin_file: Option<&str>, + input: Result>, + backend: Backend<'_>, + ) -> Run { + let directory = tempfile::tempdir().expect("scratch directory"); + let mut full: Vec = arguments.iter().map(|s| (*s).to_owned()).collect(); + if let Some(contents) = admin_file { + let path = directory.path().join("admin.url"); + std::fs::write(&path, contents).expect("admin file"); + full.push("--admin-url-file".to_owned()); + full.push(path.display().to_string()); + } + full.push("--runtime-config".to_owned()); + full.push("runtime.yaml".to_owned()); + let refs: Vec<&str> = full.iter().map(String::as_str).collect(); + let args = parse(&refs).expect("arguments parse"); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1.2.3-test", + &args, + |_| input, + backend, + &mut stdout, + &mut stderr, + ); + Run { + exit, + stdout: String::from_utf8(stdout).expect("utf-8"), + stderr: String::from_utf8(stderr).expect("utf-8"), + } + } + + fn created_everything( + _: &AdminConfig, + plan: &Plan, + _: &ProvisionTarget, + ) -> Result { + Ok(Outcome { + statements: plan + .statements() + .iter() + .map(|statement| { + let outcome = if statement.probe.is_some() { + StatementOutcome::Created + } else { + StatementOutcome::Applied + }; + (statement.step, outcome) + }) + .collect(), + single_role: plan.single_role(), + }) + } + + fn must_not_run( + _: &AdminConfig, + _: &Plan, + _: &ProvisionTarget, + ) -> Result { + panic!("the backend must not run"); + } + + #[cfg(feature = "schema")] + #[test] + fn checked_in_schema_matches_the_owning_type() { + assert_eq!( + report_schema_document().expect("the report schema renders"), + include_str!("../schema/provision-report.schema.json"), + "regenerate with: cargo run --locked -p registry-platform-provision --features schema --example provision-report-schema -- --output crates/registry-platform-provision/schema/provision-report.schema.json" + ); + } + + // ---- flags ---- + + #[test] + fn print_sql_conflicts_with_both_admin_flags() { + for admin in [["--admin-url-file", "a"], ["--admin-url-env", "A"]] { + let error = parse(&["--runtime-config", "r", "--print-sql", admin[0], admin[1]]) + .expect_err("print conflicts with an admin flag"); + assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); + assert_eq!(error.exit_code(), 2); + } + } + + #[test] + fn the_two_admin_flags_conflict() { + let error = parse(&[ + "--runtime-config", + "r", + "--admin-url-file", + "a", + "--admin-url-env", + "A", + ]) + .expect_err("two sources conflict"); + assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); + } + + #[test] + fn executing_needs_exactly_one_admin_flag() { + let error = parse(&["--runtime-config", "r"]).expect_err("no administrator source"); + assert_eq!( + error.kind(), + clap::error::ErrorKind::MissingRequiredArgument + ); + assert_eq!(error.exit_code(), 2); + assert!(parse(&["--runtime-config", "r", "--admin-url-file", "a"]).is_ok()); + assert!(parse(&["--runtime-config", "r", "--admin-url-env", "A"]).is_ok()); + assert!(parse(&["--runtime-config", "r", "--print-sql"]).is_ok()); + } + + #[test] + fn the_runtime_config_is_required_and_the_format_is_text_or_json() { + assert!(parse(&["--print-sql"]).is_err()); + let args = parse(&["--runtime-config", "r", "--print-sql"]).unwrap(); + assert_eq!(args.format, OutputFormat::Text); + let args = parse(&["--runtime-config", "r", "--print-sql", "--format", "json"]).unwrap(); + assert_eq!(args.format, OutputFormat::Json); + assert!(parse(&["--runtime-config", "r", "--print-sql", "--format", "yaml"]).is_err()); + } + + // ---- print mode ---- + + #[test] + fn print_mode_writes_only_the_script_to_stdout() { + let run = execute_run(&["--print-sql"], None, Ok(split_input()), &must_not_run); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert_eq!(run.stderr, ""); + assert!(run.stdout.starts_with("-- "), "{}", run.stdout); + assert!(run.stdout.contains("CREATE ROLE \"app_migration\"")); + assert!(run.stdout.contains("\\password \"app_migration\"")); + assert!(run.stdout.contains("\\password \"app_runtime\"")); + assert!(run.stdout.contains("\\connect \"app\"")); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + "SCRAM-SHA-256$", + "postgres://", + ] { + assert!(!run.stdout.contains(secret), "script holds {secret}"); + } + assert!(!run.stdout.contains("PASSWORD '")); + } + + #[test] + fn print_mode_json_reports_every_statement_as_not_run() { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 0, "{}", run.all_output()); + let report = run.json(); + assert_eq!(report["ok"], true); + assert_eq!(report["command"], "provision"); + assert_eq!(report["status"], "complete"); + assert_eq!(report["apiVersion"], REPORT_API_VERSION); + assert_eq!(report["kind"], REPORT_KIND); + assert_eq!(report["version"], "1.2.3-test"); + assert_eq!(report["product"], "casework"); + assert_eq!(report["executed"], false); + assert_eq!(report["roleMode"], "split"); + assert_eq!(report["database"], "app"); + assert_eq!(report["migrationRole"], "app_migration"); + assert_eq!(report["runtimeRole"], "app_runtime"); + assert_eq!(report["diagnostics"], serde_json::json!([])); + let statements = report["statements"].as_array().unwrap(); + assert!(statements.len() > 5); + for statement in statements { + assert_eq!(statement["outcome"], "not-run"); + assert!(statement["sql"].as_str().is_some_and(|sql| !sql.is_empty())); + } + assert_eq!(statements[0]["step"], "role.migration"); + assert_eq!(statements[0]["scope"], "server"); + assert_eq!(statements[0]["needs"], "createrole"); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + "SCRAM-SHA-256$", + "postgres://", + ] { + assert!(!run.stdout.contains(secret)); + } + } + + #[test] + fn print_mode_marks_the_statement_that_needs_a_superuser() { + let product = ProductDatabase { + product: "breg", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: Some(Spatial { + schema: "registry_spatial_ext".to_owned(), + bbox_role: "app_bbox".to_owned(), + minimum_postgis: (3, 5), + }), + }; + let input = input_with( + &format!("postgres://app_migration:{MIGRATION_PASSWORD}@db.example/app"), + &format!("postgres://app_runtime:{RUNTIME_PASSWORD}@db.example/app"), + product, + ); + let text = execute_run(&["--print-sql"], None, Ok(input), &must_not_run); + assert_eq!(text.exit, 0); + assert!(text.stdout.contains("-- needs a superuser")); + } + + #[test] + fn print_mode_does_not_compare_against_an_administrator() { + let run = execute_run(&["--print-sql"], None, Ok(split_input()), &must_not_run); + assert_eq!(run.exit, 0); + } + + // ---- complete runs ---- + + #[test] + fn a_complete_run_reports_each_outcome() { + let admin = admin_url("db.example", 5432); + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &created_everything, + ); + assert_eq!(run.exit, 0, "{}", run.all_output()); + let report = run.json(); + assert_eq!(report["ok"], true); + assert_eq!(report["status"], "complete"); + assert_eq!(report["executed"], true); + assert_eq!(report["roleMode"], "split"); + let statements = report["statements"].as_array().unwrap(); + assert_eq!(statements[0]["outcome"], "created"); + assert!(statements.iter().any(|s| s["outcome"] == "applied")); + assert!(statements.iter().all(|s| s["outcome"] != "not-run")); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + ADMIN_PASSWORD, + "SCRAM-SHA-256$", + "postgres://", + ] { + assert!(!run.all_output().contains(secret)); + } + } + + #[test] + fn a_complete_text_run_lists_statements_roles_and_database() { + let admin = admin_url("db.example", 5432); + let run = execute_run(&[], Some(&admin), Ok(split_input()), &created_everything); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert_eq!(run.stderr, ""); + assert!( + run.stdout.contains("created role.migration\n"), + "{}", + run.stdout + ); + assert!(run.stdout.contains("applied database.revoke-public\n")); + assert!(run.stdout.contains("database: app\n")); + assert!(run.stdout.contains("migration role: app_migration\n")); + assert!(run.stdout.contains("runtime role: app_runtime\n")); + assert!(!run.stdout.contains("single-role mode")); + } + + #[test] + fn single_role_mode_says_so() { + let input = input_with( + &format!("postgres://app:{MIGRATION_PASSWORD}@db.example/app"), + &format!("postgres://app:{MIGRATION_PASSWORD}@db.example/app"), + owned_product(), + ); + let admin = admin_url("db.example", 5432); + let run = execute_run(&[], Some(&admin), Ok(input), &created_everything); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert!(run + .stdout + .contains(registry_platform_activation::SINGLE_ROLE_STATEMENT)); + let input = input_with( + &format!("postgres://app:{MIGRATION_PASSWORD}@db.example/app"), + &format!("postgres://app:{MIGRATION_PASSWORD}@db.example/app"), + owned_product(), + ); + let json = execute_run( + &["--format", "json"], + Some(&admin), + Ok(input), + &created_everything, + ); + assert_eq!(json.json()["roleMode"], "single"); + } + + // ---- refusals from the executor ---- + + fn refusal_json(error: ProvisionError) -> (u8, Value) { + let admin = admin_url("db.example", 5432); + let backend = move |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| Err(error.clone()); + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.stderr, ""); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + ADMIN_PASSWORD, + "postgres://", + ] { + assert!(!run.stdout.contains(secret)); + } + let report = run.json(); + (run.exit, report) + } + + #[test] + fn each_executor_refusal_has_its_code_status_and_path() { + use ProvisionError as E; + let cases: Vec<(E, &str, &str, u8, Option<&str>)> = vec![ + ( + E::AdminConnectFailed { sqlstate: None }, + "platform.provision.admin-connect-failed", + "operational-failure", + 3, + None, + ), + ( + E::UnsupportedPostgres, + "platform.provision.unsupported-postgres", + "domain-refusal", + 1, + None, + ), + ( + E::StatementNeedsPrivilege { + step: "extension.postgis", + needs: Needs::Superuser, + scope: Scope::Database, + database: "app".to_owned(), + }, + "platform.provision.statement-needs-privilege", + "domain-refusal", + 1, + Some("extension.postgis"), + ), + ( + E::RoleAttributesDiffer { + step: "role.runtime", + role: "app_runtime".to_owned(), + }, + "platform.provision.role-attributes-differ", + "domain-refusal", + 1, + Some("role.runtime"), + ), + ( + E::DatabaseOwnerDiffers { + database: "app".to_owned(), + }, + "platform.provision.database-owner-differs", + "domain-refusal", + 1, + Some("database.create"), + ), + ( + E::SchemaOwnerDiffers { + step: "schema.owned", + schema: "casework".to_owned(), + database: "app".to_owned(), + }, + "platform.provision.schema-owner-differs", + "domain-refusal", + 1, + Some("schema.owned"), + ), + ( + E::ExtensionTooOld { + step: "extension.postgis", + extension: "postgis".to_owned(), + }, + "platform.provision.extension-too-old", + "domain-refusal", + 1, + Some("extension.postgis"), + ), + ( + E::RoleLoginFailed { + role: "app_runtime".to_owned(), + }, + "platform.provision.role-login-failed", + "domain-refusal", + 1, + None, + ), + ( + E::EffectUnconfirmed { + step: "database.create", + }, + "platform.provision.effect-unconfirmed", + "operational-failure", + 3, + Some("database.create"), + ), + ( + E::StatementFailed { + step: "role.migration", + sqlstate: "23505".to_owned(), + }, + "platform.provision.statement-failed", + "operational-failure", + 3, + Some("role.migration"), + ), + ]; + for (error, code, status, exit, step) in cases { + let (actual_exit, report) = refusal_json(error); + assert_eq!(actual_exit, exit, "{code}"); + assert_eq!(report["ok"], false, "{code}"); + assert_eq!(report["status"], status, "{code}"); + assert_eq!(report["executed"], true, "{code}"); + let diagnostics = report["diagnostics"].as_array().unwrap(); + assert_eq!(diagnostics.len(), 1, "{code}"); + let diagnostic = &diagnostics[0]; + assert_eq!(diagnostic["severity"], "error"); + assert_eq!(diagnostic["code"], code); + assert_eq!(diagnostic["path"], step.unwrap_or(""), "{code}"); + assert!(!diagnostic["message"].as_str().unwrap().is_empty()); + assert!(!diagnostic["suggestedAction"].as_str().unwrap().is_empty()); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{code}"); + } + } + } + + #[test] + fn the_privilege_refusal_names_the_statement_and_offers_print_mode() { + let (_, report) = refusal_json(ProvisionError::StatementNeedsPrivilege { + step: "extension.postgis", + needs: Needs::Superuser, + scope: Scope::Database, + database: "app".to_owned(), + }); + let diagnostic = &report["diagnostics"][0]; + assert_eq!( + diagnostic["message"], + "the administrator role cannot run CREATE EXTENSION postgis in database \"app\"; it needs a superuser" + ); + assert_eq!( + diagnostic["suggestedAction"], + "run this statement as a role that has it, or run \"casectl provision --print-sql\" \ + and give the script to the database administrator, then run provision again" + ); + } + + #[test] + fn a_text_refusal_goes_to_stderr_and_stdout_stays_empty() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| { + Err(ProvisionError::UnsupportedPostgres) + }; + let run = execute_run(&[], Some(&admin), Ok(split_input()), &backend); + assert_eq!(run.exit, 1); + assert_eq!(run.stdout, ""); + assert!(run + .stderr + .contains("error[platform.provision.unsupported-postgres]")); + } + + // ---- refusals before any statement ---- + + fn first_diagnostic(run: &Run) -> Value { + run.json()["diagnostics"][0].clone() + } + + #[test] + fn a_bad_administrator_url_is_a_usage_error_that_names_the_rule() { + let run = execute_run( + &["--format", "json"], + Some(&format!( + "http://admin:{ADMIN_PASSWORD}@db.example/postgres" + )), + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 2); + let report = run.json(); + assert_eq!(report["status"], "usage-error"); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.admin-url-invalid" + ); + assert!(!run.stdout.contains(ADMIN_PASSWORD)); + assert!(!run.stdout.contains("http://")); + } + + #[test] + fn plaintext_and_weak_sslmode_in_the_administrator_url_are_refused() { + let run = execute_run( + &["--format", "json"], + Some(&format!( + "postgres://admin:{ADMIN_PASSWORD}@db.example/postgres?sslmode=disable" + )), + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 2); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.admin-url-invalid" + ); + } + + #[test] + fn an_unreadable_administrator_file_is_an_admin_url_refusal() { + let args = parse(&[ + "--runtime-config", + "r", + "--admin-url-file", + "/nonexistent-provision-admin-url", + "--format", + "json", + ]) + .unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + assert_eq!(exit, 2); + let report: Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!( + report["diagnostics"][0]["code"], + "platform.provision.admin-url-invalid" + ); + assert!(!String::from_utf8(stdout).unwrap().contains("nonexistent")); + } + + #[test] + fn an_unset_administrator_variable_is_an_admin_url_refusal_that_names_the_variable() { + let args = parse(&[ + "--runtime-config", + "r", + "--admin-url-env", + "PROVISION_TEST_UNSET_ADMIN_URL", + "--format", + "json", + ]) + .unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + assert_eq!(exit, 2); + let report: Value = serde_json::from_slice(&stdout).unwrap(); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], "platform.provision.admin-url-invalid"); + assert!(diagnostic["message"] + .as_str() + .unwrap() + .contains("PROVISION_TEST_UNSET_ADMIN_URL")); + } + + #[test] + fn an_invalid_ca_bundle_is_refused_with_the_ca_code() { + let mut input = split_input(); + input.ca_pem = Some(b"not a certificate".to_vec()); + let run = execute_run( + &["--format", "json"], + Some(&admin_url("db.example", 5432)), + Ok(input), + &must_not_run, + ); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.admin-ca-invalid" + ); + assert_eq!(run.exit, 1); + assert_eq!(run.json()["status"], "domain-refusal"); + } + + #[test] + fn product_urls_naming_different_targets_are_a_mismatch() { + let variants = [ + ( + "postgres://m:pw1@db-a.example/app", + "postgres://r:pw2@db-b.example/app", + "host", + ), + ( + "postgres://m:pw1@db.example:5432/app", + "postgres://r:pw2@db.example:5433/app", + "port", + ), + ( + "postgres://m:pw1@db.example/app", + "postgres://r:pw2@db.example/other", + "database", + ), + ]; + for (migration, runtime, what) in variants { + let run = execute_run( + &["--format", "json"], + Some(&admin_url("db.example", 5432)), + Ok(input_with(migration, runtime, owned_product())), + &must_not_run, + ); + assert_eq!(run.exit, 1, "{what}"); + let diagnostic = first_diagnostic(&run); + assert_eq!( + diagnostic["code"], "platform.provision.target-mismatch", + "{what}" + ); + assert!(diagnostic["message"].as_str().unwrap().contains(what)); + assert!( + !run.stdout.contains("db-a.example"), + "no host values: {what}" + ); + } + } + + #[test] + fn a_mismatch_between_the_product_urls_is_refused_in_print_mode_too() { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input_with( + "postgres://m:pw1@db.example/app", + "postgres://r:pw2@db.example/other", + owned_product(), + )), + &must_not_run, + ); + assert_eq!(run.exit, 1); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.target-mismatch" + ); + } + + #[test] + fn an_administrator_on_another_host_or_port_is_a_mismatch() { + for (host, port, what) in [ + ("other.example", 5432, "host"), + ("db.example", 6543, "port"), + ] { + let run = execute_run( + &["--format", "json"], + Some(&admin_url(host, port)), + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 1, "{what}"); + let diagnostic = first_diagnostic(&run); + assert_eq!(diagnostic["code"], "platform.provision.target-mismatch"); + assert!(diagnostic["message"] + .as_str() + .unwrap() + .contains("administrator")); + assert!(diagnostic["message"].as_str().unwrap().contains(what)); + } + } + + #[test] + fn the_host_comparison_ignores_case() { + let run = execute_run( + &["--format", "json"], + Some(&admin_url("DB.Example", 5432)), + Ok(split_input()), + &created_everything, + ); + assert_eq!(run.exit, 0, "{}", run.all_output()); + } + + #[test] + fn a_product_url_that_cannot_name_a_target_is_refused_without_echoing_it() { + let cases = [ + "not a url at all, pw", + "mysql://m:pw@db.example/app", + "postgres://m@db.example/app", + "postgres://m:pw@db.example", + "postgres://m:pw@db.example/app?host=other.example", + ]; + for bad in cases { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input_with( + bad, + "postgres://r:pw2@db.example/app", + owned_product(), + )), + &must_not_run, + ); + assert_eq!(run.exit, 2, "{bad}"); + assert_eq!(run.json()["status"], "usage-error"); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.target-invalid" + ); + assert!(!run.stdout.contains("other.example"), "{bad}"); + assert!(!run.stdout.contains(bad), "{bad}"); + } + } + + #[test] + fn one_role_name_with_two_passwords_is_refused() { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input_with( + "postgres://app:pw1@db.example/app", + "postgres://app:pw2@db.example/app", + owned_product(), + )), + &must_not_run, + ); + assert_eq!(run.exit, 2); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.target-invalid" + ); + assert!(!run.stdout.contains("pw1") && !run.stdout.contains("pw2")); + } + + #[test] + fn a_percent_encoded_role_name_and_password_are_decoded() { + let input = input_with( + "postgres://app%5Fmigration:p%40ss@db.example/app", + "postgres://app%5Fruntime:p%40ss2@db.example/app", + owned_product(), + ); + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input), + &must_not_run, + ); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert_eq!(run.json()["migrationRole"], "app_migration"); + } + + #[test] + fn the_loader_diagnostic_is_reported_as_given() { + let diagnostic = Diagnostic::error( + "platform.runtime-config.unsafe-file", + "", + "the runtime file is unsafe", + "Fix the file.", + ); + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Err(Box::new(diagnostic)), + &must_not_run, + ); + assert_eq!(run.exit, 1); + let report = run.json(); + assert_eq!(report["status"], "domain-refusal"); + assert_eq!(report["executed"], false); + assert_eq!(report["statements"], serde_json::json!([])); + assert!(report.get("product").is_none()); + assert_eq!( + report["diagnostics"][0]["code"], + "platform.runtime-config.unsafe-file" + ); + } + + #[test] + fn no_output_ever_holds_a_password_verifier_or_url() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| { + Err(ProvisionError::StatementFailed { + step: "role.migration", + sqlstate: "42710".to_owned(), + }) + }; + for format in [["--format", "text"], ["--format", "json"]] { + let run = execute_run(&format, Some(&admin), Ok(split_input()), &backend); + let output = run.all_output(); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + ADMIN_PASSWORD, + "SCRAM-SHA-256$", + "postgres://", + ] { + assert!(!output.contains(secret), "{format:?} leaked {secret}"); + } + } + } +} + +/// Runs the command against the disposable server named by +/// `PROVISION_TEST_DATABASE_URL` (a superuser, over TLS) and its CA file in +/// `PROVISION_TEST_DATABASE_CA`. A missing variable fails the test. +#[cfg(all(test, feature = "postgres-test"))] +mod postgres_tests { + use super::*; + use crate::SchemaLayout; + use serde_json::Value; + + fn required(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("the postgres-test feature needs {name}")) + } + + fn random_hex(bytes: usize) -> String { + let mut buffer = vec![0_u8; bytes]; + getrandom::fill(&mut buffer).expect("random bytes"); + buffer.iter().map(|byte| format!("{byte:02x}")).collect() + } + + /// Drops what the test created, even when an assertion failed. + struct Cleanup { + admin: AdminConfig, + database: String, + roles: Vec, + } + + impl Drop for Cleanup { + fn drop(&mut self) { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("cleanup runtime"); + runtime.block_on(async { + let session = self.admin.connect(None).await.expect("cleanup session"); + session + .client + .batch_execute(&format!( + "DROP DATABASE IF EXISTS \"{}\" WITH (FORCE)", + self.database + )) + .await + .expect("drop database"); + for role in &self.roles { + session + .client + .batch_execute(&format!("DROP ROLE IF EXISTS \"{role}\"")) + .await + .expect("drop role"); + } + }); + } + } + + fn run_command( + arguments: &[&str], + admin_file: &Path, + input: ProvisionInput, + backend: Backend<'_>, + ) -> (u8, String, String) { + let admin_file = admin_file.display().to_string(); + let mut full = vec![ + "--runtime-config", + "runtime.yaml", + "--admin-url-file", + admin_file.as_str(), + ]; + full.extend_from_slice(arguments); + let args = { + use clap::Parser; + #[derive(Parser)] + struct Harness { + #[command(flatten)] + args: ProvisionArgs, + } + Harness::try_parse_from(std::iter::once("tool").chain(full)) + .expect("arguments parse") + .args + }; + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1.2.3-test", + &args, + |_| Ok(input), + backend, + &mut stdout, + &mut stderr, + ); + ( + exit, + String::from_utf8(stdout).expect("utf-8"), + String::from_utf8(stderr).expect("utf-8"), + ) + } + + #[test] + fn provision_converges_a_real_server_and_refuses_a_changed_password() { + let admin_url = required("PROVISION_TEST_DATABASE_URL"); + let ca = std::fs::read(required("PROVISION_TEST_DATABASE_CA")).expect("CA file"); + let endpoint = parse_endpoint(&admin_url).expect("administrator URL"); + let suffix = random_hex(6); + let (database, migration, runtime_role) = ( + format!("s3_{suffix}_db"), + format!("s3_{suffix}_mig"), + format!("s3_{suffix}_run"), + ); + let (migration_password, runtime_password) = (random_hex(16), random_hex(16)); + let (host, port) = (endpoint.host.as_str(), endpoint.port); + let input = |runtime_password: &str| ProvisionInput { + product: ProductDatabase { + product: "casework", + layout: SchemaLayout::Owned(vec!["casework".to_owned()]), + btree_gist: true, + spatial: None, + }, + migration_url: Zeroizing::new(format!( + "postgres://{migration}:{migration_password}@{host}:{port}/{database}" + )), + runtime_url: Zeroizing::new(format!( + "postgres://{runtime_role}:{runtime_password}@{host}:{port}/{database}" + )), + ca_pem: Some(ca.clone()), + }; + let _cleanup = Cleanup { + admin: admin_config(&admin_url, Some(&ca)).expect("administrator config"), + database: database.clone(), + roles: vec![migration.clone(), runtime_role.clone()], + }; + let directory = tempfile::tempdir().expect("scratch directory"); + let admin_file = directory.path().join("admin.url"); + std::fs::write(&admin_file, &admin_url).expect("admin file"); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + let backend = server_backend(&runtime); + + let (exit, stdout, stderr) = run_command( + &["--format", "json"], + &admin_file, + input(&runtime_password), + &backend, + ); + assert_eq!(exit, 0, "{stdout}{stderr}"); + let first: Value = serde_json::from_str(&stdout).expect("JSON report"); + let outcome = |report: &Value, step: &str| { + report["statements"] + .as_array() + .expect("statements") + .iter() + .find(|statement| statement["step"] == step) + .map(|statement| statement["outcome"].clone()) + }; + assert_eq!(outcome(&first, "role.migration"), Some("created".into())); + assert_eq!(outcome(&first, "database.create"), Some("created".into())); + assert_eq!(outcome(&first, "schema.owned"), Some("created".into())); + assert_eq!(first["executed"], true); + + let (exit, stdout, stderr) = run_command( + &["--format", "json"], + &admin_file, + input(&runtime_password), + &backend, + ); + assert_eq!(exit, 0, "{stdout}{stderr}"); + let second: Value = serde_json::from_str(&stdout).expect("JSON report"); + assert_eq!(outcome(&second, "role.migration"), Some("present".into())); + assert_eq!(outcome(&second, "database.create"), Some("present".into())); + assert_eq!(outcome(&second, "schema.owned"), Some("present".into())); + for secret in [ + migration_password.as_str(), + runtime_password.as_str(), + "postgres://", + ] { + assert!(!stdout.contains(secret), "the report leaked a secret"); + } + + let (exit, stdout, _) = run_command( + &["--format", "json"], + &admin_file, + input(&random_hex(16)), + &backend, + ); + assert_eq!(exit, 1, "{stdout}"); + let refused: Value = serde_json::from_str(&stdout).expect("JSON report"); + assert_eq!( + refused["diagnostics"][0]["code"], + "platform.provision.role-login-failed" + ); + + let (exit, stdout, stderr) = + run_command(&[], &admin_file, input(&runtime_password), &backend); + assert_eq!(exit, 0, "{stdout}{stderr}"); + assert!(stdout.contains("present role.migration\n"), "{stdout}"); + } +} diff --git a/crates/registry-platform-provision/src/lib.rs b/crates/registry-platform-provision/src/lib.rs index 404ad8d7aa..55b035b9aa 100644 --- a/crates/registry-platform-provision/src/lib.rs +++ b/crates/registry-platform-provision/src/lib.rs @@ -15,6 +15,8 @@ //! report. [`verify_logins`] then opens a session as each product role. mod admin; +#[cfg(feature = "cli")] +pub mod cli; mod execute; mod plan; pub mod sql; @@ -26,3 +28,6 @@ pub use plan::{ plan, render_script, verify_server_version, Needs, Plan, PlanError, Probe, ProductDatabase, ProvisionTarget, RoleCredential, SchemaLayout, Scope, Spatial, Statement, UnsupportedPostgres, }; + +#[cfg(feature = "cli")] +pub use cli::{run_provision, ProvisionArgs, ProvisionInput}; diff --git a/products/identifiers/contracts/catalog-source.json b/products/identifiers/contracts/catalog-source.json index 75077af100..03b64b6ba3 100644 --- a/products/identifiers/contracts/catalog-source.json +++ b/products/identifiers/contracts/catalog-source.json @@ -226,6 +226,14 @@ "compatibilityLine": "v1alpha1", "description": "Product-scoped CLI API connections and project selections." }, + { + "glob": "crates/registry-platform-provision/schema/*.schema.json", + "sourcePath": "crates/registry-platform-provision/src/cli.rs", + "owner": "platform", + "status": "active", + "compatibilityLine": "v1alpha1", + "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions." + }, { "glob": "products/platform/generated/mcp-runtime/*.schema.json", "sourcePath": "crates/registry-mcp/src/schema.rs", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 4c0d117756..a71fa93ff5 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -6069,6 +6069,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/platform/cli-database-provision-report/cli-database-provision-report.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "platform", + "title": "Registry Stack CLI database provision report", + "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions.", + "source": { + "path": "crates/registry-platform-provision/src/cli.rs", + "sha256": "76bb9ff03c5acfde5c92823721ded6f3587b5185fef95cd4c80c159bbc04be69" + }, + "artifact": { + "path": "crates/registry-platform-provision/schema/provision-report.schema.json", + "sha256": "6b3a5f1f63ac5bc66ce1d84142cb4004f62cb47e130c57685cdc2fc5d1ec6d15", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/platform/identity-deployment/identity-deployment.v1.schema.json", "kind": "schema", diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 4bdb1360fd..783bbe344d 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -3646,6 +3646,37 @@ formats: conformance: none securityMembers: [] restrictingMembers: [] + - id: platform/cli-database-provision-report + product: platform + title: Shared CLI database provision report + files: [] + syntax: json + audience: generated + stability: unpromised + current: + apiVersion: id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1 + kind: PlatformCliDatabaseProvisionReport + checkedBy: + file: crates/registry-platform-provision/src/cli.rs + symbol: REPORT_API_VERSION + target: + apiVersion: id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1 + kind: PlatformCliDatabaseProvisionReport + schema: + path: crates/registry-platform-provision/schema/provision-report.schema.json + id: https://id.registrystack.org/schemas/platform/cli-database-provision-report/cli-database-provision-report.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-platform-provision --features schema --example provision-report-schema -- --output crates/registry-platform-provision/schema/provision-report.schema.json + driftCheck: crates/registry-platform-provision/src/cli.rs + reader: none + emittedBy: + file: crates/registry-platform-provision/src/cli.rs + symbol: run_provision + check: none + example: crates/registry-platform-provision/example/provision-report.json + conformance: none + securityMembers: [] + restrictingMembers: [] - id: platform/task-connection product: platform title: Task-grant operator connection file From c618a782ca2e87a161dd298bb0335d5478a73f06 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:20:48 +0100 Subject: [PATCH 006/136] feat(platform): name every failed check and bound the refusal log Products refuse requests for many reasons and log them in different ways, some without a bound. registry-platform-authcommon now holds the closed set of failed checks and, behind the refusal-recorder feature, a recorder that counts each refusal by check and writes at most five lines per check per minute, naming the check and nothing a caller sent. The OIDC error type maps itself onto that set. Signed-off-by: Jeremi Joslin --- Cargo.lock | 4 + .../registry-platform-authcommon/Cargo.toml | 9 + .../registry-platform-authcommon/src/lib.rs | 9 + .../src/refusal.rs | 570 ++++++++++++++++++ crates/registry-platform-oidc/Cargo.toml | 1 + .../registry-platform-oidc/src/diagnostics.rs | 102 ++++ 6 files changed, 695 insertions(+) create mode 100644 crates/registry-platform-authcommon/src/refusal.rs diff --git a/Cargo.lock b/Cargo.lock index 7dfada62c1..ba605272e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7801,12 +7801,15 @@ dependencies = [ "futures", "proptest", "registry-platform-crypto", + "registry-platform-metrics", "serde", "serde_json", "sha2 0.11.1", "subtle", "tempfile", "thiserror 2.0.21", + "tracing", + "tracing-subscriber", "ulid", "zeroize", ] @@ -8016,6 +8019,7 @@ dependencies = [ "base64 0.23.1", "chrono", "jsonwebtoken", + "registry-platform-authcommon", "registry-platform-config", "registry-platform-crypto", "registry-platform-httputil", diff --git a/crates/registry-platform-authcommon/Cargo.toml b/crates/registry-platform-authcommon/Cargo.toml index 77de1d9064..de3c74dd53 100644 --- a/crates/registry-platform-authcommon/Cargo.toml +++ b/crates/registry-platform-authcommon/Cargo.toml @@ -10,18 +10,27 @@ publish = false [lints] workspace = true +[features] +# The refusal recorder: the counter, the bounded log line and `record_refusal!`. +# Off by default so client crates that reach this crate through +# `registry-platform-httputil` do not gain the metrics crate. +refusal-recorder = ["dep:registry-platform-metrics", "dep:tracing"] + [dependencies] base64.workspace = true futures.workspace = true registry-platform-crypto.workspace = true +registry-platform-metrics = { workspace = true, optional = true } serde.workspace = true serde_json.workspace = true sha2.workspace = true subtle.workspace = true thiserror.workspace = true +tracing = { workspace = true, optional = true } ulid.workspace = true zeroize.workspace = true [dev-dependencies] proptest.workspace = true tempfile.workspace = true +tracing-subscriber.workspace = true diff --git a/crates/registry-platform-authcommon/src/lib.rs b/crates/registry-platform-authcommon/src/lib.rs index 825f367bad..7624bda2c1 100644 --- a/crates/registry-platform-authcommon/src/lib.rs +++ b/crates/registry-platform-authcommon/src/lib.rs @@ -2,6 +2,15 @@ //! provider. pub mod client_assertion; +pub mod refusal; + +pub use refusal::FailedCheck; +#[cfg(feature = "refusal-recorder")] +pub use refusal::{ + RefusalLine, RefusalNote, RefusalRecorder, REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, +}; +#[cfg(feature = "refusal-recorder")] +pub use tracing as __tracing; use std::env; use std::fs; diff --git a/crates/registry-platform-authcommon/src/refusal.rs b/crates/registry-platform-authcommon/src/refusal.rs new file mode 100644 index 0000000000..012661cf64 --- /dev/null +++ b/crates/registry-platform-authcommon/src/refusal.rs @@ -0,0 +1,570 @@ +//! The closed set of checks a request can fail, and the recorder that counts +//! and logs a refusal by its check. +//! +//! The check is operator-side only. It is never written to a response body. + +/// The check a request failed. Closed. Operator-side only: never written to a +/// response. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FailedCheck { + /// No credential, or not the scheme the route takes. + CredentialMissing, + /// Credential header repeated or unreadable, or the credential is not in the expected shape. + CredentialMalformed, + /// Signing algorithm not allowed. + TokenAlgorithm, + /// Token type not allowed. + TokenType, + /// Key id missing, too long or unknown. + TokenKey, + /// Signature does not verify. + TokenSignature, + /// Issuer is not the configured one. + TokenIssuer, + /// Audience does not include this service. + TokenAudience, + /// Expired, not yet valid, or time claims unusable. + TokenTime, + /// Client not on the verifier's allow list, or the matched client is unusable. + TokenClient, + /// An exchanged token whose assertion issuer is not allowed or not declared. + TokenAssertionIssuer, + /// A required identity claim is missing or malformed (principal, subject, issuer, expiry). + TokenClaims, + /// Actor kind claim missing, malformed, or not the kind the route or profile takes. + ActorKind, + /// A delegated actor is present where none is allowed, or is not the trusted one. + Delegation, + /// The token is sender-constrained and the service does not accept that. + SenderConstraint, + /// The verifier could not reach or use its key source. + KeySourceUnavailable, + /// A static secret, API key, Basic pair or path token does not match. + SharedSecret, + /// A single-use code or token is unknown, expired, already used or locked out. + OneTimeCredential, + /// A signed delivery or provider callback has a missing, malformed, unsupported or wrong signature. + DeliverySignature, + /// A signed delivery time is outside the receiver's window. + DeliveryFreshness, + /// A signed delivery's source, type, schema, route or target is not what the receiver expects. + DeliveryBinding, + /// The request's host or origin is not accepted. + HostOrigin, + /// A required scope is missing. + Scope, + /// No access profile, policy or authority entry admits this caller on this surface. + AccessProfile, + /// The profile or resource does not admit this requester client. + RequesterClient, + /// The declared purpose is missing or not admitted. + Purpose, + /// The caller's profile or policy does not allow this operation, action, workflow, template or record type. + Operation, + /// The request asks for fields or a response format beyond what the caller's profile discloses. + Disclosure, + /// The subject selector is not one the caller's grant or authority covers. + SubjectSelector, + /// The caller pinned a configuration revision that is not the deployed one. + RevisionPin, + /// The acquisition channel is not open to the resolved profile. + AcquisitionChannel, + /// The source or target authority refused the access. + SourceAuthority, + /// The caller already acted in a role that excludes this one. + SeparationOfDuties, + /// The operation needs a task grant and none was presented. + TaskGrantMissing, + /// The task grant is partial or malformed. + TaskGrantClaims, + /// The task grant has expired. + TaskGrantExpired, + /// The task grant is bound to another client, audience, principal, issuer or task. + TaskGrantBinding, + /// The task grant does not cover this service, location, action or operation. + TaskGrantScope, + /// The task grant has more lifetime, or more lifetime left, than the receiver accepts. + TaskGrantLifetime, + /// The status authority says the grant is inactive, or its source is not listed. + TaskGrantStatus, + /// The target row is outside the caller's row boundary. + RowBoundary, + /// The target exists and belongs to another caller. + Ownership, + /// The target is absent or not visible to the caller, and the product does not tell which. + Visibility, + /// A BReg Action guard refused. Operator-side only, so an answer never tells a guard from a boundary. + ActionGuard, + /// An identity-keyed or route-keyed request budget is spent. + RateLimit, +} + +impl FailedCheck { + /// Every member, in declaration order. + pub const ALL: [Self; 45] = [ + Self::CredentialMissing, + Self::CredentialMalformed, + Self::TokenAlgorithm, + Self::TokenType, + Self::TokenKey, + Self::TokenSignature, + Self::TokenIssuer, + Self::TokenAudience, + Self::TokenTime, + Self::TokenClient, + Self::TokenAssertionIssuer, + Self::TokenClaims, + Self::ActorKind, + Self::Delegation, + Self::SenderConstraint, + Self::KeySourceUnavailable, + Self::SharedSecret, + Self::OneTimeCredential, + Self::DeliverySignature, + Self::DeliveryFreshness, + Self::DeliveryBinding, + Self::HostOrigin, + Self::Scope, + Self::AccessProfile, + Self::RequesterClient, + Self::Purpose, + Self::Operation, + Self::Disclosure, + Self::SubjectSelector, + Self::RevisionPin, + Self::AcquisitionChannel, + Self::SourceAuthority, + Self::SeparationOfDuties, + Self::TaskGrantMissing, + Self::TaskGrantClaims, + Self::TaskGrantExpired, + Self::TaskGrantBinding, + Self::TaskGrantScope, + Self::TaskGrantLifetime, + Self::TaskGrantStatus, + Self::RowBoundary, + Self::Ownership, + Self::Visibility, + Self::ActionGuard, + Self::RateLimit, + ]; + + /// The number of members. + pub const COUNT: usize = Self::ALL.len(); + + /// Stable kebab-case label for the counter and the log line. + pub const fn as_str(self) -> &'static str { + match self { + Self::CredentialMissing => "credential-missing", + Self::CredentialMalformed => "credential-malformed", + Self::TokenAlgorithm => "token-algorithm", + Self::TokenType => "token-type", + Self::TokenKey => "token-key", + Self::TokenSignature => "token-signature", + Self::TokenIssuer => "token-issuer", + Self::TokenAudience => "token-audience", + Self::TokenTime => "token-time", + Self::TokenClient => "token-client", + Self::TokenAssertionIssuer => "token-assertion-issuer", + Self::TokenClaims => "token-claims", + Self::ActorKind => "actor-kind", + Self::Delegation => "delegation", + Self::SenderConstraint => "sender-constraint", + Self::KeySourceUnavailable => "key-source-unavailable", + Self::SharedSecret => "shared-secret", + Self::OneTimeCredential => "one-time-credential", + Self::DeliverySignature => "delivery-signature", + Self::DeliveryFreshness => "delivery-freshness", + Self::DeliveryBinding => "delivery-binding", + Self::HostOrigin => "host-origin", + Self::Scope => "scope", + Self::AccessProfile => "access-profile", + Self::RequesterClient => "requester-client", + Self::Purpose => "purpose", + Self::Operation => "operation", + Self::Disclosure => "disclosure", + Self::SubjectSelector => "subject-selector", + Self::RevisionPin => "revision-pin", + Self::AcquisitionChannel => "acquisition-channel", + Self::SourceAuthority => "source-authority", + Self::SeparationOfDuties => "separation-of-duties", + Self::TaskGrantMissing => "task-grant-missing", + Self::TaskGrantClaims => "task-grant-claims", + Self::TaskGrantExpired => "task-grant-expired", + Self::TaskGrantBinding => "task-grant-binding", + Self::TaskGrantScope => "task-grant-scope", + Self::TaskGrantLifetime => "task-grant-lifetime", + Self::TaskGrantStatus => "task-grant-status", + Self::RowBoundary => "row-boundary", + Self::Ownership => "ownership", + Self::Visibility => "visibility", + Self::ActionGuard => "action-guard", + Self::RateLimit => "rate-limit", + } + } +} + +#[cfg(feature = "refusal-recorder")] +pub use recorder::{ + RefusalLine, RefusalNote, RefusalRecorder, REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, +}; + +#[cfg(feature = "refusal-recorder")] +mod recorder { + use std::sync::{Mutex, PoisonError}; + use std::time::{Duration, Instant}; + + use registry_platform_metrics::{CounterVec, LabelSpace, MetricsError}; + + use super::FailedCheck; + + /// The length of one log window for one check. + pub const REFUSAL_LOG_WINDOW: Duration = Duration::from_secs(60); + /// The most lines one check may write in one window. + pub const REFUSAL_LOG_LINES_PER_WINDOW: u32 = 5; + + /// What the refusal answer carries to the recording layer, in the response + /// extensions. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct RefusalNote { + pub check: FailedCheck, + pub remedy: Option<&'static str>, + } + + impl RefusalNote { + pub const fn new(check: FailedCheck) -> Self { + Self { + check, + remedy: None, + } + } + + /// Attach a fixed operator hint. It is code-defined text, never a + /// caller value. + #[must_use] + pub const fn with_remedy(self, remedy: &'static str) -> Self { + Self { + remedy: Some(remedy), + ..self + } + } + } + + /// One admitted log line. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct RefusalLine { + pub failed_check: &'static str, + /// Refusals of this check counted but not logged since the last line. + pub suppressed: u64, + } + + #[derive(Clone, Copy, Default)] + pub(super) struct Slot { + window_start: Option, + written: u32, + suppressed: u64, + } + + /// Counts refusals by check and admits a bounded number of log lines. + /// + /// State is one counter family and a fixed array of slots, one per + /// [`FailedCheck`]. Nothing is keyed by a value a caller sends. + pub struct RefusalRecorder { + counter: CounterVec, + pub(super) slots: Mutex<[Slot; FailedCheck::COUNT]>, + } + + impl RefusalRecorder { + /// `product` is the metric prefix, for example "breg" or + /// "evidence_oid4vci". + pub fn new(product: &'static str) -> Result { + let labels: Vec<[&str; 1]> = FailedCheck::ALL + .iter() + .map(|check| [check.as_str()]) + .collect(); + let declared: Vec<&[&str]> = labels.iter().map(<[&str; 1]>::as_slice).collect(); + Ok(Self { + counter: CounterVec::new( + format!("{product}_request_refusals_total"), + "Requests refused, by the check that failed.", + LabelSpace::closed_zero_filled(&["check"], &declared)?, + )?, + slots: Mutex::new([Slot::default(); FailedCheck::COUNT]), + }) + } + + /// Count the refusal. Returns the line to write when the limiter + /// admits one. + #[must_use] + pub fn record(&self, check: FailedCheck) -> Option { + self.record_at(check, Instant::now()) + } + + pub(super) fn record_at(&self, check: FailedCheck, now: Instant) -> Option { + let label = check.as_str(); + let counted = self.counter.inc(&[label]); + // The slot state is plain counters, so a poisoned lock is safe to reuse. + let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner); + let slot = &mut slots[check as usize]; + if counted.is_err() { + // Labels come from the closed enum, so this is a defect. It is + // reported once per window, not swallowed. + if slot + .window_start + .is_none_or(|start| now.saturating_duration_since(start) >= REFUSAL_LOG_WINDOW) + { + tracing::error!( + failed_check = label, + "a refusal was rejected by its closed label space" + ); + } + } + let expired = slot + .window_start + .is_none_or(|start| now.saturating_duration_since(start) >= REFUSAL_LOG_WINDOW); + if expired { + let suppressed = slot.suppressed; + *slot = Slot { + window_start: Some(now), + written: 1, + suppressed: 0, + }; + return Some(RefusalLine { + failed_check: label, + suppressed, + }); + } + if slot.written < REFUSAL_LOG_LINES_PER_WINDOW { + slot.written += 1; + return Some(RefusalLine { + failed_check: label, + suppressed: 0, + }); + } + slot.suppressed = slot.suppressed.saturating_add(1); + None + } + + /// For the product's exposition. + pub fn counter(&self) -> &CounterVec { + &self.counter + } + } + + /// Count a refusal and write the admitted line at the call site's own + /// tracing target. The line names the check and nothing a caller sent. + #[macro_export] + macro_rules! record_refusal { + ($recorder:expr, $note:expr $(, trace_id = $trace_id:expr)?) => {{ + let note: $crate::RefusalNote = $note; + if let Some(line) = $recorder.record(note.check) { + match note.remedy { + Some(remedy) => $crate::__tracing::info!( + decision = "refused", + failed_check = line.failed_check, + suppressed = line.suppressed, + remedy + $(, trace_id = %$trace_id)?, + "request refused" + ), + None => $crate::__tracing::info!( + decision = "refused", + failed_check = line.failed_check, + suppressed = line.suppressed + $(, trace_id = %$trace_id)?, + "request refused" + ), + } + } + }}; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_set_is_closed_unique_and_in_declaration_order() { + assert_eq!(FailedCheck::ALL.len(), 45); + assert_eq!(FailedCheck::COUNT, 45); + let mut seen = std::collections::HashSet::new(); + for (index, check) in FailedCheck::ALL.iter().enumerate() { + assert_eq!(*check as usize, index); + let label = check.as_str(); + assert!(seen.insert(label), "duplicate label {label}"); + assert!( + !label.is_empty() + && !label.starts_with('-') + && !label.ends_with('-') + && !label.contains("--") + && label.bytes().all(|b| b.is_ascii_lowercase() || b == b'-'), + "label {label} is not kebab-case" + ); + } + } +} + +#[cfg(all(test, feature = "refusal-recorder"))] +mod recorder_tests { + use super::*; + use std::sync::{Arc, Mutex}; + use std::time::{Duration, Instant}; + + use crate::record_refusal; + use registry_platform_metrics::Exposition; + + #[test] + fn a_new_recorder_exposes_every_check_at_zero() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let mut out = Exposition::new(); + recorder.counter().write(&mut out).unwrap(); + let text = out.finish(); + assert!(text.contains("# TYPE breg_request_refusals_total counter")); + for check in FailedCheck::ALL { + let line = format!( + "breg_request_refusals_total{{check=\"{}\"}} 0", + check.as_str() + ); + assert!(text.contains(&line), "missing {line}"); + } + assert_eq!( + text.lines().filter(|l| l.starts_with("breg_")).count(), + FailedCheck::COUNT + ); + } + + #[test] + fn record_counts_the_right_series() { + let recorder = RefusalRecorder::new("scheduling").unwrap(); + let _ = recorder.record(FailedCheck::Scope); + let _ = recorder.record(FailedCheck::Scope); + let _ = recorder.record(FailedCheck::TokenSignature); + assert_eq!(recorder.counter().get(&["scope"]), Some(2)); + assert_eq!(recorder.counter().get(&["token-signature"]), Some(1)); + assert_eq!(recorder.counter().get(&["purpose"]), Some(0)); + assert_eq!(recorder.counter().refused(), 0); + } + + #[test] + fn a_flood_writes_five_lines_then_reports_the_rest() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let start = Instant::now(); + let mut lines = Vec::new(); + for _ in 0..10_000 { + if let Some(line) = recorder.record_at(FailedCheck::TokenSignature, start) { + lines.push(line); + } + } + assert_eq!(lines.len(), 5); + assert!(lines.iter().all(|l| l.suppressed == 0)); + assert_eq!(lines[0].failed_check, "token-signature"); + assert_eq!(recorder.counter().get(&["token-signature"]), Some(10_000)); + let next = recorder + .record_at(FailedCheck::TokenSignature, start + REFUSAL_LOG_WINDOW) + .expect("the next window admits a line"); + assert_eq!(next.suppressed, 9_995); + let after = recorder + .record_at(FailedCheck::TokenSignature, start + REFUSAL_LOG_WINDOW) + .expect("the new window admits more lines"); + assert_eq!(after.suppressed, 0); + } + + #[test] + fn members_do_not_share_a_budget() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let now = Instant::now(); + for _ in 0..1_000 { + let _ = recorder.record_at(FailedCheck::TokenSignature, now); + } + for _ in 0..5 { + assert!(recorder.record_at(FailedCheck::Scope, now).is_some()); + } + assert!(recorder.record_at(FailedCheck::Scope, now).is_none()); + } + + #[test] + fn a_poisoned_lock_still_counts_and_logs() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _guard = recorder.slots.lock().unwrap(); + panic!("poison the lock"); + })); + assert!(poisoned.is_err()); + assert!(recorder.record(FailedCheck::Scope).is_some()); + assert_eq!(recorder.counter().get(&["scope"]), Some(1)); + } + + #[derive(Clone, Default)] + struct Capture(Arc>>); + + impl std::io::Write for Capture { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture { + type Writer = Capture; + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } + } + + fn captured(run: impl FnOnce()) -> String { + let capture = Capture::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(capture.clone()) + .with_ansi(false) + .finish(); + tracing::subscriber::with_default(subscriber, run); + let bytes = capture.0.lock().unwrap().clone(); + String::from_utf8(bytes).unwrap() + } + + #[test] + fn the_macro_writes_one_fixed_line_with_the_member_only() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let canary = String::from("canary-token-value-7f3a"); + let output = captured(|| { + // The caller-supplied string is in scope but is not an argument. + let note = RefusalNote::new(FailedCheck::TokenAudience); + let _unused = &canary; + record_refusal!(recorder, note); + }); + assert_eq!(output.lines().count(), 1, "{output}"); + assert!(output.contains("request refused")); + assert!(output.contains("decision=\"refused\"")); + assert!(output.contains("failed_check=\"token-audience\"")); + assert!(output.contains("suppressed=0")); + assert!(!output.contains("remedy")); + assert!(!output.contains("canary")); + } + + #[test] + fn the_macro_carries_a_remedy_and_a_trace_id_when_given() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let output = captured(|| { + let note = RefusalNote::new(FailedCheck::Scope).with_remedy("check readsScope"); + record_refusal!(recorder, note, trace_id = "01TRACE"); + }); + assert!(output.contains("remedy=\"check readsScope\""), "{output}"); + assert!(output.contains("trace_id=01TRACE"), "{output}"); + } + + #[test] + fn the_macro_is_bounded() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let output = captured(|| { + for _ in 0..100 { + record_refusal!(recorder, RefusalNote::new(FailedCheck::Scope)); + } + }); + assert_eq!(output.lines().count(), 5); + let _ = Duration::ZERO; + } +} diff --git a/crates/registry-platform-oidc/Cargo.toml b/crates/registry-platform-oidc/Cargo.toml index d1cba5fa5d..d5e3dadc83 100644 --- a/crates/registry-platform-oidc/Cargo.toml +++ b/crates/registry-platform-oidc/Cargo.toml @@ -17,6 +17,7 @@ schema = ["dep:schemars"] [dependencies] base64.workspace = true jsonwebtoken.workspace = true +registry-platform-authcommon.workspace = true registry-platform-crypto = { workspace = true } registry-platform-httputil = { workspace = true } registry-platform-config.workspace = true diff --git a/crates/registry-platform-oidc/src/diagnostics.rs b/crates/registry-platform-oidc/src/diagnostics.rs index 3641df2af1..840de87f99 100644 --- a/crates/registry-platform-oidc/src/diagnostics.rs +++ b/crates/registry-platform-oidc/src/diagnostics.rs @@ -3,6 +3,8 @@ use std::sync::{Mutex, PoisonError}; use std::time::{Duration, Instant}; +use registry_platform_authcommon::FailedCheck; + use crate::OidcError; /// Fixed verification stages suitable for operational logs. @@ -73,6 +75,45 @@ impl OidcError { } } +impl OidcError { + /// The check a verification failure maps to. Never format the underlying + /// error to diagnose a public authentication failure. + pub fn failed_check(&self) -> FailedCheck { + match self { + Self::MalformedToken | Self::InvalidToken => FailedCheck::CredentialMalformed, + Self::AlgorithmNotAllowed => FailedCheck::TokenAlgorithm, + Self::TokenTypeNotAllowed => FailedCheck::TokenType, + Self::MissingKid | Self::KidTooLong | Self::UnknownKid => FailedCheck::TokenKey, + Self::SignatureInvalid => FailedCheck::TokenSignature, + Self::IssuerMismatch { .. } => FailedCheck::TokenIssuer, + Self::AudienceMismatch => FailedCheck::TokenAudience, + Self::TokenExpired | Self::TokenNotYetValid | Self::InvalidTimeClaims => { + FailedCheck::TokenTime + } + Self::ClientNotAllowed => FailedCheck::TokenClient, + Self::AssertionIssuerNotAllowed => FailedCheck::TokenAssertionIssuer, + Self::Transport(_) + | Self::BoundedRead(_) + | Self::FetchUrl(_) + | Self::HttpStatus(_) + | Self::InvalidUrl + | Self::Parse + | Self::InvalidJwk + | Self::EmptyKeySet + | Self::StaticKeySet(_) + | Self::MissingIssuer + | Self::ConflictingEndpointConfiguration + | Self::InsecureHttpRequiresOptIn + | Self::EndpointRefused { .. } => FailedCheck::KeySourceUnavailable, + } + } + + /// True when the verifier could not reach or use its key source. + pub fn is_key_source_unavailable(&self) -> bool { + self.failed_check() == FailedCheck::KeySourceUnavailable + } +} + /// Log one value-free refusal at the call site's own tracing target, at most /// once per stage per minute per verifier. `$message` is a literal naming the /// product; the optional `remedy` is a fixed operator hint. @@ -157,3 +198,64 @@ mod tests { assert!(diagnostics.admit(AuthenticationStage::Header)); } } + +#[cfg(test)] +mod failed_check_tests { + use crate::OidcError; + use registry_platform_authcommon::FailedCheck; + + #[test] + fn issuer_mismatch_maps_without_the_issuers() { + let error = OidcError::IssuerMismatch { + expected: "canary-expected-issuer".into(), + actual: "canary-actual-issuer".into(), + }; + let check = error.failed_check(); + assert_eq!(check, FailedCheck::TokenIssuer); + assert!(!format!("{check:?}{}", check.as_str()).contains("canary")); + } + + #[test] + fn key_source_failures_are_unavailable() { + assert!(OidcError::EmptyKeySet.is_key_source_unavailable()); + assert!(OidcError::InvalidUrl.is_key_source_unavailable()); + assert!(!OidcError::SignatureInvalid.is_key_source_unavailable()); + } + + #[test] + fn every_simple_variant_maps_to_its_member() { + let table = [ + (OidcError::MalformedToken, FailedCheck::CredentialMalformed), + (OidcError::InvalidToken, FailedCheck::CredentialMalformed), + (OidcError::AlgorithmNotAllowed, FailedCheck::TokenAlgorithm), + (OidcError::TokenTypeNotAllowed, FailedCheck::TokenType), + (OidcError::MissingKid, FailedCheck::TokenKey), + (OidcError::KidTooLong, FailedCheck::TokenKey), + (OidcError::UnknownKid, FailedCheck::TokenKey), + (OidcError::SignatureInvalid, FailedCheck::TokenSignature), + (OidcError::AudienceMismatch, FailedCheck::TokenAudience), + (OidcError::TokenExpired, FailedCheck::TokenTime), + (OidcError::TokenNotYetValid, FailedCheck::TokenTime), + (OidcError::InvalidTimeClaims, FailedCheck::TokenTime), + (OidcError::ClientNotAllowed, FailedCheck::TokenClient), + ( + OidcError::AssertionIssuerNotAllowed, + FailedCheck::TokenAssertionIssuer, + ), + (OidcError::Parse, FailedCheck::KeySourceUnavailable), + (OidcError::InvalidJwk, FailedCheck::KeySourceUnavailable), + (OidcError::MissingIssuer, FailedCheck::KeySourceUnavailable), + ( + OidcError::ConflictingEndpointConfiguration, + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::InsecureHttpRequiresOptIn, + FailedCheck::KeySourceUnavailable, + ), + ]; + for (error, expected) in table { + assert_eq!(error.failed_check(), expected, "{error:?}"); + } + } +} From 14a1e1b9d1b1c05b09e3ede4cf7e993509b13951 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:20:49 +0100 Subject: [PATCH 007/136] feat(platform): add a shared block that derives allowed clients from the package Messaging and Documents ask operators to repeat, in the runtime file, the client list the reviewed package already names. The PackageClients block takes from-package to admit exactly the package's requester clients, an explicit list that must include every one of them, or unrestricted, which each runtime decides on. A resolved list is never empty. Signed-off-by: Jeremi Joslin --- crates/registry-platform-config/src/blocks.rs | 229 ++++++++++++++++++ .../src/blocks_tests.rs | 136 +++++++++++ crates/registry-platform-config/src/lib.rs | 15 +- crates/registry-platform-config/src/schema.rs | 6 +- products/platform/CONFIG-CONVENTIONS.md | 4 +- .../runtime-config-blocks.schema.json | 53 ++++ 6 files changed, 433 insertions(+), 10 deletions(-) diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 11139df63e..be9739f581 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -787,6 +787,235 @@ impl OidcClientsConfig { } } +const FROM_PACKAGE: &str = "from-package"; + +/// How `allowedClients` is written where the governed package names the +/// clients (CFG-EMPTY-2): the keyword `from-package`, the keyword +/// `unrestricted`, or a list of at least one client. The member stays +/// required and an empty list is refused. A runtime resolves the value with +/// [`PackageClients::resolve`] before it builds a token verifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum PackageClients { + /// Admit exactly the clients the package's access profiles name. + FromPackage, + /// Admit a token from every client the issuer verifies. A runtime decides + /// whether that is acceptable in production. + Unrestricted, + /// Admit the listed clients, which must cover every package client. + Listed(Vec), +} + +/// The keywords `allowedClients` takes beside a list. +enum PackageClientsKeyword { + FromPackage, + Unrestricted, +} + +fn package_clients_refused() -> E { + registry_platform_yaml::Invalid::expected( + "from-package, unrestricted, or a list of at least one OAuth client", + "Write from-package to admit the package's requester clients, list the OAuth clients whose access tokens are admitted, or write unrestricted to admit every client the issuer verifies.", + ) + .into_error() +} + +impl<'de> Deserialize<'de> for PackageClientsKeyword { + fn deserialize>(deserializer: D) -> Result { + match String::deserialize(deserializer)?.as_str() { + FROM_PACKAGE => Ok(Self::FromPackage), + UNRESTRICTED => Ok(Self::Unrestricted), + _ => Err(package_clients_refused()), + } + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for PackageClientsKeyword { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + "PackageClientsKeyword".into() + } + + fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({"type": "string", "enum": [FROM_PACKAGE, UNRESTRICTED]}) + } +} + +/// The authored shape of [`PackageClients`], so the schema and the reader +/// agree on the two forms. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "schema", schemars(untagged))] +enum OidcPackageAllowedClients { + /// A keyword. + Keyword(PackageClientsKeyword), + /// Admit a token only from a listed client. + Listed(ListedClients), +} + +registry_platform_yaml::shape_union!(OidcPackageAllowedClients { scalar => Keyword, list => Listed }); + +impl<'de> Deserialize<'de> for PackageClients { + fn deserialize>(deserializer: D) -> Result { + Ok( + match OidcPackageAllowedClients::deserialize(deserializer)? { + OidcPackageAllowedClients::Keyword(PackageClientsKeyword::FromPackage) => { + Self::FromPackage + } + OidcPackageAllowedClients::Keyword(PackageClientsKeyword::Unrestricted) => { + Self::Unrestricted + } + OidcPackageAllowedClients::Listed(ListedClients(clients)) => Self::Listed(clients), + }, + ) + } +} + +impl Serialize for PackageClients { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::FromPackage => serializer.serialize_str(FROM_PACKAGE), + Self::Unrestricted => serializer.serialize_str(UNRESTRICTED), + Self::Listed(clients) => clients.serialize(serializer), + } + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for PackageClients { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + "OidcPackageAllowedClients".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + OidcPackageAllowedClients::json_schema(generator) + } +} + +/// The OAuth clients a runtime admits access tokens for when the governed +/// package names its requester clients, and the assertion authorities each +/// client may exchange a subject token from, written under +/// `authentication.oidc` beside the issuer. Runtimes whose package does not +/// name clients keep [`OidcClientsConfig`]. +// A product's `authentication.oidc` block embeds this with +// `#[serde(flatten)]`, as it does `OidcClientsConfig`. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(feature = "schema", schemars(deny_unknown_fields))] +pub struct OidcPackageClientsConfig { + /// The OAuth clients whose access tokens are admitted: `from-package` for + /// the package's requester clients, `unrestricted` for every client the + /// issuer verifies, or a list of at least one distinct client that covers + /// the package's requester clients. + pub allowed_clients: PackageClients, + /// Assertion authorities each client may exchange a subject token from, + /// with the meaning and bounds of `OidcClientsConfig::assertion_issuers`. + #[serde( + default, + skip_serializing_if = "BTreeMap::is_empty", + deserialize_with = "non_empty_assertion_issuers" + )] + #[cfg_attr(feature = "schema", schemars(schema_with = "assertion_issuers_schema"))] + pub assertion_issuers: BTreeMap>, +} + +impl OidcPackageClientsConfig { + /// The bounds of [`OidcClientsConfig::check`] on `assertionIssuers`. + pub fn check(&self, field: &str) -> Result<(), ConfigBlockError> { + OidcClientsConfig { + allowed_clients: Vec::new(), + assertion_issuers: self.assertion_issuers.clone(), + } + .check(field) + } +} + +/// A non-empty, sorted list of the clients a token verifier admits. It is the +/// only value a runtime passes to a verifier built from [`PackageClients`], so +/// an unresolved keyword cannot reach it as the empty list, which a verifier +/// reads as "every client". +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AdmittedClients(Vec); + +impl AdmittedClients { + /// The sorted, de-duplicated clients, or `None` when there are none. + #[must_use] + pub fn new(clients: Vec) -> Option { + let clients: BTreeSet = clients.into_iter().collect(); + if clients.is_empty() { + None + } else { + Some(Self(clients.into_iter().collect())) + } + } + + #[must_use] + pub fn as_slice(&self) -> &[String] { + &self.0 + } + + #[must_use] + pub fn into_vec(self) -> Vec { + self.0 + } +} + +/// Why [`PackageClients::resolve`] produced no admitted clients. Client +/// identifiers are not secrets. +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +pub enum PackageClientsError { + /// `allowedClients` is `unrestricted`, which this resolution never turns + /// into a list. + #[error("allowedClients is unrestricted and admits no resolved list of clients")] + Unrestricted, + /// The resolved list has no client: the package names none, or the list + /// is empty. + #[error("allowedClients resolves to no client")] + Empty, + /// The explicit list leaves out a client the package names. + #[error("allowedClients does not list the package client {0}")] + Missing(String), +} + +impl PackageClients { + /// The clients to admit, given the requester clients of every access + /// profile of the loaded package. `FromPackage` is the sorted union of + /// `package_clients`. `Listed` is returned when it covers every package + /// client, and refused naming the first missing one otherwise. Extra + /// clients in a list stay admitted. `Unrestricted` and an empty result are + /// errors: the runtime decides what `Unrestricted` means for it. + pub fn resolve( + &self, + package_clients: &[String], + ) -> Result { + match self { + Self::Unrestricted => Err(PackageClientsError::Unrestricted), + Self::FromPackage => { + AdmittedClients::new(package_clients.to_vec()).ok_or(PackageClientsError::Empty) + } + Self::Listed(listed) => { + let admitted = + AdmittedClients::new(listed.clone()).ok_or(PackageClientsError::Empty)?; + let missing = package_clients + .iter() + .filter(|client| !admitted.0.contains(client)) + .min(); + match missing { + Some(client) => Err(PackageClientsError::Missing(client.clone())), + None => Ok(admitted), + } + } + } + } +} + /// The package a runtime serves: `root` is the absolute package directory, /// and `expectedDigest`, when set, pins the package digest the runtime must /// find there. The package digest is the digest of the package's diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 9f000454c8..d41d6eb0fa 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -1202,3 +1202,139 @@ fn url_hook_destinations_are_keyed_by_local_identifiers_and_bounded() { ); } } + +fn package_clients(yaml: &str) -> OidcPackageClientsConfig { + read_block(yaml).expect("package clients parse") +} + +fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() +} + +#[test] +fn from_package_keyword_parses() { + let block = package_clients("allowedClients: from-package"); + assert_eq!(block.allowed_clients, PackageClients::FromPackage); + assert_eq!( + serde_json::to_value(&block).expect("serialize"), + serde_json::json!({"allowedClients": "from-package"}) + ); +} + +#[test] +fn unrestricted_parses() { + let block = package_clients("allowedClients: unrestricted"); + assert_eq!(block.allowed_clients, PackageClients::Unrestricted); + assert_eq!( + serde_json::to_value(&block).expect("serialize"), + serde_json::json!({"allowedClients": "unrestricted"}) + ); +} + +#[test] +fn list_parses() { + let block = package_clients( + "allowedClients: [portal, kiosk]\nassertionIssuers: {portal: [https://assert.example.test]}", + ); + assert_eq!( + block.allowed_clients, + PackageClients::Listed(strings(&["portal", "kiosk"])) + ); + assert_eq!( + block.assertion_issuers["portal"], + ["https://assert.example.test"] + ); + block.check("authentication.oidc").expect("within bounds"); + assert_eq!( + serde_json::to_value(&block).expect("serialize"), + serde_json::json!({ + "allowedClients": ["portal", "kiosk"], + "assertionIssuers": {"portal": ["https://assert.example.test"]}, + }) + ); +} + +#[test] +fn empty_list_is_refused() { + let report = read_block::("allowedClients: []") + .expect_err("an empty list is refused"); + assert_eq!(report.diagnostics()[0].path, "/allowedClients"); +} + +#[test] +fn unknown_keyword_is_refused() { + for refused in [ + "allowedClients: portal", + "allowedClients: From-Package", + "allowedClients: from_package", + "allowedClients: 7", + ] { + let report = read_block::(refused).expect_err(refused); + assert_eq!(report.diagnostics()[0].path, "/allowedClients", "{refused}"); + } +} + +#[test] +fn absent_member_is_refused() { + let report = read_block::("{}").expect_err("omission is refused"); + assert!( + report.diagnostics()[0].message.contains("allowedClients"), + "{:?}", + report.diagnostics() + ); +} + +#[test] +fn a_repeated_listed_client_is_refused() { + let report = read_block::("allowedClients: [portal, portal]") + .expect_err("repeat refused"); + assert_eq!(report.diagnostics()[0].path, "/allowedClients/1"); +} + +#[test] +fn resolve_from_package_returns_the_sorted_union() { + let admitted = PackageClients::FromPackage + .resolve(&strings(&["c3", "c1", "c2", "c3", "c1"])) + .expect("resolves"); + assert_eq!(admitted.as_slice(), ["c1", "c2", "c3"]); +} + +#[test] +fn resolve_never_returns_an_empty_list() { + assert_eq!( + PackageClients::FromPackage + .resolve(&[]) + .expect_err("empty package"), + PackageClientsError::Empty + ); + assert_eq!( + PackageClients::Unrestricted + .resolve(&strings(&["c1"])) + .expect_err("unrestricted"), + PackageClientsError::Unrestricted + ); + assert_eq!( + PackageClients::Listed(Vec::new()) + .resolve(&strings(&["c1"])) + .expect_err("an unparsed empty list"), + PackageClientsError::Empty + ); + assert!(AdmittedClients::new(Vec::new()).is_none()); +} + +#[test] +fn resolve_listed_missing_a_package_client_names_the_client() { + let listed = PackageClients::Listed(strings(&["c1", "c2"])); + let error = listed + .resolve(&strings(&["c1", "c3", "c4"])) + .expect_err("c3 is missing"); + assert_eq!(error, PackageClientsError::Missing("c3".to_owned())); + assert!(error.to_string().contains("c3")); +} + +#[test] +fn resolve_listed_covering_the_package_keeps_extra_clients() { + let listed = PackageClients::Listed(strings(&["c1", "c2", "extra"])); + let admitted = listed.resolve(&strings(&["c2", "c1"])).expect("covers"); + assert_eq!(admitted.as_slice(), ["c1", "c2", "extra"]); +} diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index 7fc2a9e14f..2069dac1de 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -23,13 +23,14 @@ use sha2::{Digest, Sha256}; #[cfg(feature = "schema")] pub use blocks::url_hook_destinations_schema; pub use blocks::{ - describe_secret_failure, is_sha256_label, url_hook_destinations, AttachmentVerifierConfig, - AttemptTimeoutMilliseconds, AuditKeyConfig, ConfigBlockError, ConfigBlockErrorKind, - DatabaseConfig, EnvironmentSecretProviderConfig, FileSecretProviderConfig, JwksSource, - ListenerBind, ListenerConfig, ListenerNetworkExposure, MetricsListenerConfig, - ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, PackageConfig, PackageDigestMismatch, - PrivateListenerConfig, SecretProvidersConfig, TaskGrantStatusConfig, TlsTermination, - UrlHookDestinationConfig, DEFAULT_ATTEMPT_TIMEOUT_MILLISECONDS, + describe_secret_failure, is_sha256_label, url_hook_destinations, AdmittedClients, + AttachmentVerifierConfig, AttemptTimeoutMilliseconds, AuditKeyConfig, ConfigBlockError, + ConfigBlockErrorKind, DatabaseConfig, EnvironmentSecretProviderConfig, + FileSecretProviderConfig, JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, + MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, + OidcPackageClientsConfig, PackageClients, PackageClientsError, PackageConfig, + PackageDigestMismatch, PrivateListenerConfig, SecretProvidersConfig, TaskGrantStatusConfig, + TlsTermination, UrlHookDestinationConfig, DEFAULT_ATTEMPT_TIMEOUT_MILLISECONDS, DEFAULT_HOOK_ATTEMPT_TIMEOUT_MILLISECONDS, DEFAULT_HOOK_MAXIMUM_ATTEMPTS, DEFAULT_TASK_GRANT_STATUS_PATH, DEFAULT_TASK_GRANT_STATUS_SCOPE, MAX_ASSERTION_ISSUERS_PER_CLIENT, MAX_ASSERTION_ISSUER_BYTES, MAX_ASSERTION_ISSUER_CLIENTS, diff --git a/crates/registry-platform-config/src/schema.rs b/crates/registry-platform-config/src/schema.rs index 4c7c6824f3..784ea825da 100644 --- a/crates/registry-platform-config/src/schema.rs +++ b/crates/registry-platform-config/src/schema.rs @@ -4,8 +4,9 @@ use serde_json::{Map, Value}; use crate::blocks::{ AttachmentVerifierConfig, AuditKeyConfig, DatabaseConfig, JwksSource, ListenerConfig, - MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, PackageConfig, - PrivateListenerConfig, SecretProvidersConfig, TaskGrantStatusConfig, UrlHookDestinationConfig, + MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, + OidcPackageClientsConfig, PackageConfig, PrivateListenerConfig, SecretProvidersConfig, + TaskGrantStatusConfig, UrlHookDestinationConfig, }; /// File name the shared-blocks generator writes. @@ -26,6 +27,7 @@ struct SharedBlocks { audit_key: AuditKeyConfig, oidc_issuer: OidcIssuerConfig, oidc_clients: OidcClientsConfig, + oidc_package_clients: OidcPackageClientsConfig, task_grant_status: TaskGrantStatusConfig, object_storage: ObjectStorageConfig, attachment_verifier: AttachmentVerifierConfig, diff --git a/products/platform/CONFIG-CONVENTIONS.md b/products/platform/CONFIG-CONVENTIONS.md index 489b47dd60..a97583c692 100644 --- a/products/platform/CONFIG-CONVENTIONS.md +++ b/products/platform/CONFIG-CONVENTIONS.md @@ -613,7 +613,9 @@ must decide (`requiredScopes`, `rowBoundaries`, `allowedClients`) is required and takes the sentinel `unrestricted` in place of the list. A member that only narrows further (`requiredPurposes`, `requesterClients`) takes no sentinel: omit it when nothing is added, and the format registry records its omission as -open. An enumerable set (Scheduling +open. A format whose governed package names the clients may also accept the +keyword `from-package` for `allowedClients`, meaning the package's requester +clients. The member stays required and omission stays refused. An enumerable set (Scheduling `channels`) takes no sentinel: its open choice is every member listed, and `[]` is refused. diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index 4f5e35f5f7..3f0bff16bf 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -350,6 +350,59 @@ ], "type": "object" }, + "OidcPackageClientsConfig": { + "additionalProperties": false, + "description": "The OAuth clients a runtime admits access tokens for when the governed\npackage names its requester clients, and the assertion authorities each\nclient may exchange a subject token from, written under\n`authentication.oidc` beside the issuer. Runtimes whose package does not\nname clients keep [`OidcClientsConfig`].", + "properties": { + "allowedClients": { + "anyOf": [ + { + "description": "A keyword.", + "enum": [ + "from-package", + "unrestricted" + ], + "type": "string" + }, + { + "description": "Admit a token only from a listed client.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + } + ], + "description": "The OAuth clients whose access tokens are admitted: `from-package` for\nthe package's requester clients, `unrestricted` for every client the\nissuer verifies, or a list of at least one distinct client that covers\nthe package's requester clients." + }, + "assertionIssuers": { + "additionalProperties": { + "items": { + "maxLength": 512, + "minLength": 1, + "type": "string" + }, + "maxItems": 16, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "description": "Assertion authorities each client may exchange a subject token from,\nwith the meaning and bounds of `OidcClientsConfig::assertion_issuers`.", + "maxProperties": 64, + "minProperties": 1, + "propertyNames": { + "$ref": "#/$defs/ExternalId", + "maxLength": 128 + }, + "type": "object" + } + }, + "required": [ + "allowedClients" + ], + "type": "object" + }, "PackageConfig": { "additionalProperties": false, "description": "The package a runtime serves: `root` is the absolute package directory,\nand `expectedDigest`, when set, pins the package digest the runtime must\nfind there. The package digest is the digest of the package's\n`SHA256SUMS` file; see [`crate::package`].", From 0301c9cfb5591971fca79d5da3bc66b74d43d9b7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:23:45 +0100 Subject: [PATCH 008/136] refactor(rstack-dev): provision development databases through the shared plan rstack dev kept its own role, grant and schema statement builders. It now renders them from registry-platform-provision, the code every product tool will use, so a development database and an operator-provisioned one are made by the same statements. A byte-identity test held the output equal before the local builders were removed. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-rstack-dev/Cargo.toml | 1 + crates/registry-rstack-dev/src/database.rs | 355 +++++++++++++-------- 3 files changed, 217 insertions(+), 140 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ba605272e3..7c55207561 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8371,6 +8371,7 @@ dependencies = [ "registry-platform-config", "registry-platform-crypto", "registry-platform-httputil", + "registry-platform-provision", "registry-platform-yaml", "reqwest 0.12.28", "rustix 1.1.6", diff --git a/crates/registry-rstack-dev/Cargo.toml b/crates/registry-rstack-dev/Cargo.toml index 15fefe903e..82b740baee 100644 --- a/crates/registry-rstack-dev/Cargo.toml +++ b/crates/registry-rstack-dev/Cargo.toml @@ -42,6 +42,7 @@ registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true registry-platform-httputil.workspace = true +registry-platform-provision.workspace = true registry-platform-yaml.workspace = true reqwest.workspace = true rustix.workspace = true diff --git a/crates/registry-rstack-dev/src/database.rs b/crates/registry-rstack-dev/src/database.rs index 1305474153..d7d88e55ab 100644 --- a/crates/registry-rstack-dev/src/database.rs +++ b/crates/registry-rstack-dev/src/database.rs @@ -9,6 +9,10 @@ use std::{ use anyhow::{anyhow, bail, Context, Result}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use registry_platform_provision::{ + plan, sql::quote_identifier, Plan, ProductDatabase, ProvisionTarget, RoleCredential, + SchemaLayout, Scope, Spatial, +}; use rustls::pki_types::{pem::PemObject as _, CertificateDer}; use serde::{Deserialize, Serialize}; use sha2::{Digest as _, Sha256}; @@ -437,13 +441,20 @@ impl Database { let migration_password = random_password()?; let runtime_password = random_password()?; + let batches = Batches::new( + &names, + breg, + requires_postgis, + &migration_password, + &runtime_password, + )?; self.create_role(&names.migration_role, &migration_password)?; self.create_role(&names.runtime_role, &runtime_password)?; - if requires_postgis { - self.create_spatial_bbox_role(&names)?; + if let Some(statement) = &batches.bbox_role { + self.create_spatial_bbox_role(&spatial_bbox_role(&names), statement)?; } - self.create_database(&names)?; - self.configure_database(&names, breg, requires_postgis)?; + self.create_database(&names, &batches)?; + self.configure_database(&names, &batches)?; Ok(DatabaseUrls { runtime: self.product_url(&names.database, &names.runtime_role, &runtime_password)?, @@ -610,7 +621,9 @@ impl Database { let verifier = Zeroizing::new(postgres_protocol::password::scram_sha_256( password.as_bytes(), )); - let statement = Zeroizing::new(create_role_sql(role, &verifier)); + let statement = Zeroizing::new(registry_platform_provision::sql::create_role_sql( + role, &verifier, + )); self.create_owned_role( role, &statement, @@ -618,14 +631,8 @@ impl Database { ) } - fn create_spatial_bbox_role(&mut self, names: &Names) -> Result<()> { - let role = spatial_bbox_role(names); - let statement = create_nologin_role_sql(&role); - self.create_owned_role( - &role, - &statement, - "cannot create the BReg spatial bbox role", - ) + fn create_spatial_bbox_role(&mut self, role: &str, statement: &str) -> Result<()> { + self.create_owned_role(role, statement, "cannot create the BReg spatial bbox role") } fn create_owned_role( @@ -646,13 +653,12 @@ impl Database { created.map_err(anyhow::Error::new).context(context) } - fn create_database(&mut self, names: &Names) -> Result<()> { - let statement = format!( - "CREATE DATABASE {} WITH ALLOW_CONNECTIONS false", - quote_identifier(&names.database) + fn create_database(&mut self, names: &Names, batches: &Batches) -> Result<()> { + let created = self.execute_admin_operation( + &batches.create_database, + "database creation", + OPERATION_TIMEOUT, ); - let created = - self.execute_admin_operation(&statement, "database creation", OPERATION_TIMEOUT); retain_create_acquisition( &mut self.acquisitions, Acquisition::Database(names.database.clone()), @@ -662,13 +668,13 @@ impl Database { .map_err(anyhow::Error::new) .context("cannot create an isolated PostgreSQL database")?; - self.execute_admin(&database_access_sql(names)) + self.execute_admin(&batches.access) .context("cannot restrict the PostgreSQL database to this run's roles") } - fn configure_database(&self, names: &Names, breg: bool, requires_postgis: bool) -> Result<()> { - let statement = database_setup_sql(names, breg); - let postgis = requires_postgis.then(|| postgis_prerequisites_sql(names)); + fn configure_database(&self, names: &Names, batches: &Batches) -> Result<()> { + let statement = &batches.setup; + let postgis = &batches.postgis; let mut target = self.admin_config.clone(); target.dbname(&names.database).ssl_mode(SslMode::Require); @@ -681,14 +687,14 @@ impl Database { let connection_task = tokio::spawn(connection); let executed = tokio::time::timeout(OPERATION_TIMEOUT, async { client - .batch_execute(&statement) + .batch_execute(statement) .await .map_err(|error| { OperationFailure::postgres("database configuration", error) }) .map_err(anyhow::Error::new) .context("cannot configure the provisioned PostgreSQL database")?; - if let Some(postgis) = &postgis { + if let Some(postgis) = postgis { client .batch_execute(postgis) .await @@ -829,6 +835,90 @@ impl Names { } } +/// The statements one database run sends, taken from the shared provisioning +/// plan and grouped as they are executed: the access statements as one batch +/// on the administrator session, the setup statements as one batch inside the +/// new database, and the PostGIS statements as a second batch there. The login +/// roles are created from their password verifiers, which the plan keeps +/// private. +struct Batches { + bbox_role: Option, + create_database: String, + access: String, + setup: String, + postgis: Option, +} + +impl Batches { + fn new( + names: &Names, + breg: bool, + requires_postgis: bool, + migration_password: &str, + runtime_password: &str, + ) -> Result { + let product = ProductDatabase { + product: "rstack-dev", + layout: if breg { + SchemaLayout::Owned( + BREG_SCHEMAS + .iter() + .map(|schema| (*schema).to_owned()) + .collect(), + ) + } else { + SchemaLayout::PublicForMigration + }, + btree_gist: breg, + spatial: requires_postgis.then(|| Spatial { + schema: POSTGIS_SCHEMA.to_owned(), + bbox_role: spatial_bbox_role(names), + minimum_postgis: MIN_POSTGIS, + }), + }; + let target = ProvisionTarget { + database: names.database.clone(), + migration: RoleCredential::new(&names.migration_role, migration_password), + runtime: RoleCredential::new(&names.runtime_role, runtime_password), + }; + let plan = plan(&product, &target).context("cannot plan the PostgreSQL provisioning")?; + Self::from_plan(&plan) + } + + fn from_plan(plan: &Plan) -> Result { + let printable = |wanted: &dyn Fn(&str, Scope) -> bool| { + plan.statements() + .iter() + .filter(|statement| wanted(statement.step, statement.scope)) + .map(|statement| statement.printable.clone()) + .collect::>() + }; + let one = |step: &str| { + let mut found = printable(&|candidate, _| candidate == step); + match (found.pop(), found.is_empty()) { + (Some(statement), true) => Ok(statement), + _ => Err(anyhow!( + "the provisioning plan has no single {step} statement" + )), + } + }; + let postgis = printable(&|step, _| step == "extension.postgis"); + Ok(Self { + bbox_role: printable(&|step, _| step == "role.spatial-bbox").pop(), + create_database: one("database.create")?, + access: printable(&|step, _| { + step.starts_with("database.") && step != "database.create" + }) + .join("; "), + setup: printable(&|step, scope| { + scope == Scope::Database && step != "extension.postgis" + }) + .join("; "), + postgis: postgis.into_iter().next(), + }) + } +} + fn spatial_bbox_role(names: &Names) -> String { spatial_bbox_role_for(&names.runtime_role) } @@ -853,23 +943,6 @@ fn spatial_bbox_role_for(runtime_role: &str) -> String { /// The schema BReg's generated spatial SQL reads PostGIS from. const POSTGIS_SCHEMA: &str = "registry_spatial_ext"; -/// Administrator-run PostGIS setup for one spatial run: the extension in its -/// own schema, usable by both run roles, and the bbox role the migration role -/// may SET. The bbox role itself is created earlier in provisioning. -fn postgis_prerequisites_sql(names: &Names) -> String { - let migration = quote_identifier(&names.migration_role); - let runtime = quote_identifier(&names.runtime_role); - let bbox = quote_identifier(&spatial_bbox_role(names)); - format!( - "CREATE SCHEMA IF NOT EXISTS {POSTGIS_SCHEMA};\n\ - REVOKE ALL ON SCHEMA {POSTGIS_SCHEMA} FROM PUBLIC;\n\ - CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA {POSTGIS_SCHEMA};\n\ - GRANT USAGE ON SCHEMA {POSTGIS_SCHEMA} TO {migration}, {runtime};\n\ - GRANT {bbox} TO {migration} WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ - GRANT USAGE ON SCHEMA {POSTGIS_SCHEMA} TO {bbox};" - ) -} - fn validate_run_id(run_id: &str) -> Result<()> { if run_id.len() == 32 && run_id @@ -890,56 +963,6 @@ fn validate_label(label: &str) -> Result<()> { } } -fn database_access_sql(names: &Names) -> String { - format!( - "REVOKE ALL ON DATABASE {database} FROM PUBLIC; \ - GRANT CONNECT ON DATABASE {database} TO {migration}, {runtime}; \ - ALTER DATABASE {database} ALLOW_CONNECTIONS true", - database = quote_identifier(&names.database), - migration = quote_identifier(&names.migration_role), - runtime = quote_identifier(&names.runtime_role), - ) -} - -fn create_role_sql(role: &str, verifier: &str) -> String { - format!( - "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD {}", - quote_identifier(role), - quote_literal(verifier) - ) -} - -fn create_nologin_role_sql(role: &str) -> String { - format!( - "CREATE ROLE {} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS", - quote_identifier(role) - ) -} - -fn database_setup_sql(names: &Names, breg: bool) -> String { - if breg { - let schemas = BREG_SCHEMAS - .iter() - .map(|schema| { - format!( - "CREATE SCHEMA {schema} AUTHORIZATION {owner}; \ - REVOKE ALL ON SCHEMA {schema} FROM PUBLIC", - schema = quote_identifier(schema), - owner = quote_identifier(&names.migration_role), - ) - }) - .collect::>() - .join("; "); - format!("CREATE EXTENSION btree_gist; {schemas}") - } else { - format!( - "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ - GRANT USAGE, CREATE ON SCHEMA public TO {}", - quote_identifier(&names.migration_role) - ) - } -} - fn admin_config(admin_url: &str) -> Result<(Config, Endpoint)> { let parsed = Url::parse(admin_url) .map_err(|_| anyhow!("the PostgreSQL admin URL is not a parseable URL"))?; @@ -1061,17 +1084,10 @@ pub(super) fn random_password() -> Result> { Ok(Zeroizing::new(URL_SAFE_NO_PAD.encode(bytes.as_ref()))) } -fn quote_identifier(value: &str) -> String { - format!("\"{}\"", value.replace('"', "\"\"")) -} - -fn quote_literal(value: &str) -> String { - format!("'{}'", value.replace('\'', "''")) -} - #[cfg(test)] mod tests { use super::*; + use registry_platform_provision::sql::quote_literal; use std::{future::pending, time::Instant}; const RUN_ID: &str = "0123456789abcdef0123456789abcdef"; @@ -1558,42 +1574,6 @@ mod tests { } } - #[test] - fn database_access_is_closed_to_public_before_connections_are_enabled() { - let names = Names::new(RUN_ID, "casework"); - let sql = database_access_sql(&names); - let revoke = sql.find("REVOKE ALL ON DATABASE").unwrap(); - let grant = sql.find("GRANT CONNECT ON DATABASE").unwrap(); - let enable = sql.find("ALLOW_CONNECTIONS true").unwrap(); - assert!(revoke < grant && grant < enable, "{sql}"); - assert!(sql.contains("e_identifier(&names.migration_role))); - assert!(sql.contains("e_identifier(&names.runtime_role))); - } - - #[test] - fn breg_setup_installs_extension_and_all_owned_schemas() { - let names = Names::new(RUN_ID, "breg"); - let sql = database_setup_sql(&names, true); - assert!(sql.starts_with("CREATE EXTENSION btree_gist;"), "{sql}"); - for schema in BREG_SCHEMAS { - assert!( - sql.contains(&format!( - "CREATE SCHEMA {} AUTHORIZATION {}", - quote_identifier(schema), - quote_identifier(&names.migration_role) - )), - "{sql}" - ); - assert!( - sql.contains(&format!( - "REVOKE ALL ON SCHEMA {} FROM PUBLIC", - quote_identifier(schema) - )), - "{sql}" - ); - } - } - #[test] fn spatial_breg_uses_the_governed_bbox_role_for_its_runtime() { for label in ["breg_test", "breg"] { @@ -1602,7 +1582,9 @@ mod tests { assert_eq!(spatial_bbox_role(&names), expected); assert!(expected.starts_with("breg_bbox_")); assert!(expected.len() <= 63); - let statement = create_nologin_role_sql(&expected); + let batches = + Batches::new(&names, true, true, "migration-secret", "runtime-secret").unwrap(); + let statement = batches.bbox_role.unwrap(); assert_eq!( statement, format!( @@ -1660,10 +1642,100 @@ mod tests { assert!(run_object_names(RUN_ID, "other", false).is_err()); } + /// The statements `rstack dev` issued before it used the shared plan, + /// written out as text. The shared plan must keep rendering exactly this + /// for the same input. + #[test] + fn shared_plan_renders_the_statements_rstack_dev_has_always_issued() { + for (label, breg, postgis) in [ + ("breg", true, false), + ("breg", true, true), + ("casework", false, false), + ("messaging", false, false), + ] { + let names = Names::new(RUN_ID, label); + let batches = + Batches::new(&names, breg, postgis, "migration-secret", "runtime-secret").unwrap(); + let (database, migration, runtime) = ( + quote_identifier(&names.database), + quote_identifier(&names.migration_role), + quote_identifier(&names.runtime_role), + ); + assert_eq!( + batches.create_database, + format!("CREATE DATABASE {database} WITH ALLOW_CONNECTIONS false"), + "{label}" + ); + assert_eq!( + batches.access, + format!( + "REVOKE ALL ON DATABASE {database} FROM PUBLIC; \ + GRANT CONNECT ON DATABASE {database} TO {migration}, {runtime}; \ + ALTER DATABASE {database} ALLOW_CONNECTIONS true" + ), + "{label}" + ); + let expected_setup = if breg { + let schemas = BREG_SCHEMAS + .iter() + .map(|schema| { + format!( + "CREATE SCHEMA \"{schema}\" AUTHORIZATION {migration}; \ + REVOKE ALL ON SCHEMA \"{schema}\" FROM PUBLIC" + ) + }) + .collect::>() + .join("; "); + format!("CREATE EXTENSION btree_gist; {schemas}") + } else { + format!( + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO {migration}" + ) + }; + assert_eq!(batches.setup, expected_setup, "{label}"); + if postgis { + let bbox_role = spatial_bbox_role(&names); + let bbox = quote_identifier(&bbox_role); + assert_eq!( + batches.bbox_role.as_deref(), + Some( + format!( + "CREATE ROLE {bbox} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE \ + NOINHERIT NOBYPASSRLS" + ) + .as_str() + ) + ); + assert_eq!( + batches.postgis.as_deref(), + Some( + format!( + "CREATE SCHEMA IF NOT EXISTS registry_spatial_ext;\n\ + REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC;\n\ + CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA registry_spatial_ext;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO {migration}, {runtime};\n\ + GRANT {bbox} TO {migration} WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO {bbox};" + ) + .as_str() + ) + ); + } else { + assert!( + batches.bbox_role.is_none() && batches.postgis.is_none(), + "{label}" + ); + } + } + } + #[test] fn casework_setup_gives_only_migration_role_public_schema_creation() { let names = Names::new(RUN_ID, "casework"); - let sql = database_setup_sql(&names, false); + let sql = Batches::new(&names, false, false, "migration-secret", "runtime-secret") + .unwrap() + .setup; assert!( sql.starts_with("REVOKE CREATE ON SCHEMA public FROM PUBLIC;"), "{sql}" @@ -1678,7 +1750,9 @@ mod tests { #[test] fn messaging_setup_gives_only_migration_role_public_schema_creation() { let names = Names::new(RUN_ID, "messaging"); - let sql = database_setup_sql(&names, false); + let sql = Batches::new(&names, false, false, "migration-secret", "runtime-secret") + .unwrap() + .setup; assert!( sql.starts_with("REVOKE CREATE ON SCHEMA public FROM PUBLIC;"), "{sql}" @@ -1701,7 +1775,7 @@ mod tests { fn role_statement_carries_a_postgresql_scram_verifier_not_cleartext() { let password = random_password().unwrap(); let verifier = postgres_protocol::password::scram_sha_256(password.as_bytes()); - let sql = create_role_sql("rstack_role", &verifier); + let sql = registry_platform_provision::sql::create_role_sql("rstack_role", &verifier); let expected = format!( "CREATE ROLE \"rstack_role\" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD '{verifier}'" ); @@ -1724,6 +1798,7 @@ mod tests { #[cfg(all(test, feature = "postgres-test"))] mod postgres_tests { use super::*; + use registry_platform_provision::sql::quote_literal; use std::{sync::mpsc, thread}; struct Server { From 5ffc99bc12c797547c0d6be8901e1e11d0433aa1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:29:52 +0100 Subject: [PATCH 009/136] feat(breg): check the static key set with the shared public-key rule BReg kept its own ten-member allow list for a pinned key set and refused any member it did not name, unlike every other product and unlike RFC 7517. It now calls the shared rule: unknown public members such as x5c load, private and symmetric members are refused by name and position, and BReg's own algorithm, use and denied-kid checks still apply. A listener origin uses the shared loopback definition, so an IPv4-mapped loopback literal counts as loopback. Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/runtime_config.rs | 46 +++----- crates/registry-breg/tests/runtime_config.rs | 111 ++++++++++++++++-- docs/site/src/content/docs/security/breg.mdx | 16 ++- .../contracts/security-invariant-matrix.yaml | 2 +- 4 files changed, 129 insertions(+), 46 deletions(-) diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index eed81bd2d0..c48ee1951d 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -20,14 +20,15 @@ use registry_platform_config::{ RuntimeConfigLoader, RuntimeEnvelope, SecretError, SecretReference, SecretResolver, TaskGrantStatusConfig, REMOVED_OIDC_JWKS_SOURCE_KIND, }; -use registry_platform_crypto::{parse_json_strict, PublicJwk, SigningAlgorithm}; +use registry_platform_crypto::{PublicJwk, SigningAlgorithm}; #[cfg(feature = "schema")] use registry_platform_httputil::destination::{ MAX_DESTINATION_ORIGIN_URL_BYTES, MAX_DESTINATION_PRIVATE_CIDRS, MAX_DESTINATION_TARGET_BYTES, }; use registry_platform_oidc::{ - access_token_typ_set, fetch_discovery_for_issuer, AccessTokenAlgorithm, ClaimNames, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + access_token_typ_set, fetch_discovery_for_issuer, public_jwks_document, AccessTokenAlgorithm, + ClaimNames, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, + StaticJwksError, TokenVerifierConfig, }; use registry_platform_yaml::{ lookalike_local_id_pairs, Diagnostic, Report, RetiredApiVersion, Severity, Source, Url, @@ -365,6 +366,8 @@ pub enum RuntimeConfigError { UnsafePackageRoot, #[error("runtime configuration contains an invalid OIDC binding")] InvalidOidc, + #[error("the static OIDC key set was refused: {0}")] + InvalidStaticJwks(StaticJwksError), #[error("the OIDC leeway must be a whole number of seconds from 0 to 300000 milliseconds")] InvalidOidcLeeway, #[error("runtime configuration contains an invalid audit binding")] @@ -435,7 +438,7 @@ impl RuntimeConfigError { Self::InvalidPackage => "breg.runtime.invalid-package", Self::PackageRootUnavailable => "breg.runtime.package-root-unavailable", Self::UnsafePackageRoot => "breg.runtime.unsafe-package-root", - Self::InvalidOidc => "breg.runtime.invalid-oidc", + Self::InvalidOidc | Self::InvalidStaticJwks(_) => "breg.runtime.invalid-oidc", Self::InvalidOidcLeeway => "breg.runtime.invalid-oidc-leeway", Self::InvalidAudit => "breg.runtime.invalid-audit", Self::InvalidCursor => "breg.runtime.invalid-cursor", @@ -477,7 +480,7 @@ impl RuntimeConfigError { Self::PlaintextDatabase => "/database/testOnlyPlaintext", Self::InvalidPackage => "/package", Self::PackageRootUnavailable | Self::UnsafePackageRoot => "/package/root", - Self::InvalidOidc => "/authentication/oidc", + Self::InvalidOidc | Self::InvalidStaticJwks(_) => "/authentication/oidc", Self::InvalidOidcLeeway => "/authentication/oidc/leewayMilliseconds", Self::InvalidAudit => "/audit", Self::InvalidCursor => "/cursor", @@ -549,6 +552,8 @@ impl RuntimeConfigError { Self::InvalidOidc => { "Correct authentication.oidc and authentication.authorityClaims: use an https issuer, loopback http, or set authentication.oidc.allowInsecureHttp: true for a declared non-loopback http issuer; keep values bounded without whitespace, list entries distinct, and claim names non-repeating." } + // The remedy is the cause's own text, which `diagnostics` states. + Self::InvalidStaticJwks(_) => "", Self::InvalidOidcLeeway => { "Set authentication.oidc.leewayMilliseconds to a multiple of 1000 no greater than 300000." } @@ -604,6 +609,7 @@ impl RuntimeConfigError { } let action = match self { Self::InvalidMetricsListener(cause) => cause.remedy(METRICS_NETWORK_EXPOSURE_KEY), + Self::InvalidStaticJwks(cause) => cause.to_string(), other => other.suggested_action().to_owned(), }; let mut diagnostic = Diagnostic::error(self.code(), self.path(), self.to_string(), action); @@ -1838,10 +1844,7 @@ impl PublicOrigin { .host() .trim_start_matches('[') .trim_end_matches(']'); - let loopback = host.eq_ignore_ascii_case("localhost") - || host - .parse::() - .is_ok_and(|address| address.is_loopback()); + let loopback = registry_platform_httputil::loopback::loopback_host(host).is_some(); let scheme_allowed = match uri.scheme_str() { Some("https") => true, Some("http") => loopback, @@ -2421,11 +2424,8 @@ fn validate_static_jwks( allowed_algorithm: AccessTokenAlgorithm, denied_kids: &[String], ) -> Result { - let value = parse_json_strict(bytes).map_err(|_| RuntimeConfigError::InvalidOidc)?; + let value = public_jwks_document(bytes).map_err(RuntimeConfigError::InvalidStaticJwks)?; let object = value.as_object().ok_or(RuntimeConfigError::InvalidOidc)?; - if object.len() != 1 || !object.contains_key("keys") { - return Err(RuntimeConfigError::InvalidOidc); - } let keys = object .get("keys") .and_then(Value::as_array) @@ -2433,9 +2433,8 @@ fn validate_static_jwks( if keys.is_empty() || keys.len() > MAX_LIST_ITEMS { return Err(RuntimeConfigError::InvalidOidc); } - let mut kids = HashSet::new(); for key in keys { - validate_static_jwk(key, allowed_algorithm, denied_kids, &mut kids)?; + validate_static_jwk(key, allowed_algorithm, denied_kids)?; } serde_json::from_value::(value).map_err(|_| RuntimeConfigError::InvalidOidc) } @@ -2444,10 +2443,8 @@ fn validate_static_jwk( value: &Value, allowed_algorithm: AccessTokenAlgorithm, denied_kids: &[String], - kids: &mut HashSet, ) -> Result<()> { let object = value.as_object().ok_or(RuntimeConfigError::InvalidOidc)?; - validate_static_jwk_members(object)?; validate_static_jwk_use(object)?; validate_static_jwk_key_ops(object)?; let kid = object @@ -2455,7 +2452,7 @@ fn validate_static_jwk( .and_then(Value::as_str) .ok_or(RuntimeConfigError::InvalidOidc)?; validate_bounded_list(&[kid.to_owned()])?; - if denied_kids.iter().any(|denied| denied == kid) || !kids.insert(kid.to_owned()) { + if denied_kids.iter().any(|denied| denied == kid) { return Err(RuntimeConfigError::InvalidOidc); } if object.get("alg").and_then(Value::as_str) != Some(allowed_algorithm.jwa_name()) { @@ -2479,19 +2476,6 @@ fn validate_static_jwk( Ok(()) } -fn validate_static_jwk_members(object: &Map) -> Result<()> { - const ALLOWED: &[&str] = &[ - "kty", "kid", "alg", "use", "key_ops", "crv", "x", "y", "n", "e", - ]; - if object - .keys() - .any(|member| !ALLOWED.contains(&member.as_str())) - { - return Err(RuntimeConfigError::InvalidOidc); - } - Ok(()) -} - fn validate_static_jwk_use(object: &Map) -> Result<()> { match object.get("use") { None => Ok(()), diff --git a/crates/registry-breg/tests/runtime_config.rs b/crates/registry-breg/tests/runtime_config.rs index 61417bd3d9..71723b30fe 100644 --- a/crates/registry-breg/tests/runtime_config.rs +++ b/crates/registry-breg/tests/runtime_config.rs @@ -26,6 +26,7 @@ use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::destination::{ DestinationDnsFamily, DestinationSendError, EventDeliveryHeaders, }; +use registry_platform_oidc::StaticJwksError; use serde_json::{json, Value}; const DATABASE_URL_CANARY: &str = @@ -110,6 +111,12 @@ fn public_origin_accepts_only_explicit_web_origins_and_redacts_debug() { ("http://127.0.0.1:8080", "http://127.0.0.1:8080"), ("http://[::1]:8080/", "http://[::1]:8080"), ("http://localhost:8080", "http://localhost:8080"), + ("http://LOCALHOST:8080", "http://LOCALHOST:8080"), + ("http://127.0.0.2:8080", "http://127.0.0.2:8080"), + ( + "http://[::ffff:127.0.0.1]:8080", + "http://[::ffff:127.0.0.1]:8080", + ), ] { let origin = PublicOrigin::parse(input).expect("explicit HTTPS or loopback origin"); assert_eq!(origin.as_str(), expected); @@ -122,6 +129,9 @@ fn public_origin_accepts_only_explicit_web_origins_and_redacts_debug() { "ftp://registry.example", "http://registry.example", "http://127.0.0.1.attacker.example", + "http://localhost.:8080", + "http://app.localhost:8080", + "http://[::ffff:10.0.0.1]:8080", "https://user:secret@registry.example", "https://registry.example/a//b", "https://registry.example/a/../b", @@ -3325,12 +3335,6 @@ async fn static_jwks_validation_refuses_unsafe_documents_value_free() { }; let cases = [ ("top-level-missing", "{}".to_owned(), "EdDSA"), - ( - "top-level-unknown", - serde_json::to_string(&json!({"keys":[valid.clone()],"issuer":"issuer-canary"})) - .expect("JWKS serializes"), - "EdDSA", - ), ("empty-keys", r#"{"keys":[]}"#.to_owned(), "EdDSA"), ( "keys-not-array", @@ -3342,11 +3346,6 @@ async fn static_jwks_validation_refuses_unsafe_documents_value_free() { static_jwks_document(&[with_member(valid.clone(), "d", json!("private-canary"))]), "EdDSA", ), - ( - "unknown-member", - static_jwks_document(&[with_member(valid.clone(), "x5c", json!(["cert-canary"]))]), - "EdDSA", - ), ( "duplicate-json-field", format!( @@ -3462,7 +3461,32 @@ async fn static_jwks_validation_refuses_unsafe_documents_value_free() { .oidc_key_source() .await .expect_err("invalid static JWKS refused"); - assert_eq!(error, RuntimeConfigError::InvalidOidc, "{name}"); + let expected = match name { + "top-level-missing" | "keys-not-array" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::NotAKeySet) + } + "empty-keys" => RuntimeConfigError::InvalidStaticJwks(StaticJwksError::Empty), + "private-member" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::PrivateKeyMember { + key: 0, + member: "d", + }) + } + "duplicate-json-field" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::NotJson) + } + "oct-key" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::SymmetricKey { key: 0 }) + } + "missing-kid" | "empty-kid" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::MissingKeyId { key: 0 }) + } + "duplicate-kid" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::RepeatedKeyId { key: 1 }) + } + _ => RuntimeConfigError::InvalidOidc, + }; + assert_eq!(error, expected, "{name}"); let rendered = format!("{error:?} {error} {config:?}"); for canary in [ "oidc-jwks", @@ -3482,6 +3506,69 @@ async fn static_jwks_validation_refuses_unsafe_documents_value_free() { } } +#[tokio::test] +async fn a_static_key_set_with_unknown_public_members_loads() { + let fixture = RuntimeFixture::new(); + let kid = "static-ed25519"; + let key = static_ed25519_jwk(kid); + let documents = [ + ( + "x5c", + static_jwks_document(&[with_member(key.clone(), "x5c", json!(["cert-canary"]))]), + ), + ( + "ext", + static_jwks_document(&[with_member(key.clone(), "ext", json!(true))]), + ), + ( + "top-level", + serde_json::to_string(&json!({"keys":[key.clone()],"issuer":"issuer-canary"})) + .expect("JWKS serializes"), + ), + ]; + for (name, document) in documents { + fixture.write_secret("oidc-jwks", document.as_bytes()); + let config = parse_runtime_config_with_env( + &runtime_with_static_jwks_ref(&fixture, "secret:file/oidc-jwks"), + env_lookup, + ) + .expect("runtime shell parses"); + let source = config + .oidc_key_source() + .await + .unwrap_or_else(|error| panic!("{name} key set refused: {error}")); + source + .key_for_kid(kid) + .await + .unwrap_or_else(|_| panic!("{name} key set key is selectable by kid")); + } +} + +#[tokio::test] +async fn a_private_member_in_a_static_key_set_is_named_in_the_startup_refusal() { + let fixture = RuntimeFixture::new(); + let document = static_jwks_document(&[with_member( + static_ed25519_jwk("static-ed25519"), + "d", + json!("private-canary"), + )]); + fixture.write_secret("oidc-jwks", document.as_bytes()); + let config = parse_runtime_config_with_env( + &runtime_with_static_jwks_ref(&fixture, "secret:file/oidc-jwks"), + env_lookup, + ) + .expect("runtime shell parses"); + let error = config + .oidc_key_source() + .await + .expect_err("private member refused"); + let rendered = error.render_human(None); + assert!(rendered.contains("breg.runtime.invalid-oidc"), "{rendered}"); + assert!(rendered.contains("/authentication/oidc"), "{rendered}"); + assert!(rendered.contains("private-key member \"d\""), "{rendered}"); + assert!(!rendered.contains("private-canary"), "{rendered}"); +} + #[tokio::test] async fn static_jwks_resolves_once_and_rotates_only_on_reconstruction() { let fixture = RuntimeFixture::new(); diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index c670557581..4763acfe75 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -493,9 +493,21 @@ The residuals refer to these obligations by number. Loopback HTTP is accepted for an issuer; anything else needs `authentication.oidc.allowInsecureHttp: true`, which is logged at startup and reported by `bregctl doctor` (`BREG-RES-17`). - {/* Evidence: crates/registry-breg/src/runtime_config.rs, PlaintextDatabase; + Loopback means an address in `127.0.0.0/8`, `::1`, an IPv4-mapped form of a `127.0.0.0/8` + address, or the exact name `localhost`. + A pinned key set (`authentication.oidc.jwksSource.type: static`) holds public keys only. + BReg refuses a key that carries a private or symmetric member (`d`, `p`, `q`, `dp`, `dq`, `qi`, + `oth`, `k`), a repeated member name, a missing or repeated `kid`, or a key that does not match + `allowedAlgorithm`. + It ignores members it does not name, such as `x5c` or `ext`. + A refusal names the rule and the key's position, never a value. + {/* Evidence: crates/registry-breg/src/runtime_config.rs, PlaintextDatabase, + validate_static_jwks, PublicOrigin::parse; crates/registry-breg/tests/runtime_config.rs, - non_loopback_http_issuer_refusal_names_the_opt_in; + non_loopback_http_issuer_refusal_names_the_opt_in, + static_jwks_validation_refuses_unsafe_documents_value_free, + a_static_key_set_with_unknown_public_members_loads, + public_origin_accepts_only_explicit_web_origins_and_redacts_debug; crates/registry-bregctl/src/doctor.rs, insecure_http_warning. */} 8. Keep the metrics listener private. `metricsListener.bind` must be a loopback or private address; it carries no authentication. diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index 7bf229aa85..ef0cf4cbe4 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -20,7 +20,7 @@ invariants: - {id: BREG-SEC-16, state: enforced, targetWave: W5, threat: A domain fixture gains hidden production behavior through a hard-coded runtime concept., enforcementPoint: self-tested source-neutrality gate over production source and public kernel contracts, refusal: Reject any acceptance-fixture identifier planted in the runtime source or public kernel contract., negativeId: BREG-NEG-16, negativeTest: {path: products/breg/scripts/test_check_source_neutrality.py, name: test_fixture_identifier_in_production_source_is_rejected}} - {id: BREG-SEC-17, state: enforced, targetWave: W3, threat: An encrypted cursor is replayed under a different authorized query context., enforcementPoint: fresh HTTP authorization plus authenticated cursor opening and PostgreSQL ReadPlan binding recomputation, refusal: "Reject before SQL when package, route, operation, profile, principal, purpose, row boundary, projection, filter, sort, temporal instant, page size, or expiry differs.", negativeId: BREG-NEG-17, negativeTest: {path: crates/registry-breg/tests/postgres_read.rs, name: real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced}} - {id: BREG-SEC-18, state: enforced, targetWave: W5, threat: A bulk request bypasses per-item authority or commits a valid prefix after a later item fails., enforcementPoint: configured Batch route and single-transaction mutation coordinator, refusal: "Refuse the complete request before record I/O when its bounds, operation, profile, or mutation mode is invalid; otherwise roll back every item and release nothing when any item or terminal component fails.", negativeId: BREG-NEG-18, negativeTest: {path: crates/registry-breg/tests/postgres_batch.rs, name: real_postgres_batch_is_bounded_authorized_atomic_and_exactly_replayable}} - - {id: BREG-SEC-19, state: enforced, targetWave: W5, threat: "A malformed, private, ambiguous, denied, or wrong-algorithm operator-pinned JWKS selects unintended verification material or leaks key metadata.", enforcementPoint: static JWKS validation before verifier construction in production startup and schema-test execution, refusal: "Reject the complete bounded document unless it is a strict duplicate-free set of valid public keys exactly bound to the configured algorithm, signature use, verification operation, and kid policy.", negativeId: BREG-NEG-19, negativeTest: {path: crates/registry-breg/tests/runtime_config.rs, name: static_jwks_validation_refuses_unsafe_documents_value_free}} + - {id: BREG-SEC-19, state: enforced, targetWave: W5, threat: "A malformed, private, ambiguous, denied, or wrong-algorithm operator-pinned JWKS selects unintended verification material or leaks key metadata.", enforcementPoint: static JWKS validation before verifier construction in production startup and schema-test execution, refusal: "Reject the complete bounded document unless it is a strict duplicate-free set of valid public keys, with no private or symmetric key member, exactly bound to the configured algorithm, signature use, verification operation, and kid policy.", negativeId: BREG-NEG-19, negativeTest: {path: crates/registry-breg/tests/runtime_config.rs, name: static_jwks_validation_refuses_unsafe_documents_value_free}} - {id: BREG-SEC-20, state: enforced, targetWave: W3, threat: "A lookup selector accepts partial, extra, mistyped, caller-supplied claim values, queries unbounded rows, or otherwise becomes an enumeration oracle.", enforcementPoint: compiled selector permission bounded lookup request parser and two-row PostgreSQL limit, refusal: "Require the selector's exact configured field set and origin, query at most two rows, and collapse unknown, ungranted, missing-claim, zero-match, and multiple-match outcomes to one value-free unresolved response without audit cardinality.", negativeId: BREG-NEG-20, negativeTest: {path: crates/registry-breg/tests/http_read_only.rs, name: lookup_body_exactness_origin_types_and_unresolved_equivalence_are_value_free}} - {id: BREG-SEC-21, state: enforced, targetWave: W3, threat: "A relationship traversal inherits direct target rights or widens its configured target projection, filtering, ordering, or count authority.", enforcementPoint: compiled named read-path permission and route-specific query plan, refusal: "Require an independently granted path and enforce only that path's target fields and query capabilities; conceal unknown and ungranted paths identically before record I/O.", negativeId: BREG-NEG-21, negativeTest: {path: crates/registry-breg/tests/http_read_only.rs, name: relationship_route_uses_path_grant_not_direct_target_rights}} - {id: BREG-SEC-22, state: enforced, targetWave: W5, threat: A new profile or relationship grant omits mandatory entity access restrictions., enforcementPoint: compiler access requirements after module composition and before artifact generation, refusal: Reject profiles missing mandatory scopes or row bindings or widening allowed purposes; reject relationship grants whose target or join row requirements cannot be enforced., negativeId: BREG-NEG-22, negativeTest: {path: crates/registry-breg/tests/access_configuration.rs, name: requirements_are_mandatory_not_grants_and_cannot_be_weakened_by_profiles}} From 0a6f6ae180f0bef488beaf70f91c7a5157ee759a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:34:51 +0100 Subject: [PATCH 010/136] test(platform): add the acceptance journey tables and their shared library Three journeys (own provider, rstack dev, promote) say where a reader stops today for each of the sixteen runtimes that load a runtime file, and which milestone removes the stop. The tables hold the product list, the first-hour pass rule, the counted concepts and the ratchet of expected failures, with a static check. The shell library gives every journey script the same options, generated secrets, redaction, container cleanup and ratchet comparison, and its self-test runs against fake docker, curl and cargo commands. Signed-off-by: Jeremi Joslin --- products/platform/journeys/README.md | 89 + products/platform/journeys/concepts.yaml | 96 + .../platform/journeys/expected-failures.yaml | 366 +++ .../journeys/first-hour-pass-rule.yaml | 136 + products/platform/journeys/lib.sh | 2608 +++++++++++++++++ products/platform/journeys/products.yaml | 191 ++ .../platform/journeys/test_journey_tables.py | 280 ++ products/platform/journeys/test_lib.sh | 2056 +++++++++++++ .../test_cargo_runtime_script_contracts.py | 7 +- 9 files changed, 5828 insertions(+), 1 deletion(-) create mode 100644 products/platform/journeys/README.md create mode 100644 products/platform/journeys/concepts.yaml create mode 100644 products/platform/journeys/expected-failures.yaml create mode 100644 products/platform/journeys/first-hour-pass-rule.yaml create mode 100644 products/platform/journeys/lib.sh create mode 100644 products/platform/journeys/products.yaml create mode 100644 products/platform/journeys/test_journey_tables.py create mode 100644 products/platform/journeys/test_lib.sh diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md new file mode 100644 index 0000000000..c8ee203b57 --- /dev/null +++ b/products/platform/journeys/README.md @@ -0,0 +1,89 @@ +# Acceptance journeys + +This folder holds the tables behind three acceptance journeys and a static check +of those tables. A journey walks one product from nothing to a first +authenticated call, or from a development run to a production start, using only +what a reader of the documentation has. The tables say where each journey stops +for each product today and which milestone removes the stop. + +## The three journeys + +| Journey | What it does | Steps | +|---|---|---| +| `own-provider` | Starts a product against an identity provider and a PostgreSQL server the reader already runs. | prepare, issuer, database.provision, database.connect, start, ready, token, call, hook, stop | +| `rstack-dev` | Starts the product with `rstack dev` and uses its own issuer, with no identity provider to set up. | init, plan, start, issuer, token, call, hook, keep, attach, stop | +| `promote` | Takes the files a development journey ended with and starts them as production. | input, start-as-production, refusals, fix, start, call, same-contract | + +The own-provider journey uses Keycloak. The image is the one +`products/breg/scripts/test-issuer-portability.py` pins, and `products.yaml` +repeats it so the test can compare the two. The `rstack dev` journey uses the +issuer the run starts and does not start an identity provider. + +## Files + +| File | Holds | +|---|---| +| `products.yaml` | The product column: the sixteen runtimes that load a runtime file, with their crate, binary, tool, and whether they use PostgreSQL or verify tokens. Ten are primary and six are supporting. A supporting runtime starts beside its parent, so a journey records it as unreached. | +| `first-hour-pass-rule.yaml` | What counts as a pass for a first hour: six hard conditions, ten counters with a threshold for each path, and the model that turns effort into reader time. | +| `concepts.yaml` | The closed list of concepts that counter 6 counts. | +| `expected-failures.yaml` | The ratchet table. Every cell (a journey and a product) is listed once, as an expected failure, as unreached, or as a pass. | +| `test_journey_tables.py` | The static check. | +| `lib.sh` | The shared library every journey script sources: options, binaries, generated secrets and redaction, containers and their cleanup, steps, outcomes and the ratchet comparison. | +| `test_lib.sh` | The library's self-test. It runs against fake `docker`, `curl` and `cargo` commands, so it starts no container and builds nothing: `bash products/platform/journeys/test_lib.sh`. | + +## Reading the ratchet table + +A cell fails at its first failing step with one code. The code has one of these +forms. + +- `journey.needs.`: the only way past the step is something the journeys + forbid. The things are a certificate, a claim mapper, hand-written SQL, an + image build, a signature verifier and a hand-written plan. +- `journey.promote.`, `journey.keep.`, `journey.attach.`: the + step named in the form found nothing to work with, lost the written record or + refused the reader's own setup. +- `http..`: a refused call. The stage is one of the + authentication stages the shared OIDC crate reports. +- `product.`: the diagnostic code a product prints. + +Each row has a `basis`. A `predicted` row was inferred from reading the code. A +journey run replaces it with the code the run saw and sets `observed`. A +harness failure, such as a container that did not start, is never a row. + +A journey run in ratchet mode succeeds when every cell matches the table. A +milestone that fixes a cell deletes the row in the same commit and adds the +cell to `passes`. A fix that is not recorded fails the run, and so does a new +failure that the table does not list. + +## Running the static check + +The check reads these files and a few source files. It starts no container and +builds nothing. It needs PyYAML. + +``` +uv run --no-project --with PyYAML==6.0.2 python3 -m unittest products/platform/journeys/test_journey_tables.py +``` + +It checks that: + +- the product list has sixteen unique rows, each with a crate, binary and tool + that exist in `crates/` +- the `rstackDevPlan` flag matches the products `rstack dev` can plan +- the Keycloak image equals the pin in the portability journey +- the pass rule has the six hard conditions, ten numbered counters with both + thresholds, and the full reader-time model +- the concept list has unique, well-formed entries +- every journey and product cell appears exactly once, every step belongs to its + journey, every code is valid, every failure row names a listed milestone, + and every row records its basis and a reason +- journey scripts, when they exist, call none of `openssl`, `mkcert`, `keytool`, + `psql`, `docker build` or `docker exec`, outside `lib-assists.sh`, and the + Keycloak realm import has no `protocolMappers` + +## Why the journeys are shell and not Python + +Journey scripts start product binaries directly. On macOS a process started +through a protected system launcher, such as `/usr/bin/env` under `uv` or the +system Python, loses the `DYLD_*` variables, and the binary then aborts on a +missing FIPS library. Keeping the journeys in `bash` with direct launches avoids +that. A Python helper that starts a binary would bring the problem back. diff --git a/products/platform/journeys/concepts.yaml b/products/platform/journeys/concepts.yaml new file mode 100644 index 0000000000..b49623a778 --- /dev/null +++ b/products/platform/journeys/concepts.yaml @@ -0,0 +1,96 @@ +# The closed list of concepts the first-hour pass rule counts (counter 6). +# +# A concept is something the reader must type a name for or choose a value for. +# The first 24 entries are the terms the BReg first-hour measurement found in +# the two hand-written files and the prose before the first call (the journey +# and step identifiers, and the run identifier with its time to live, are each +# one entry). The rest are the terms the runtime files of the other products +# add. Each journey step declares the concepts it introduces. A declaration +# outside this list is a defect in the journey, so a new term is added here +# first and in the same change as the step that needs it. + +schema: registry.journey-concepts/v1 + +concepts: + - id: project + meaning: A product's project directory and the files `init` writes. + - id: record-type + meaning: A BReg Record type. + - id: field-classification + meaning: The classification a field carries. + - id: dataset + meaning: A BReg dataset. + - id: access-profile + meaning: An access profile that a caller's token selects. + - id: principal-claim + meaning: The token claim that names the calling principal. + - id: required-scopes + meaning: The scopes a profile requires. + - id: required-purposes + meaning: The purposes a profile requires. + - id: row-boundary + meaning: The rule that limits which rows a caller sees. + - id: development-plan + meaning: The `dev.yaml` plan that `rstack dev` reads. + - id: issuer-name + meaning: The name a plan gives an issuer. + - id: audience + meaning: The audience a token names for the API. + - id: test-person + meaning: A person a development scenario signs in as. + - id: client + meaning: An OAuth client. + - id: grant + meaning: The grant type a client uses. + - id: scopes + meaning: The scopes a client requests. + - id: extra-claims + meaning: Claims a plan adds to a token. + - id: registry-actor-kind + meaning: The `registry_actor_kind` claim. + - id: registry-purpose + meaning: The `registry_purpose` claim. + - id: scenario-file + meaning: The scenario file a plan names. + - id: scenario-journey-and-step-ids + meaning: The journey and step identifiers inside a scenario. + - id: run-id-and-ttl + meaning: The run identifier and its time to live. + - id: header-file + meaning: The file that holds a ready authorisation header. + - id: short-lived-token + meaning: A token with a five minute lifetime. + - id: runtime-file + meaning: The runtime file a product loads at start. + - id: issuer-url + meaning: The issuer URL a product trusts. + - id: jwks-uri + meaning: The key set address a product fetches. + - id: token-type + meaning: The `typ` header value a product accepts. + - id: scope-claim + meaning: The claim a product reads scopes from. + - id: allowed-clients + meaning: The list of clients a product admits. + - id: database-url + meaning: The PostgreSQL address a product connects to. + - id: database-role + meaning: The PostgreSQL role a product connects as. + - id: database-tls + meaning: How a product verifies its PostgreSQL server. + - id: listener-bind + meaning: The address and port a product listens on. + - id: tls-termination + meaning: Where TLS ends for a product's listener. + - id: public-origin + meaning: The origin a product tells callers it has. + - id: secret-file + meaning: A file that holds a secret a runtime file refers to. + - id: package + meaning: A verified package directory a product loads. + - id: hook-destination + meaning: The URL a hook delivers to. + - id: hook-secret + meaning: The secret that signs or authenticates a hook delivery. + - id: posture + meaning: Whether a run declares development or production. diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml new file mode 100644 index 0000000000..34da7e684b --- /dev/null +++ b/products/platform/journeys/expected-failures.yaml @@ -0,0 +1,366 @@ +# The ratchet table of the acceptance journeys: where each journey stops for +# each product on `main`, and which milestone removes the stop. +# +# A cell is one journey and one product. Every cell of the journeys and products +# in this folder appears exactly once, as an expected failure or as unreached, +# or in `passes` once a cell passes. A cell fails at its first failing step with +# one code. In ratchet mode a journey exits 0 when every cell equals this table. +# A cell that fails differently, or no longer fails while still listed, fails +# the run. A milestone that fixes a cell deletes its row in the same commit and +# adds the cell to `passes`. +# +# basis: predicted inferred from reading code. The first journey run on +# `main` replaces it with the code the run observed and sets +# basis: observed. +# basis: observed seen in a journey run against the tree named in `observedOn`. +# +# A harness failure (a container that did not start, an occupied name, a +# timeout) is never a row here. +# +# Code forms: +# journey.needs. the only way past the step is one of the things the +# journeys forbid a reader to do +# journey.promote. a promote step with no input or nothing to refuse +# journey.keep. the keep step lost the written record +# journey.attach. the attach step refused the reader's own setup +# http.. a refused call: the HTTP status and the +# authentication stage in the operator log +# product. the diagnostic code a product prints for a refused +# check or start + +schema: registry.journey-expected-failures/v1 + +journeys: + own-provider: + steps: [prepare, issuer, database.provision, database.connect, start, ready, token, call, hook, stop] + rstack-dev: + steps: [init, plan, start, issuer, token, call, hook, keep, attach, stop] + promote: + steps: [input, start-as-production, refusals, fix, start, call, same-contract] + +# Words the code forms above accept. The journeys' own list is closed so a typo +# cannot pass as a new failure. +journeyCodeSuffixes: + needs: [certificate, claim-mapper, hand-written-sql, image-build, signature-verifier, hand-written-plan] + promote: [no-input, nothing-refused] + keep: [state-lost] + attach: [issuer-refused] +authenticationStages: [header, algorithm, token-type, key, signature, issuer, audience, time, client, scope, profile, unavailable] + +# Milestones of the plan that can remove a row. +milestones: [M1, M2, M3, M4, M5, M6, M7, M8, M9, M10, M11, M12, M13, M14, M15, M16] + +expectedFailures: + - journey: own-provider + product: breg + step: database.provision + code: journey.needs.hand-written-sql + finding: X13 + removedBy: M4 + basis: predicted + reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + - journey: own-provider + product: casework + step: database.provision + code: journey.needs.hand-written-sql + finding: X13 + removedBy: M4 + basis: predicted + reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + - journey: own-provider + product: messaging + step: database.provision + code: journey.needs.hand-written-sql + finding: X13 + removedBy: M4 + basis: predicted + reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + - journey: own-provider + product: scheduling + step: database.provision + code: journey.needs.hand-written-sql + finding: X13 + removedBy: M4 + basis: predicted + reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + - journey: own-provider + product: documents + step: database.provision + code: journey.needs.hand-written-sql + finding: X13 + removedBy: M4 + basis: predicted + reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + - journey: own-provider + product: coordinator + step: database.provision + code: journey.needs.hand-written-sql + finding: X13 + removedBy: M4 + basis: predicted + reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + - journey: own-provider + product: adapter + step: database.provision + code: journey.needs.hand-written-sql + finding: X13 + removedBy: M4 + basis: predicted + reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + - journey: own-provider + product: evidence + step: call + code: http.401.token-type + finding: G3 + removedBy: M7 + basis: predicted + reason: No database. Evidence accepts at+jwt or application/at+jwt only and Keycloak sends typ JWT. + - journey: own-provider + product: render + step: call + code: http.401.token-type + finding: G3 + removedBy: M7 + basis: predicted + reason: Render fixes the token type at at+jwt and Keycloak sends typ JWT. + - journey: rstack-dev + product: scheduling + step: plan + code: product.rstack-dev.plan-unparsed + removedBy: M4 + basis: predicted + reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + - journey: rstack-dev + product: coordinator + step: plan + code: product.rstack-dev.plan-unparsed + removedBy: M4 + basis: predicted + reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + - journey: rstack-dev + product: documents + step: plan + code: product.rstack-dev.plan-unparsed + removedBy: M4 + basis: predicted + reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + - journey: rstack-dev + product: adapter + step: plan + code: product.rstack-dev.plan-unparsed + removedBy: M4 + basis: predicted + reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + - journey: rstack-dev + product: render + step: plan + code: product.rstack-dev.plan-unparsed + removedBy: M4 + basis: predicted + reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + - journey: rstack-dev + product: discovery + step: plan + code: product.rstack-dev.plan-unparsed + removedBy: M4 + basis: predicted + reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + - journey: rstack-dev + product: breg + step: plan + code: journey.needs.hand-written-plan + finding: FH-4 + removedBy: M4 + basis: predicted + reason: bregctl init does not ship dev.yaml or the scenario file. + - journey: rstack-dev + product: casework + step: plan + code: journey.needs.hand-written-plan + removedBy: M4 + basis: predicted + reason: Predicted from the same gap as BReg. What caseworkctl init writes is not yet observed. + - journey: rstack-dev + product: messaging + step: keep + code: journey.keep.state-lost + finding: FH-3 + removedBy: M4 + basis: predicted + reason: The starter ships a plan, but every start draws fresh databases, so a written record does not survive a restart. + - journey: rstack-dev + product: evidence + step: attach + code: journey.attach.issuer-refused + removedBy: M11 + basis: predicted + reason: Evidence refuses any issuer other than the run's own. No database, so keep does not apply. + - journey: promote + product: breg + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: casework + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: messaging + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: evidence + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: scheduling + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: documents + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: coordinator + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: adapter + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: render + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + - journey: promote + product: discovery + step: input + code: journey.promote.no-input + removedBy: M4 + basis: predicted + reason: The development journey does not finish for this product, so there are no files to promote. + +unreached: + - journey: own-provider + product: discovery + step: call + basis: predicted + reason: Discovery verifies no token. Its last step is one served public call, and whether the steps before it pass is not known until the first run. + - journey: own-provider + product: breg-mcp + step: prepare + basis: predicted + reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + - journey: own-provider + product: breg-review + step: prepare + basis: predicted + reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + - journey: own-provider + product: registry-mcp + step: prepare + basis: predicted + reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + - journey: own-provider + product: evidence-oid4vci + step: prepare + basis: predicted + reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + - journey: own-provider + product: evidence-oid4vp + step: prepare + basis: predicted + reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + - journey: own-provider + product: adapter-job + step: prepare + basis: predicted + reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + - journey: rstack-dev + product: breg-mcp + step: init + basis: predicted + reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + - journey: rstack-dev + product: breg-review + step: init + basis: predicted + reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + - journey: rstack-dev + product: registry-mcp + step: init + basis: predicted + reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + - journey: rstack-dev + product: evidence-oid4vci + step: init + basis: predicted + reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + - journey: rstack-dev + product: evidence-oid4vp + step: init + basis: predicted + reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + - journey: rstack-dev + product: adapter-job + step: init + basis: predicted + reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + - journey: promote + product: breg-mcp + step: input + basis: predicted + reason: Supporting runtime. It is promoted with its parent. + - journey: promote + product: breg-review + step: input + basis: predicted + reason: Supporting runtime. It is promoted with its parent. + - journey: promote + product: registry-mcp + step: input + basis: predicted + reason: Supporting runtime. It is promoted with its parent. + - journey: promote + product: evidence-oid4vci + step: input + basis: predicted + reason: Supporting runtime. It is promoted with its parent. + - journey: promote + product: evidence-oid4vp + step: input + basis: predicted + reason: Supporting runtime. It is promoted with its parent. + - journey: promote + product: adapter-job + step: input + basis: predicted + reason: Supporting runtime. It is promoted with its parent. + +passes: [] diff --git a/products/platform/journeys/first-hour-pass-rule.yaml b/products/platform/journeys/first-hour-pass-rule.yaml new file mode 100644 index 0000000000..fab1b94702 --- /dev/null +++ b/products/platform/journeys/first-hour-pass-rule.yaml @@ -0,0 +1,136 @@ +# The first-hour pass rule for the acceptance journeys. +# +# One first hour is one product, one path (own-provider or rstack-dev) and one +# reader. The rule is fixed before the first measured run. A number changes only +# by a reviewed edit to this file that says why, never to make a measured run +# pass. + +schema: registry.first-hour-pass-rule/v1 + +notCounted: + - Docker installed and running. + - Images pulled. + - Product binaries installed. + - On the own-provider path, an identity provider the reader already runs with + one user, and a stock PostgreSQL server. Creating the client, scope and + audience for the product in that provider is counted (counter 4). + +endPoints: + t1: + name: first call + meaning: The first 2xx answer to an authenticated read. + t2: + name: the hour + meaning: >- + One write accepted, the process restarted, and the written record read + back. Where the product delivers hooks, one delivery received. + +# Any one failing makes the hour fail. Each is counted mechanically as a use of +# an assist (a function in lib-assists.sh) or as a refusal the documented path +# meets. +hardConditions: + - id: certificate + text: No certificate or TLS key made by the reader. + - id: token-hook-or-mapper + text: No token hook and no custom claim mapper for a plain read. + - id: provisioning-sql + text: No SQL typed or written by the reader to provision. + - id: image-build + text: No image built locally. + - id: signature-verifier + text: No signature verifier written by the reader. + - id: no-refusal + text: >- + No refusal met while following the documented path exactly (a refused + start, a 4xx on the documented call). + +# Thresholds are upper bounds, except counter 10, which is a lower bound +# written as a required count out of three planted mistakes. +counters: + - id: 1 + name: steps-to-t1 + how: Commands the reader types, counted as the journey's step calls for the product. + unit: commands + rstackDev: 4 + ownProvider: 10 + - id: 2 + name: files-touched-to-t1 + how: >- + Files the reader creates or edits by hand, counted as the journey's + write_file and edit_file calls. Files a command writes are listed, not + counted. + unit: files + rstackDev: 0 + ownProvider: 2 + - id: 3 + name: lines-written-to-t1 + how: Lines the reader types into those files. + unit: lines + rstackDev: 0 + ownProvider: 25 + - id: 4 + name: identity-provider-changes + how: >- + Objects created or changed in the reader's identity provider. A client, a + scope and an audience count. A mapper or a hook is never allowed. + unit: objects + rstackDev: 0 + ownProvider: 3 + - id: 5 + name: certificates-made + how: Uses of a certificate or key tool by the reader. + unit: certificates + rstackDev: 0 + ownProvider: 0 + - id: 6 + name: concepts-met-to-t1 + how: >- + The size of the union of entries in concepts.yaml that the reader must + type or choose a value for. Each step declares the concepts it introduces. + unit: concepts + rstackDev: 10 + ownProvider: 14 + - id: 7 + name: reader-time-to-t1-modelled + how: The reader-time model below, applied to the steps to T1. + unit: minutes + rstackDev: 10 + ownProvider: 30 + - id: 8 + name: reader-time-to-t2-modelled + how: The reader-time model below, applied to the steps to T2. + unit: minutes + rstackDev: 30 + ownProvider: 60 + - id: 9 + name: machine-time-to-t1 + how: >- + Measured wall time of the commands, without image pulls and builds. + Directional only on a shared machine. + unit: minutes + rstackDev: 3 + ownProvider: 3 + - id: 10 + name: errors-that-say-what-to-change + how: >- + Three planted mistakes (wrong audience, missing scope, expired token). + In development each answer names the setting or claim to change. + The value is the number of the three that do. + unit: of-three + direction: at-least + rstackDev: 3 + ownProvider: 3 + +# The model that turns counted effort into reader time. The same constants are +# used for every run, so two runs are comparable even though neither is a +# stopwatch reading. +readerTimeModel: + typingCharactersPerMinute: 200 + readingWordsPerMinute: 200 + secondsPerHandWrittenLine: 30 + secondsPerConceptFirstMet: 60 + minutesPerRefusalMet: 5 + minutesPerAssistUsed: 10 + +# Pass means every hard condition holds and every counter is inside its threshold. +pass: all-hard-conditions-and-all-counters diff --git a/products/platform/journeys/lib.sh b/products/platform/journeys/lib.sh new file mode 100644 index 0000000000..70143fcd8d --- /dev/null +++ b/products/platform/journeys/lib.sh @@ -0,0 +1,2608 @@ +#!/usr/bin/env bash +# Shared helpers for the acceptance journeys in this folder. A journey script +# sources this file and calls journey_init before anything else: +# +# source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" +# journey_init own-provider --value-option issuer -- "$@" +# +# README.md documents the commands, the two modes and the table formats. This +# file holds the rules every journey shares. +# +# Exit status: 0 when every cell is what the mode requires, 1 when a product +# outcome is wrong (acceptance mode: a cell did not pass; ratchet mode: a cell +# differs from the table), 2 for usage or a missing prerequisite, 3 for a +# harness failure (a container that did not start, an occupied name, a +# timeout, a journey script error, a cleanup that failed, a secret found in +# saved output). A harness failure is never recorded as a product outcome. +# +# Binaries come from --bin-dir, else from a build into the exported +# CARGO_TARGET_DIR through scripts/cargo-runtime-library-path.sh. The +# repository target/ directory is never used. On macOS the AWS-LC FIPS library +# directory is exported as DYLD_FALLBACK_LIBRARY_PATH inside this shell and +# product binaries are started directly by bash. A protected launcher in +# between (/usr/bin/env, /usr/bin/time, the system Python, uv) drops every +# DYLD_* variable and the binary aborts on the missing library, so none is +# used: step deadlines are kept by a bash watchdog, not by a wrapper command. +# +# Containers are plain `docker run` on the default bridge network. A name is +# ---, is written to /containers.txt the +# moment Docker creates it (seen through --cidfile, or for an interrupted +# docker run by looking up that exact name), and cleanup removes exactly the +# names in that file. Ports are published on 127.0.0.1 only. No +# network is created, no Compose file is used, nothing is pruned, no label +# filter selects what to remove, and a name that already exists is never +# adopted. +# +# Secrets are generated into /secrets/ with mode 0600 and reach +# containers by env file and products by file path. Tokens stay in shell +# variables and reach curl through process substitution, so they are never on +# an argument list or on disk. Command output is captured into /.raw/ +# (mode 0700), passed through journey_redact into its saved place and the raw +# copy deleted. Before the run ends the saved output is scanned for every +# secret value, private key block and compact JWT. +# +# Cleanup runs from one EXIT trap on normal exit, on error and on interrupt: +# cleanup hooks, then host processes, then containers, then raw output, then +# the secret scan, then secrets. A cleanup failure is printed and turns exit +# status 0 or 1 into 3: a run that left something behind is a harness failure +# whatever the products did. +# +# Functions named journey_* are the interface for journey scripts. Functions +# named journey__* and variables named _journey_* or _jc_* are internal. A +# function that hands back a value sets a variable the caller names; the +# JOURNEY_* variables set after a step (JOURNEY_STEP_STATUS, _STDOUT, _STDERR, +# JOURNEY_HTTP_STATUS, _PROBLEM_CODE, _HEADERS, _CAPTURE_FAILED and +# JOURNEY_PROCESS_STATUS) are read by the journey scripts. +# +# shellcheck disable=SC2016 # jq and perl programs name their own $variables inside single quotes +# shellcheck disable=SC2034 # the JOURNEY_* outputs above are read by the scripts that source this file +set -euo pipefail + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + printf 'lib.sh is sourced by a journey script; it does nothing on its own.\n' >&2 + exit 2 +fi + +JOURNEY_LIB_DIR="$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" +JOURNEY_ROOT="$(CDPATH='' cd -- "$JOURNEY_LIB_DIR/../../.." && pwd -P)" +JOURNEY_TABLES_DIR="${JOURNEY_TABLES_DIR:-$JOURNEY_LIB_DIR}" +JOURNEY_ASSISTS_FILE="${JOURNEY_ASSISTS_FILE:-$JOURNEY_LIB_DIR/lib-assists.sh}" +JOURNEY_STEP_TIMEOUT="${JOURNEY_STEP_TIMEOUT:-300}" +JOURNEY_KILL_GRACE="${JOURNEY_KILL_GRACE:-10}" +JOURNEY_CONTAINER_PREFIX="${JOURNEY_CONTAINER_PREFIX:-rsj}" +JOURNEY_PORT_BASE="${JOURNEY_PORT_BASE:-}" + +_journey_re_id='^[a-z0-9]+(-[a-z0-9]+)*$' +_journey_re_step='^[a-z0-9]+([.-][a-z0-9]+)*$' +_journey_re_var='^[A-Za-z_][A-Za-z0-9_]*$' +_journey_re_env='^[A-Z_][A-Z0-9_]*$' +_journey_re_uint='^[0-9]+$' +_journey_re_posint='^[1-9][0-9]*$' +_journey_re_digest='^[^[:space:]@]+@sha256:[0-9a-f]{64}$' +_journey_re_code_journey='^journey\.([a-z]+)\.([a-z0-9]+(-[a-z0-9]+)*)$' +_journey_re_code_http='^http\.[1-5][0-9][0-9]\.([a-z]+(-[a-z]+)*)$' +_journey_re_code_product='^product(\.[a-z0-9]+(-[a-z0-9]+)*)+$' +_journey_re_container='^[a-z0-9][a-z0-9.-]*$' +_journey_re_header='^[A-Za-z0-9-]+: [^[:cntrl:]]*$' +_journey_re_credential_header='^([Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]|[Cc][Oo][Oo][Kk][Ii][Ee]):' +_journey_nl=$'\n' + +_journey_finished=0 +_journey_cleaned=0 +_journey_harness_message='' +_journey_exit_status='' +_journey_secret_scan='not-run' +_journey_cleanup_failures='' +_journey_address_class='' +_journey_image_lines='' +_journey_leftovers='' +_journey_taken_over='' +_journey_binaries_source='' +_journey_raw_counter=0 +_journey_port_count=0 +_journey_foreground_pid='' +_journey_watchdog_pid='' +_journey_run_timed_out=0 +_journey_done_cells='' +_journey_value_options=() +_journey_extra_names=() +_journey_extra_values=() +_journey_cleanup_hooks=() +_journey_raw_files=() +_journey_secret_files=() +_journey_secret_labels=() +_journey_secret_dirs=() +_journey_secret_values=() +_journey_secret_value_labels=() +_journey_process_keys=() +_journey_process_pids=() +_journey_process_bases=() +_journey_process_raws=() +_journey_pending_container='' +_journey_pending_cidfile='' +_journey_products_json='' +_journey_concepts_json='' +_journey_concept_ids='' +_journey_expected_json='' +_journey_model_json='' +_journey_steps='' +_journey_last_step='' +_jc_open=0 +_jc_product='' +JOURNEY_BIN_DIR='' +JOURNEY_PRODUCTS=() +JOURNEY_SELECTED=() + +# --------------------------------------------------------------------------- +# Messages and failures + +journey__say() { + printf 'journey: %s\n' "$*" >&2 +} + +# Usage or a missing prerequisite: exit 2. During cleanup nothing exits: the +# failure is recorded as a cleanup failure and cleanup carries on. +journey_usage_error() { + if [[ $_journey_cleaned -eq 1 ]]; then + journey__cleanup_problem "$*" + return 1 + fi + journey__say "$*" + exit 2 +} + +# A failure of the harness, never of a product: exit 3. +journey_harness_failure() { + if [[ $_journey_cleaned -eq 1 ]]; then + journey__cleanup_problem "$*" + return 1 + fi + journey__say "harness failure: $*" + _journey_harness_message="$*" + exit 3 +} + +journey__script_error() { + journey_harness_failure "journey script error: $*" +} + +# A function that sets or reads a variable the caller names keeps its own +# locals under _jr_ (journey_http under _jh_), so a caller's name must not +# start with _jr_: printf -v would set the function's local instead. +journey__check_var() { + [[ "${1:-}" =~ $_journey_re_var && "${1:-}" != _jr_* ]] || + journey__script_error "'${1:-}' is not a variable name the library can set (names starting with _jr_ are its own)" +} + +journey__check_id() { + [[ "${2:-}" =~ $_journey_re_id ]] || journey__script_error "$1 '${2:-}' must be lowercase words joined by hyphens" +} + +journey__in_list() { + [[ $'\n'"$2"$'\n' == *$'\n'"$1"$'\n'* ]] +} + +journey__plain_text() { + [[ "$2" != *$'\t'* && "$2" != *$'\n'* ]] || journey__script_error "$1 must not contain a tab or a line break" +} + +# --------------------------------------------------------------------------- +# Small tools: clock, sums, JSON and YAML readers + +journey__now() { + local _jr_value + _jr_value="$(perl -MTime::HiRes=time -e 'printf "%.3f\n", time')" || journey_harness_failure "the clock (perl Time::HiRes) failed" + printf -v "$1" '%s' "$_jr_value" +} + +journey__elapsed() { + local _jr_value + _jr_value="$(perl -e 'printf "%.3f\n", $ARGV[1] - $ARGV[0]' "$1" "$2")" || journey_harness_failure "cannot subtract times" + printf -v "$3" '%s' "$_jr_value" +} + +journey__sum() { + local _jr_value + _jr_value="$(perl -e 'printf "%.3f\n", $ARGV[0] + $ARGV[1]' "$1" "$2")" || journey_harness_failure "cannot add times" + printf -v "$3" '%s' "$_jr_value" +} + +# journey__jq_into VAR JSON FILTER [jq options...] +journey__jq_into() { + local _jr_target=$1 _jr_json=$2 _jr_filter=$3 _jr_out + shift 3 + _jr_out="$(jq -r "$@" "$_jr_filter" <<<"$_jr_json")" || journey_harness_failure "jq could not evaluate $_jr_filter" + printf -v "$_jr_target" '%s' "$_jr_out" +} + +# Read a YAML table into JSON with the YAML reader in core Perl. That reader +# covers block mappings and sequences; a flow sequence of plain words (`[a, b]`) +# arrives as a string and is split here, and null, true, false and integers +# become JSON values. Anything outside that subset is refused, never guessed. +# The Perl programs in this file are single-quoted strings rather than here +# documents inside $(...), which bash 3.2 cannot parse. +_journey_perl_yaml_json=' +use strict; +use warnings; +use CPAN::Meta::YAML; +use JSON::PP; +my ($path) = @ARGV; +open my $fh, "<:encoding(UTF-8)", $path or die "cannot read $path: $!\n"; +local $/; +my $text = <$fh>; +close $fh; +my $docs = CPAN::Meta::YAML->read_string($text) + or die "cannot read $path: " . CPAN::Meta::YAML->errstr . "\n"; +sub value { + my ($v) = @_; + return undef unless defined $v; + if ($v =~ /^\[(.*)\]$/s) { + my $inner = $1; + die "$path: unsupported flow sequence $v\n" if $inner =~ /[\[\]{}"\x27]/; + return [] if $inner =~ /^\s*$/; + return [ map { my $item = $_; $item =~ s/^\s+|\s+$//g; $item } split /,/, $inner ]; + } + die "$path: unsupported flow mapping $v\n" if $v =~ /^\{/; + return undef if $v eq "null" || $v eq "~"; + return JSON::PP::true if $v eq "true"; + return JSON::PP::false if $v eq "false"; + return 0 + $v if $v =~ /^-?(0|[1-9][0-9]*)$/; + return $v; +} +sub walk { + my ($node) = @_; + return { map { $_ => walk($node->{$_}) } keys %$node } if ref $node eq "HASH"; + return [ map { walk($_) } @$node ] if ref $node eq "ARRAY"; + return value($node); +} +print JSON::PP->new->canonical->encode(walk($docs->[0])), "\n"; +' + +journey__yaml_json() { + local _jr_json + [[ -f "$1" ]] || journey_usage_error "the journey table $1 does not exist" + _jr_json="$(perl -e "$_journey_perl_yaml_json" "$1")" || journey_usage_error "cannot read the journey table $1" + printf -v "$2" '%s' "$_jr_json" +} + +# The reader-time model is the readerTimeModel block of the pass rule: one +# integer per line. The rest of that file uses YAML the core reader cannot +# parse, so only that block is read, and every constant must be present. +_journey_perl_reader_model=' +use strict; +use warnings; +use JSON::PP; +my ($path) = @ARGV; +open my $fh, "<", $path or die "cannot read $path: $!\n"; +my ($inside, %model) = (0); +while (my $line = <$fh>) { + chomp $line; + if ($line =~ /^readerTimeModel:\s*(#.*)?$/) { $inside = 1; next } + next unless $inside; + last if $line =~ /^\S/; + next if $line =~ /^\s*(#.*)?$/; + $line =~ /^\s+([A-Za-z]+):\s*([0-9]+)\s*(#.*)?$/ + or die "$path: readerTimeModel holds a line that is not a name and an integer: $line\n"; + $model{$1} = 0 + $2; +} +for my $name (qw(typingCharactersPerMinute readingWordsPerMinute secondsPerHandWrittenLine + secondsPerConceptFirstMet minutesPerRefusalMet minutesPerAssistUsed)) { + die "$path: readerTimeModel has no $name\n" unless exists $model{$name}; + die "$path: readerTimeModel $name must be positive\n" unless $model{$name} > 0; +} +print JSON::PP->new->canonical->encode(\%model), "\n"; +' + +journey__reader_model() { + local _jr_json + [[ -f "$1" ]] || journey_usage_error "the pass rule $1 does not exist" + _jr_json="$(perl -e "$_journey_perl_reader_model" "$1")" || journey_usage_error "cannot read the reader-time model in $1" + _journey_model_json=$_jr_json +} + +journey__require_schema() { + jq -e --arg schema "$2" '.schema == $schema' <<<"$1" >/dev/null || + journey_usage_error "$3 does not declare schema $2" +} + +# --------------------------------------------------------------------------- +# Start of a run + +journey__print_usage() { + local extra='' name + for name in ${_journey_value_options[@]+"${_journey_value_options[@]}"}; do + extra="$extra [--$name VALUE]" + done + cat </dev/null 2>&1 || journey_usage_error "this journey needs $tool on PATH" + done + perl -MCPAN::Meta::YAML -MJSON::PP -MTime::HiRes -MFile::Find -e 1 || + journey_usage_error "this journey needs perl with its core modules CPAN::Meta::YAML, JSON::PP, Time::HiRes and File::Find" +} + +journey__load_tables() { + local expected="$JOURNEY_TABLES_DIR/expected-failures.yaml" + journey__yaml_json "$JOURNEY_TABLES_DIR/products.yaml" _journey_products_json + journey__require_schema "$_journey_products_json" registry.journey-products/v1 "$JOURNEY_TABLES_DIR/products.yaml" + journey__yaml_json "$JOURNEY_TABLES_DIR/concepts.yaml" _journey_concepts_json + journey__jq_into _journey_concept_ids "$_journey_concepts_json" '.concepts[].id' + journey__reader_model "$JOURNEY_TABLES_DIR/first-hour-pass-rule.yaml" + if [[ -n "$_journey_expected_option" ]]; then + [[ -f "$_journey_expected_option" ]] || journey_usage_error "--expected $_journey_expected_option is not a file" + expected="$(CDPATH='' cd -- "$(dirname -- "$_journey_expected_option")" && pwd -P)/${_journey_expected_option##*/}" || + journey_usage_error "cannot resolve --expected $_journey_expected_option" + fi + JOURNEY_EXPECTED_FILE=$expected + journey__yaml_json "$expected" _journey_expected_json + journey__require_schema "$_journey_expected_json" registry.journey-expected-failures/v1 "$expected" + journey__jq_into _journey_steps "$_journey_expected_json" '(.journeys[$journey].steps // []) | .[]' --arg journey "$JOURNEY_NAME" + [[ -n "$_journey_steps" ]] || journey_usage_error "journey $JOURNEY_NAME has no steps in $expected" + _journey_last_step=${_journey_steps##*"$_journey_nl"} +} + +journey__select_products() { + local ids id selected + journey__jq_into ids "$_journey_products_json" '.products[].id' + JOURNEY_PRODUCTS=() + if [[ ${#JOURNEY_SELECTED[@]} -eq 0 ]]; then + while IFS= read -r id; do + [[ -z "$id" ]] || JOURNEY_PRODUCTS+=("$id") + done <<<"$ids" + return 0 + fi + for selected in "${JOURNEY_SELECTED[@]}"; do + journey__in_list "$selected" "$ids" || journey_usage_error "unknown product $selected; products.yaml lists: ${ids//$_journey_nl/ }" + done + while IFS= read -r id; do + for selected in "${JOURNEY_SELECTED[@]}"; do + if [[ "$selected" == "$id" ]]; then + JOURNEY_PRODUCTS+=("$id") + break + fi + done + done <<<"$ids" +} + +# Assists live in lib-assists.sh, the one file allowed to do what the pass +# rule forbids. It is sourced only when --assist names at least one assist. +journey__load_assists() { + local name rest + [[ -n "$JOURNEY_ASSISTS" ]] || return 0 + [[ -f "$JOURNEY_ASSISTS_FILE" ]] || journey_usage_error "--assist needs $JOURNEY_ASSISTS_FILE, which does not exist" + # shellcheck source=/dev/null + source "$JOURNEY_ASSISTS_FILE" + rest="$JOURNEY_ASSISTS," + while [[ -n "$rest" ]]; do + name=${rest%%,*} + rest=${rest#*,} + [[ "$name" =~ $_journey_re_id ]] || journey_usage_error "--assist names '$name', which is not an assist name" + [[ "$(type -t "journey_assist_${name//-/_}")" == function ]] || + journey_usage_error "--assist names $name, but $JOURNEY_ASSISTS_FILE defines no journey_assist_${name//-/_}" + done +} + +journey__check_settings() { + [[ "$JOURNEY_CONTAINER_PREFIX" =~ $_journey_re_id ]] || + journey_usage_error "JOURNEY_CONTAINER_PREFIX must be lowercase words joined by hyphens" + if [[ -n "$JOURNEY_PORT_BASE" ]]; then + if [[ ! "$JOURNEY_PORT_BASE" =~ $_journey_re_uint ]] || ((JOURNEY_PORT_BASE < 1024 || JOURNEY_PORT_BASE > 65000)); then + journey_usage_error "JOURNEY_PORT_BASE must be a port number from 1024 to 65000" + fi + fi + [[ "$JOURNEY_STEP_TIMEOUT" =~ $_journey_re_posint ]] || journey_usage_error "JOURNEY_STEP_TIMEOUT must be a whole number of seconds" + [[ "$JOURNEY_KILL_GRACE" =~ $_journey_re_posint ]] || journey_usage_error "JOURNEY_KILL_GRACE must be a whole number of seconds" +} + +journey__path_crosses_symlink() { + local rest=${1#/} current='' part + while [[ -n "$rest" ]]; do + part=${rest%%/*} + if [[ "$rest" == */* ]]; then + rest=${rest#*/} + else + rest='' + fi + [[ -n "$part" ]] || continue + current="$current/$part" + if [[ -L "$current" ]]; then + return 0 + fi + done + return 1 +} + +journey__directory_is_empty() { + ( + shopt -s nullglob dotglob + set -- "$1"/* + [[ $# -eq 0 ]] + ) +} + +journey__create_run_directory() { + local requested=$_journey_out_option root physical + if [[ -z "$requested" ]]; then + root="$(CDPATH='' cd -- "${TMPDIR:-/tmp}" && pwd -P)" || journey_usage_error "cannot resolve the temporary directory ${TMPDIR:-/tmp}" + requested="$root/$JOURNEY_CONTAINER_PREFIX-$JOURNEY_NAME-$JOURNEY_RUN_ID" + mkdir -m 700 -- "$requested" || journey_usage_error "cannot create the run directory $requested" + elif [[ -e "$requested" || -L "$requested" ]]; then + [[ -d "$requested" ]] || journey_usage_error "--out $requested exists and is not a directory" + journey__directory_is_empty "$requested" || + journey_usage_error "--out $requested is not empty; name an absent or empty directory so this run's cleanup lists only its own containers" + else + mkdir -p -- "$requested" || journey_usage_error "cannot create --out $requested" + fi + physical="$(CDPATH='' cd -- "$requested" && pwd -P)" || journey_usage_error "cannot resolve --out $requested" + if journey__path_crosses_symlink "$physical"; then + journey_usage_error "the run directory $physical still crosses a symbolic link; runtime files under it would be refused" + fi + # macOS chmod takes no "--"; the path is absolute, so it cannot read as an option. + chmod 700 "$physical" || journey_usage_error "cannot set mode 0700 on $physical" + JOURNEY_OUT=$physical + mkdir -m 700 -- "$JOURNEY_OUT/.raw" "$JOURNEY_OUT/secrets" || journey_usage_error "cannot create the private folders under $JOURNEY_OUT" + mkdir -- "$JOURNEY_OUT/containers" "$JOURNEY_OUT/work" || journey_usage_error "cannot create the folders under $JOURNEY_OUT" + _journey_secret_dirs+=("$JOURNEY_OUT/secrets") + : >"$JOURNEY_OUT/containers.txt" + printf 'product\tstep\toutcome\tcode\tseconds\n' >"$JOURNEY_OUT/cells.tsv" +} + +journey__record_environment() { + local status_text + _journey_git_head='' + _journey_git_dirty='' + _journey_git_note='' + if _journey_git_head="$(git --no-optional-locks -C "$JOURNEY_ROOT" rev-parse HEAD 2>/dev/null)"; then + if status_text="$(git --no-optional-locks -C "$JOURNEY_ROOT" status --porcelain)"; then + _journey_git_dirty=false + [[ -z "$status_text" ]] || _journey_git_dirty=true + else + _journey_git_note='git status failed' + fi + else + _journey_git_head='' + _journey_git_note='not a git checkout, or git is not on PATH' + fi + _journey_os="$(uname -s)" || journey_harness_failure "uname -s failed" + _journey_arch="$(uname -m)" || journey_harness_failure "uname -m failed" + _journey_started_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" || journey_harness_failure "date failed" +} + +journey__write_run_json() { + local file="$JOURNEY_OUT/run.json" ended='' + if [[ "${1:-}" == end ]]; then + ended="$(date -u +%Y-%m-%dT%H:%M:%SZ)" || return 1 + fi + jq -n \ + --arg journey "$JOURNEY_NAME" \ + --arg run "$JOURNEY_RUN_ID" \ + --arg mode "$JOURNEY_MODE" \ + --argjson strict "$JOURNEY_STRICT" \ + --argjson keep "$JOURNEY_KEEP" \ + --argjson timed "$JOURNEY_TIMED" \ + --arg assists "$JOURNEY_ASSISTS" \ + --arg table "${JOURNEY_EXPECTED_FILE:-}" \ + --arg products "$(printf '%s\n' ${JOURNEY_PRODUCTS[@]+"${JOURNEY_PRODUCTS[@]}"})" \ + --arg head "$_journey_git_head" \ + --arg dirty "$_journey_git_dirty" \ + --arg gitNote "$_journey_git_note" \ + --arg os "$_journey_os" \ + --arg arch "$_journey_arch" \ + --arg addressClass "$_journey_address_class" \ + --arg prefix "$JOURNEY_CONTAINER_PREFIX" \ + --arg portBase "$JOURNEY_PORT_BASE" \ + --arg binSource "$_journey_binaries_source" \ + --arg binDir "$JOURNEY_BIN_DIR" \ + --arg runtimeLibrary "${REGISTRY_CARGO_RUNTIME_LIBRARY_PATH:-}" \ + --arg images "$_journey_image_lines" \ + --arg startedAt "$_journey_started_at" \ + --arg endedAt "$ended" \ + --arg exitStatus "$_journey_exit_status" \ + --arg harness "$_journey_harness_message" \ + --arg cleanupFailures "$_journey_cleanup_failures" \ + --arg leftovers "$_journey_leftovers" \ + --arg takenOver "$_journey_taken_over" \ + --arg secretScan "$_journey_secret_scan" \ + 'def opt: if . == "" then null else . end; + def lines: split("\n") | map(select(length > 0)); + { + schema: "registry.journey-run/v1", + journey: $journey, runId: $run, mode: $mode, + strict: ($strict == 1), keep: ($keep == 1), timed: ($timed == 1), + assists: ($assists | split(",") | map(select(length > 0))), + table: ($table | opt), + products: ($products | lines), + git: {head: ($head | opt), dirty: (if $dirty == "" then null else ($dirty == "true") end), note: ($gitNote | opt)}, + system: {os: $os, arch: $arch}, + addressClass: ($addressClass | opt), + containerPrefix: $prefix, + portBase: (if $portBase == "" then null else ($portBase | tonumber) end), + binaries: {source: ($binSource | opt), directory: ($binDir | opt), runtimeLibraryPath: ($runtimeLibrary | opt)}, + images: [($images | lines)[] | split("\t") | {role: .[0], container: .[1], image: .[2]}], + takenOver: ($takenOver | opt), + startedAt: $startedAt, + endedAt: ($endedAt | opt), + exitStatus: (if $exitStatus == "" then null else ($exitStatus | tonumber) end), + harnessFailure: ($harness | opt), + cleanup: {failures: ($cleanupFailures | lines)}, + leftovers: ($leftovers | lines), + secretScan: $secretScan + }' >"$file.tmp" || return 1 + mv -f -- "$file.tmp" "$file" || return 1 +} + +journey__install_traps() { + trap journey__on_exit EXIT + trap 'exit 129' HUP + trap 'exit 130' INT + trap 'exit 143' TERM +} + +# journey_init JOURNEY [--value-option NAME]... -- "$@" +# Parses the shared options (see --help) and the journey's own value options, +# checks prerequisites, reads the tables, creates the run directory, installs +# the cleanup trap and writes run.json. +journey_init() { + local random + [[ $# -gt 0 ]] || journey__script_error "journey_init needs the journey name" + JOURNEY_NAME=$1 + shift + journey__check_id journey "$JOURNEY_NAME" + while [[ $# -gt 0 && "$1" != -- ]]; do + case "$1" in + --value-option) + [[ $# -ge 2 ]] || journey__script_error "--value-option needs a name" + journey__check_id option "$2" + _journey_value_options+=("$2") + shift 2 + ;; + *) journey__script_error "journey_init: unknown declaration $1; end the declarations with --" ;; + esac + done + [[ $# -gt 0 ]] || journey__script_error "journey_init: put -- before the command-line arguments" + shift + journey__parse_arguments "$@" + journey__check_prerequisites + journey__load_tables + journey__select_products + journey__load_assists + journey__check_settings + random="$(od -An -N2 -tx1 /dev/urandom | tr -d ' \n')" || journey_harness_failure "cannot read /dev/urandom" + JOURNEY_RUN_ID="$(date -u +%Y%m%d%H%M%S)-$random" || journey_harness_failure "date failed" + journey__record_environment + journey__create_run_directory + journey__install_traps + journey__write_run_json || journey_harness_failure "cannot write $JOURNEY_OUT/run.json" + journey__say "run $JOURNEY_RUN_ID, $JOURNEY_MODE mode, output in $JOURNEY_OUT" +} + +# journey_option_value NAME VAR: the value of a journey's own --NAME option, +# or empty when it was not given. +journey_option_value() { + local _jr_name=${1:-} _jr_target=${2:-} _jr_index + journey__check_var "$_jr_target" + journey__declared_option "$_jr_name" || journey__script_error "option --$_jr_name was not declared to journey_init" + printf -v "$_jr_target" '%s' '' + for ((_jr_index = 0; _jr_index < ${#_journey_extra_names[@]}; _jr_index++)); do + if [[ "${_journey_extra_names[$_jr_index]}" == "$_jr_name" ]]; then + printf -v "$_jr_target" '%s' "${_journey_extra_values[$_jr_index]}" + fi + done +} + +# journey_product_field PRODUCT FIELD VAR: a field of the product's row in +# products.yaml. A list arrives as words joined by spaces, null as empty. +journey_product_field() { + local _jr_product=${1:-} _jr_field=${2:-} _jr_target=${3:-} _jpf_value + journey__check_var "$_jr_target" + journey__jq_into _jpf_value "$_journey_products_json" \ + '[.products[] | select(.id == $product)] | if length != 1 then error("no single row") else .[0][$field] end + | if type == "array" then join(" ") elif . == null then "" else tostring end' \ + --arg product "$_jr_product" --arg field "$_jr_field" + printf -v "$_jr_target" '%s' "$_jpf_value" +} + +# journey_require_docker: exit 2 unless the docker CLI is on PATH and +# `docker version` reaches a running daemon. +journey_require_docker() { + command -v docker >/dev/null 2>&1 || journey_usage_error "this journey needs the docker CLI on PATH" + docker version --format '{{.Server.Version}}' >/dev/null || + journey_usage_error "this journey needs a running Docker daemon; docker version could not reach one" +} + +# journey_at_cleanup FUNCTION: run FUNCTION first during cleanup (last +# registered runs first). Its failure is reported as a cleanup failure. +journey_at_cleanup() { + [[ "$(type -t "${1:-}")" == function ]] || journey__script_error "journey_at_cleanup needs a function name" + _journey_cleanup_hooks+=("$1") +} + +# journey_set_address_class loopback|bridge: record in run.json whether the +# products reached the journey's containers through ports published on +# 127.0.0.1 or at a container address on the default bridge network. +journey_set_address_class() { + case "${1:-}" in + loopback | bridge) _journey_address_class=$1 ;; + *) journey__script_error "the address class is loopback or bridge, not '${1:-}'" ;; + esac +} + +# --------------------------------------------------------------------------- +# Binaries + +journey__runtime_library_from_bin_dir() { + local directory='' candidate + [[ "$(uname -s)" == Darwin ]] || return 0 + if [[ -n "${REGISTRY_CARGO_RUNTIME_LIBRARY_PATH:-}" ]]; then + [[ -d "$REGISTRY_CARGO_RUNTIME_LIBRARY_PATH" ]] || + journey_usage_error "REGISTRY_CARGO_RUNTIME_LIBRARY_PATH names no directory: $REGISTRY_CARGO_RUNTIME_LIBRARY_PATH" + directory="$(CDPATH='' cd -- "$REGISTRY_CARGO_RUNTIME_LIBRARY_PATH" && pwd -P)" || + journey_usage_error "cannot resolve REGISTRY_CARGO_RUNTIME_LIBRARY_PATH" + else + for candidate in "$JOURNEY_BIN_DIR"/build/aws-lc-fips-sys-*/out/build/artifacts; do + if [[ -d "$candidate" ]]; then + directory="$(CDPATH='' cd -- "$candidate" && pwd -P)" || journey_usage_error "cannot resolve $candidate" + break + fi + done + fi + if [[ -z "$directory" ]]; then + journey__say "warning: no AWS-LC FIPS library directory under $JOURNEY_BIN_DIR/build and REGISTRY_CARGO_RUNTIME_LIBRARY_PATH is unset; a binary that links the library dynamically will abort when it starts" + return 0 + fi + [[ "$directory" != *:* ]] || journey_usage_error "the AWS-LC FIPS runtime directory cannot contain a colon: $directory" + REGISTRY_CARGO_RUNTIME_LIBRARY_PATH=$directory + export REGISTRY_CARGO_RUNTIME_LIBRARY_PATH + DYLD_FALLBACK_LIBRARY_PATH="$directory${DYLD_FALLBACK_LIBRARY_PATH:+:$DYLD_FALLBACK_LIBRARY_PATH}" + export DYLD_FALLBACK_LIBRARY_PATH +} + +# journey_resolve_binaries [--package P]... [--feature F]... PRODUCT... +# With --bin-dir, use that directory as it is. Otherwise build the products' +# cargoPackages and cargoFeatures (plus any extra package or feature) with +# --locked into the exported CARGO_TARGET_DIR. Sets JOURNEY_BIN_DIR. +journey_resolve_binaries() { + local -a products=() arguments=() + local product value word target packages='' features='' joined='' + while [[ $# -gt 0 ]]; do + case "$1" in + --package | --feature) + [[ $# -ge 2 && "$2" =~ ^[A-Za-z0-9_/-]+$ ]] || journey__script_error "$1 needs a package or feature name" + if [[ "$1" == --package ]]; then packages+="$2"$'\n'; else features+="$2"$'\n'; fi + shift 2 + ;; + -*) journey__script_error "journey_resolve_binaries: unknown option $1" ;; + *) + journey__in_list "$1" "$(printf '%s\n' "${JOURNEY_PRODUCTS[@]}")" || journey__script_error "product $1 is not selected for this run" + products+=("$1") + shift + ;; + esac + done + if [[ -n "$_journey_bin_dir_option" ]]; then + [[ -d "$_journey_bin_dir_option" ]] || journey_usage_error "--bin-dir $_journey_bin_dir_option is not a directory" + JOURNEY_BIN_DIR="$(CDPATH='' cd -- "$_journey_bin_dir_option" && pwd -P)" || journey_usage_error "cannot resolve --bin-dir" + _journey_binaries_source=bin-dir + journey__runtime_library_from_bin_dir + journey__write_run_json || journey_harness_failure "cannot write run.json" + return 0 + fi + [[ $JOURNEY_TIMED -eq 0 ]] || + journey_usage_error "--timed needs --bin-dir: a baseline run in which a build happened is discarded" + [[ -n "${CARGO_TARGET_DIR:-}" ]] || + journey_usage_error "no product binaries: pass --bin-dir DIR or export CARGO_TARGET_DIR to build into; the repository target/ directory is never used" + target=$CARGO_TARGET_DIR + [[ "$target" == /* ]] || target="$PWD/$target" + if [[ "$target" == "$JOURNEY_ROOT/target" || "$target" == "$JOURNEY_ROOT/target/"* ]]; then + journey_usage_error "CARGO_TARGET_DIR points at the repository target/ directory, which a journey never uses: a stale binary there once checked green against the wrong reader" + fi + command -v cargo >/dev/null 2>&1 || journey_usage_error "CARGO_TARGET_DIR is set but cargo is not on PATH" + for product in ${products[@]+"${products[@]}"}; do + journey_product_field "$product" cargoPackages value + for word in $value; do packages+="$word"$'\n'; done + journey_product_field "$product" cargoFeatures value + for word in $value; do features+="$word"$'\n'; done + done + [[ -n "$packages" ]] || journey__script_error "journey_resolve_binaries has no package to build" + arguments=(--locked --manifest-path "$JOURNEY_ROOT/Cargo.toml") + value='' + while IFS= read -r word; do + if [[ -z "$word" ]] || journey__in_list "$word" "$value"; then + continue + fi + value+="$word"$'\n' + arguments+=(-p "$word") + done <<<"$packages" + value='' + while IFS= read -r word; do + if [[ -z "$word" ]] || journey__in_list "$word" "$value"; then + continue + fi + value+="$word"$'\n' + joined="${joined:+$joined,}$word" + done <<<"$features" + [[ -z "$joined" ]] || arguments+=(--features "$joined") + arguments+=(--bins) + # The repository's helper: registry_cargo_build builds through cargo and, on + # macOS, exports the FIPS library directory it reads from cargo's messages. + # shellcheck source=/dev/null + source "$JOURNEY_ROOT/scripts/cargo-runtime-library-path.sh" + export CARGO_TARGET_DIR="$target" + registry_cargo_build "$JOURNEY_ROOT" "${arguments[@]}" || + journey_usage_error "the build of the journey binaries failed; fix it or pass --bin-dir" + JOURNEY_BIN_DIR="$target/debug" + _journey_binaries_source=build + journey__write_run_json || journey_harness_failure "cannot write run.json" +} + +# journey_bin NAME VAR: the path of an executable in JOURNEY_BIN_DIR. +journey_bin() { + local _jr_name=${1:-} _jr_target=${2:-} + journey__check_var "$_jr_target" + [[ -n "$JOURNEY_BIN_DIR" ]] || journey__script_error "call journey_resolve_binaries before journey_bin" + [[ -n "$_jr_name" && "$_jr_name" != */* ]] || journey__script_error "journey_bin needs a binary name" + [[ -x "$JOURNEY_BIN_DIR/$_jr_name" && -f "$JOURNEY_BIN_DIR/$_jr_name" ]] || + journey_usage_error "no executable $_jr_name in $JOURNEY_BIN_DIR" + printf -v "$_jr_target" '%s' "$JOURNEY_BIN_DIR/$_jr_name" +} + +# --------------------------------------------------------------------------- +# Raw output, secrets and redaction + +journey__raw_path() { + _journey_raw_counter=$((_journey_raw_counter + 1)) + local _jr_path="$JOURNEY_OUT/.raw/$_journey_raw_counter.$2" + _journey_raw_files+=("$_jr_path") + printf -v "$1" '%s' "$_jr_path" +} + +journey__discard() { + if [[ -e "$1" ]]; then + rm -- "$1" || journey_harness_failure "cannot delete $1" + fi +} + +journey__own_secret_file() { + _journey_secret_files+=("$1") + _journey_secret_labels+=("$2") +} + +# Every secret as one "labelvalue" line: the files this run generated or +# took over, and the values registered from shell variables. +journey__secret_lines() { + local index value + for ((index = 0; index < ${#_journey_secret_files[@]}; index++)); do + [[ -n "${_journey_secret_labels[$index]}" && -f "${_journey_secret_files[$index]}" ]] || continue + value="$(<"${_journey_secret_files[$index]}")" + [[ -z "$value" ]] || printf '%s\t%s\n' "${_journey_secret_labels[$index]}" "$value" + done + for ((index = 0; index < ${#_journey_secret_values[@]}; index++)); do + printf '%s\t%s\n' "${_journey_secret_value_labels[$index]}" "${_journey_secret_values[$index]}" + done +} + +# journey_secret_new NAME [BYTES]: generate BYTES (default 24) random bytes as +# hexadecimal into /secrets/NAME, mode 0600. Nothing is printed. +journey_secret_new() { + local name=${1:-} bytes=${2:-24} path + journey__check_id "secret name" "$name" + if [[ ! "$bytes" =~ $_journey_re_posint ]] || ((bytes < 16)); then + journey__script_error "a secret needs at least 16 random bytes" + fi + path="$JOURNEY_OUT/secrets/$name" + [[ ! -e "$path" ]] || journey__script_error "secret $name already exists" + ( + umask 077 + od -An -N"$bytes" -tx1 /dev/urandom | tr -d ' \n' >"$path" + ) || journey_harness_failure "cannot generate secret $name" + chmod 600 "$path" || journey_harness_failure "cannot set mode 0600 on secret $name" + [[ -s "$path" ]] || journey_harness_failure "secret $name came out empty" + journey__own_secret_file "$path" "$name" +} + +# journey_secret_path NAME VAR +journey_secret_path() { + local _jr_name=${1:-} _jr_target=${2:-} + journey__check_var "$_jr_target" + journey__check_id "secret name" "$_jr_name" + [[ -f "$JOURNEY_OUT/secrets/$_jr_name" ]] || journey__script_error "no secret named $_jr_name" + printf -v "$_jr_target" '%s' "$JOURNEY_OUT/secrets/$_jr_name" +} + +# journey_secret_env_file NAME VAR ENV=SECRET...: write an env file of mode +# 0600 that sets each ENV to the value of a generated secret, for +# `docker run --env-file`. VAR receives its path. +journey_secret_env_file() { + local _jr_name=${1:-} _jr_target=${2:-} _jr_path _jr_pair _jr_env _jr_secret _jr_value + journey__check_id "env file name" "$_jr_name" + journey__check_var "$_jr_target" + shift 2 + _jr_path="$JOURNEY_OUT/secrets/$_jr_name.env" + [[ ! -e "$_jr_path" ]] || journey__script_error "env file $_jr_name already exists" + ( + umask 077 + : >"$_jr_path" + ) || journey_harness_failure "cannot create env file $_jr_name" + journey__own_secret_file "$_jr_path" '' + for _jr_pair in "$@"; do + _jr_env=${_jr_pair%%=*} + _jr_secret=${_jr_pair#*=} + [[ "$_jr_pair" == *=* && "$_jr_env" =~ $_journey_re_env ]] || journey__script_error "an env file entry is ENV=secret-name, not $_jr_pair" + journey__check_id "secret name" "$_jr_secret" + [[ -f "$JOURNEY_OUT/secrets/$_jr_secret" ]] || journey__script_error "no secret named $_jr_secret" + _jr_value="$(<"$JOURNEY_OUT/secrets/$_jr_secret")" + printf '%s=%s\n' "$_jr_env" "$_jr_value" >>"$_jr_path" || journey_harness_failure "cannot write env file $_jr_name" + done + printf -v "$_jr_target" '%s' "$_jr_path" +} + +# journey_secret_register LABEL VARIABLE: treat the value of a shell variable +# (a token, a captured credential) as a secret for redaction and the final +# scan. The value is read by name and never passed as an argument. +journey_secret_register() { + local _jr_label=${1:-} _jr_variable=${2:-} _jr_value + journey__check_id "secret label" "$_jr_label" + journey__check_var "$_jr_variable" + _jr_value=${!_jr_variable-} + ((${#_jr_value} >= 8)) || journey__script_error "the value of $_jr_variable is shorter than 8 characters; it cannot be redacted without hiding ordinary text" + [[ "$_jr_value" != *$'\n'* && "$_jr_value" != *$'\t'* ]] || journey__script_error "the value of $_jr_variable holds a line break or a tab" + _journey_secret_values+=("$_jr_value") + _journey_secret_value_labels+=("$_jr_label") +} + +# journey_redact IN OUT: copy IN to OUT with every secret value, private key +# block, compact JWT, Authorization and Cookie header value, bearer or basic +# credential, URL password and common credential member of a JSON object +# replaced by a [redacted...] marker. +journey_redact() { + [[ -f "${1:-}" ]] || journey__script_error "journey_redact needs an input file" + [[ -n "${2:-}" ]] || journey__script_error "journey_redact needs an output file" + perl - "$1" "$2" 3< <(journey__secret_lines) <<'PERL' +use strict; +use warnings; +my ($in, $out) = @ARGV; +open my $list, '<&=', 3 or die "cannot read the secret list: $!\n"; +my @pairs; +while (my $line = <$list>) { + chomp $line; + my ($label, $value) = split /\t/, $line, 2; + push @pairs, [$label, $value] if defined $value && length $value; +} +@pairs = sort { length($b->[1]) <=> length($a->[1]) } @pairs; +open my $fh, '<:raw', $in or die "cannot read $in: $!\n"; +local $/; +my $text = <$fh>; +close $fh; +$text = '' unless defined $text; +for my $pair (@pairs) { + my $value = quotemeta $pair->[1]; + $text =~ s/$value/[redacted:$pair->[0]]/g; +} +$text =~ s/-----BEGIN ([A-Z0-9 ]*)PRIVATE KEY-----.*?-----END \1PRIVATE KEY-----/[redacted:private-key]/gs; +$text =~ s/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/[redacted:jwt]/g; +$text =~ s/^([<>*\s]*(?:proxy-)?authorization\s*:).*$/$1 [redacted]/gmi; +$text =~ s/^([<>*\s]*(?:set-)?cookie\s*:).*$/$1 [redacted]/gmi; +$text =~ s/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=-]+/$1 [redacted]/g; +$text =~ s{(://[^/\s:@]+:)[^@\s/]+@}{$1\[redacted]@}g; +$text =~ s/("(?:access_token|refresh_token|id_token|client_secret|password|secret|token)"\s*:\s*)"(?:[^"\\]|\\.)*"/$1"[redacted]"/g; +open my $o, '>:raw', $out or die "cannot write $out: $!\n"; +print {$o} $text; +close $o or die "cannot write $out: $!\n"; +PERL +} + +journey__redact_into() { + journey_redact "$1" "$2" || journey_harness_failure "cannot redact $1 into $2" + journey__discard "$1" +} + +# --------------------------------------------------------------------------- +# Processes and deadlines + +journey__process_alive() { + local state + state="$(ps -o stat= -p "$1" 2>/dev/null)" || return 1 + state=${state//[[:space:]]/} + [[ -n "$state" && "$state" != Z* ]] +} + +# Runs in the background: after TERM_AFTER seconds send TERM to PID, after a +# further KILL_AFTER seconds send KILL, and note each in MARKER. A TERM to the +# watchdog itself ends it at once. +journey__watchdog() { + local pid=$1 term_after=$2 kill_after=$3 marker=$4 sleeper='' + # shellcheck disable=SC2317,SC2329 # run by the TERM trap + journey__watchdog_stop() { + if [[ -n "$sleeper" ]]; then + kill -TERM "$sleeper" 2>/dev/null || : + fi + exit 0 + } + trap journey__watchdog_stop TERM + sleep "$term_after" & + sleeper=$! + wait "$sleeper" || : + sleeper='' + journey__process_alive "$pid" || exit 0 + printf 'term\n' >>"$marker" + kill -TERM "$pid" 2>/dev/null || exit 0 + sleep "$kill_after" & + sleeper=$! + wait "$sleeper" || : + sleeper='' + journey__process_alive "$pid" || exit 0 + printf 'kill\n' >>"$marker" + kill -KILL "$pid" 2>/dev/null || : + exit 0 +} + +journey__end_watchdog() { + # The watchdog may have finished on its own; its exit status carries + # nothing, the marker file does. + kill -TERM "$1" 2>/dev/null || : + wait "$1" || : +} + +# journey__terminate PID GRACE: TERM, then KILL after GRACE seconds. Sets +# _journey_terminate_status and _journey_terminate_killed. +journey__terminate() { + local pid=$1 grace=$2 marker watchdog status=0 + journey__raw_path marker "terminate.$pid" + # The process may have exited already; wait below collects its status. + kill -TERM "$pid" 2>/dev/null || : + journey__watchdog "$pid" "$grace" 1 "$marker" /dev/null 2>&1 & + watchdog=$! + wait "$pid" || status=$? + journey__end_watchdog "$watchdog" + _journey_terminate_status=$status + _journey_terminate_killed=0 + if [[ -f "$marker" ]]; then + [[ "$(<"$marker")" != *kill* ]] || _journey_terminate_killed=1 + # Cleanup also calls this function, so a failed delete is reported + # here and left for the final sweep of .raw rather than ending the run. + rm -- "$marker" || journey__say "cannot delete $marker" + fi +} + +# journey__run_command DEADLINE CWD STDIN STDOUT STDERR COMMAND...: run a +# command (a binary, or a shell function such as journey_poll) directly from a +# subshell of this shell, so no launcher sits between bash and the binary. +journey__run_command() { + local deadline=$1 cwd=$2 input=$3 output=$4 errors=$5 marker pid watchdog status=0 + shift 5 + journey__raw_path marker deadline + ( + if [[ -n "$cwd" ]]; then + cd -- "$cwd" || exit 126 + fi + if [[ "$(type -t "$1")" == function ]]; then + "$@" + exit + fi + exec "$@" + ) <"$input" >"$output" 2>"$errors" & + pid=$! + _journey_foreground_pid=$pid + journey__watchdog "$pid" "$deadline" "$JOURNEY_KILL_GRACE" "$marker" /dev/null 2>&1 & + watchdog=$! + _journey_watchdog_pid=$watchdog + wait "$pid" || status=$? + _journey_foreground_pid='' + journey__end_watchdog "$watchdog" + _journey_watchdog_pid='' + _journey_run_timed_out=0 + if [[ -f "$marker" ]]; then + _journey_run_timed_out=1 + journey__discard "$marker" + fi + return "$status" +} + +# journey_poll SECONDS -- COMMAND...: run COMMAND once a second until it +# succeeds. Returns 1 when SECONDS pass first. Meant as a step command. +journey_poll() { + local seconds=${1:-} deadline + [[ "$seconds" =~ $_journey_re_posint ]] || journey__script_error "journey_poll needs a number of seconds" + shift + [[ "${1:-}" != -- ]] || shift + [[ $# -gt 0 ]] || journey__script_error "journey_poll needs a command" + deadline=$((SECONDS + seconds)) + while :; do + if "$@"; then + return 0 + fi + if ((SECONDS >= deadline)); then + printf 'journey_poll: %s did not succeed within %s seconds\n' "$1" "$seconds" >&2 + return 1 + fi + sleep 1 + done +} + +# --------------------------------------------------------------------------- +# Containers + +# journey_container_name ROLE VAR +journey_container_name() { + local _jr_role=${1:-} _jr_target=${2:-} + journey__check_id "container role" "$_jr_role" + journey__check_var "$_jr_target" + printf -v "$_jr_target" '%s' "$JOURNEY_CONTAINER_PREFIX-$JOURNEY_NAME-$JOURNEY_RUN_ID-$_jr_role" +} + +# journey__container_state NAME: 0 when a container of that name exists, 1 +# when Docker says there is none, 2 (with Docker's message printed) when +# Docker could not answer. +journey__container_state() { + local errors status=0 + errors="$(docker inspect --type container "$1" 2>&1 >/dev/null)" || status=$? + [[ $status -ne 0 ]] || return 0 + if [[ "$errors" == *[Nn]o\ such* ]]; then + return 1 + fi + journey__say "docker inspect $1 failed: $errors" + return 2 +} + +journey__record_container() { + printf '%s\n' "$1" >>"$JOURNEY_OUT/containers.txt" || journey_harness_failure "cannot record container $1 in containers.txt" +} + +# A container whose docker run was interrupted is recorded when its cidfile +# shows Docker created it. Docker writes the cidfile only after the container +# exists, so without one the exact name is looked up: it carries this run's id +# and was checked absent before docker run, so only this run can have made it. +journey__adopt_pending_container() { + local name=$_journey_pending_container cidfile=$_journey_pending_cidfile status=0 failed=0 + _journey_pending_container='' + _journey_pending_cidfile='' + [[ -n "$name" ]] || return 0 + if [[ -e "$cidfile" ]]; then + if ! rm -- "$cidfile"; then + journey__cleanup_problem "cannot delete $cidfile" + failed=1 + fi + else + journey__container_state "$name" || status=$? + case "$status" in + 0) journey__say "docker run of $name was interrupted after Docker created it" ;; + 1) return 0 ;; + *) + journey__cleanup_problem "cannot tell whether the interrupted docker run created $name; remove it by that name if it exists" + return 1 + ;; + esac + fi + if ! printf '%s\n' "$name" >>"$JOURNEY_OUT/containers.txt"; then + journey__cleanup_problem "cannot record container $name; remove it by that name" + failed=1 + fi + return "$failed" +} + +# journey_container_run ROLE [--port PORT]... [--secret-env ENV=SECRET]... +# [docker run options]... -- IMAGE@sha256:DIGEST [ARGUMENTS]... +# Starts a detached container named by journey_container_name on the default +# bridge network, publishing each PORT on 127.0.0.1 only. Refused options: +# any network, publish, privileged, name, detach, cidfile, pull, rm or mount +# option, and a named volume (cleanup removes anonymous volumes only). +journey_container_run() { + local role=${1:-} name image cidfile raw_out raw_err status=0 port host spec volume_source + local -a options=() publish=() envs=() + journey__check_id "container role" "$role" + shift + while [[ $# -gt 0 && "$1" != -- ]]; do + case "$1" in + --port) + [[ $# -ge 2 && "$2" =~ ^[0-9]+(/(tcp|udp))?$ ]] || journey__script_error "--port needs a container port such as 5432 or 5432/tcp" + port=$2 + if [[ -n "$JOURNEY_PORT_BASE" ]]; then + host=$((JOURNEY_PORT_BASE + _journey_port_count)) + _journey_port_count=$((_journey_port_count + 1)) + publish+=(--publish "127.0.0.1:$host:$port") + else + publish+=(--publish "127.0.0.1::$port") + fi + shift 2 + ;; + --secret-env) + [[ $# -ge 2 ]] || journey__script_error "--secret-env needs ENV=secret-name" + envs+=("$2") + shift 2 + ;; + --network | --network=* | --net | --net=* | -p | -p?* | --publish | --publish=* | -P | --publish-all | \ + --privileged | --name | --name=* | -d | --detach | --cidfile | --cidfile=* | --pull | --pull=* | \ + --rm | --mount | --mount=*) + journey__script_error "journey_container_run refuses $1: the library owns networking, ports, names, cleanup and pulls" + ;; + -v | --volume) + [[ $# -ge 2 ]] || journey__script_error "$1 needs a value" + volume_source=${2%%:*} + [[ "$volume_source" == /* ]] || journey__script_error "volume $2 is a named volume, which cleanup would leave behind; use a bind mount from an absolute path" + options+=("$1" "$2") + shift 2 + ;; + -v?* | --volume=*) + journey__script_error "write the volume option $1 as two words (-v SOURCE:TARGET)" + ;; + *) + options+=("$1") + shift + ;; + esac + done + [[ "${1:-}" == -- ]] || journey__script_error "journey_container_run: put -- before the image" + shift + image=${1:-} + [[ "$image" =~ $_journey_re_digest ]] || journey__script_error "image '$image' is not pinned by digest (NAME:TAG@sha256:...)" + shift + journey_container_name "$role" name + status=0 + journey__container_state "$name" || status=$? + case "$status" in + 0) journey_harness_failure "a container named $name already exists; the journey never adopts one, and it was left untouched" ;; + 1) status=0 ;; + *) journey_harness_failure "cannot tell whether container $name exists" ;; + esac + if [[ ${#envs[@]} -gt 0 ]]; then + journey_secret_env_file "container-$role" spec "${envs[@]}" + options+=(--env-file "$spec") + fi + if [[ $JOURNEY_TIMED -eq 1 ]]; then + options+=(--pull never) + fi + journey__raw_path cidfile "$name.cid" + journey__raw_path raw_out "$role.run.stdout" + journey__raw_path raw_err "$role.run.stderr" + _journey_pending_container=$name + _journey_pending_cidfile=$cidfile + docker run --detach --name "$name" --cidfile "$cidfile" \ + --label "registry.journey.run=$JOURNEY_RUN_ID" \ + ${publish[@]+"${publish[@]}"} ${options[@]+"${options[@]}"} \ + "$image" "$@" <"/dev/null" >"$raw_out" 2>"$raw_err" || status=$? + if [[ -e "$cidfile" ]]; then + journey__record_container "$name" + journey__discard "$cidfile" + fi + _journey_pending_container='' + _journey_pending_cidfile='' + _journey_image_lines+="$role"$'\t'"$name"$'\t'"$image"$'\n' + journey__redact_into "$raw_err" "$JOURNEY_OUT/containers/$role.run.stderr" + journey__discard "$raw_out" + journey__write_run_json || journey_harness_failure "cannot write run.json" + if [[ $status -ne 0 ]]; then + journey_harness_failure "docker run for container $name failed (exit status $status); see $JOURNEY_OUT/containers/$role.run.stderr" + fi +} + +# journey_container_port ROLE PORT VAR: the host port Docker published PORT +# on. Anything but a 127.0.0.1 address is refused. +journey_container_port() { + local _jr_role=${1:-} _jr_port=${2:-} _jr_target=${3:-} _jcn_name _jr_answer _jr_line _jr_host='' + journey__check_var "$_jr_target" + [[ "$_jr_port" =~ ^[0-9]+(/(tcp|udp))?$ ]] || journey__script_error "journey_container_port needs a container port" + [[ "$_jr_port" == */* ]] || _jr_port="$_jr_port/tcp" + journey_container_name "$_jr_role" _jcn_name + _jr_answer="$(docker port "$_jcn_name" "$_jr_port")" || journey_harness_failure "docker port $_jcn_name $_jr_port failed" + while IFS= read -r _jr_line; do + _jr_line=${_jr_line//[[:space:]]/} + if [[ "$_jr_line" =~ ^127\.0\.0\.1:([0-9]+)$ ]] && [[ "${BASH_REMATCH[1]}" != 0 ]]; then + _jr_host=${BASH_REMATCH[1]} + break + fi + done <<<"$_jr_answer" + [[ -n "$_jr_host" ]] || journey_harness_failure "Docker did not publish $_jr_port of $_jcn_name on 127.0.0.1 (it answered: ${_jr_answer//$_journey_nl/ }); refusing to use it" + printf -v "$_jr_target" '%s' "$_jr_host" +} + +# journey_container_address ROLE VAR: the container's address on the default +# bridge network. +journey_container_address() { + local _jr_role=${1:-} _jr_target=${2:-} _jcn_name _jr_address + journey__check_var "$_jr_target" + journey_container_name "$_jr_role" _jcn_name + _jr_address="$(docker inspect --format '{{.NetworkSettings.IPAddress}}' "$_jcn_name")" || + journey_harness_failure "docker inspect could not read the address of $_jcn_name" + [[ "$_jr_address" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || + journey_harness_failure "container $_jcn_name has no bridge address (docker inspect answered '$_jr_address')" + printf -v "$_jr_target" '%s' "$_jr_address" +} + +# journey_container_logs ROLE: save the container's log, redacted, under +# /containers/. +journey_container_logs() { + local role=${1:-} name raw_out raw_err status=0 + journey_container_name "$role" name + journey__raw_path raw_out "$role.log.stdout" + journey__raw_path raw_err "$role.log.stderr" + docker logs "$name" "$raw_out" 2>"$raw_err" || status=$? + journey__redact_into "$raw_out" "$JOURNEY_OUT/containers/$role.log.stdout" + journey__redact_into "$raw_err" "$JOURNEY_OUT/containers/$role.log.stderr" + [[ $status -eq 0 ]] || journey__say "docker logs $name failed (exit status $status)" + return "$status" +} + +# journey_container_wait ROLE SECONDS -- PROBE...: wait until PROBE succeeds. +# A container that stops, or is not ready in time, is a harness failure; its +# log is saved first. Probe output is not saved: this is setup, not a step. +journey_container_wait() { + local role=${1:-} seconds=${2:-} name running deadline + [[ "$seconds" =~ $_journey_re_posint ]] || journey__script_error "journey_container_wait needs a number of seconds" + shift 2 + [[ "${1:-}" == -- ]] || journey__script_error "journey_container_wait: put -- before the probe" + shift + [[ $# -gt 0 ]] || journey__script_error "journey_container_wait needs a probe command" + journey_container_name "$role" name + deadline=$((SECONDS + seconds)) + while :; do + running="$(docker inspect --format '{{.State.Running}}' "$name")" || + journey_harness_failure "docker inspect could not read the state of $name" + if [[ "$running" != true ]]; then + journey_container_logs "$role" || : + journey_harness_failure "container $name stopped before it was ready; its log is under $JOURNEY_OUT/containers/" + fi + if "$@" /dev/null 2>&1; then + return 0 + fi + if ((SECONDS >= deadline)); then + journey_container_logs "$role" || : + journey_harness_failure "container $name was not ready within $seconds seconds; its log is under $JOURNEY_OUT/containers/" + fi + sleep 1 + done +} + +# journey_check_absent NAME...: report any container that still exists after a +# product's own cleanup (for example `rstack dev stop`). A leftover is named, +# recorded in run.json and never removed. Returns 1 when one exists. +journey_check_absent() { + local name state status=0 + for name in "$@"; do + state=0 + journey__container_state "$name" || state=$? + case "$state" in + 0) + journey__say "leftover container $name still exists; it was not created by this journey, so it is reported and not removed" + _journey_leftovers+="$name"$'\n' + status=1 + ;; + 1) ;; + *) status=1 ;; + esac + done + return "$status" +} + +# journey_take_over_run DIR: make this run responsible for the containers and +# secrets of an earlier run of the same prefix that ended with --keep, so this +# run's cleanup removes them and its redaction knows the secrets. +journey_take_over_run() { + local directory=${1:-} prefix run journey name file + [[ -d "$directory" ]] || journey_usage_error "$directory is not a run directory" + directory="$(CDPATH='' cd -- "$directory" && pwd -P)" || journey_usage_error "cannot resolve $directory" + [[ -f "$directory/run.json" && -f "$directory/kept" && -f "$directory/containers.txt" ]] || + journey_usage_error "$directory is not a run that ended with --keep" + prefix="$(jq -r '.containerPrefix' "$directory/run.json")" || journey_usage_error "cannot read $directory/run.json" + run="$(jq -r '.runId' "$directory/run.json")" || journey_usage_error "cannot read $directory/run.json" + journey="$(jq -r '.journey' "$directory/run.json")" || journey_usage_error "cannot read $directory/run.json" + [[ "$prefix" == "$JOURNEY_CONTAINER_PREFIX" ]] || + journey_usage_error "$directory used container prefix $prefix, this run uses $JOURNEY_CONTAINER_PREFIX" + while IFS= read -r name || [[ -n "$name" ]]; do + [[ -n "$name" ]] || continue + [[ "$name" == "$prefix-$journey-$run-"* && "$name" =~ $_journey_re_container ]] || + journey_usage_error "$directory/containers.txt lists $name, which that run did not name" + journey__record_container "$name" + done <"$directory/containers.txt" + if [[ -d "$directory/secrets" ]]; then + for file in "$directory/secrets"/*; do + [[ -f "$file" ]] || continue + case "${file##*/}" in + *.env | cookies-*) journey__own_secret_file "$file" '' ;; + *) journey__own_secret_file "$file" "${file##*/}" ;; + esac + done + _journey_secret_dirs+=("$directory/secrets") + fi + _journey_taken_over=$directory + journey__write_run_json || journey_harness_failure "cannot write run.json" +} + +# --------------------------------------------------------------------------- +# Cells and steps + +# journey_workdir PRODUCT VAR: /work/PRODUCT, created on first use. Files +# a reader writes go here; it is kept for promote and not scanned as output. +journey_workdir() { + local _jr_product=${1:-} _jr_target=${2:-} + journey__check_id product "$_jr_product" + journey__check_var "$_jr_target" + mkdir -p -- "$JOURNEY_OUT/work/$_jr_product" || journey_harness_failure "cannot create $JOURNEY_OUT/work/$_jr_product" + printf -v "$_jr_target" '%s' "$JOURNEY_OUT/work/$_jr_product" +} + +# journey_cell_begin PRODUCT: start the cell of PRODUCT in this journey. +journey_cell_begin() { + local product=${1:-} + [[ $_jc_open -eq 0 ]] || journey__script_error "the cell of $_jc_product is still open; call journey_cell_end first" + journey__in_list "$product" "$(printf '%s\n' "${JOURNEY_PRODUCTS[@]}")" || journey__script_error "product $product is not selected for this run" + ! journey__in_list "$product" "$_journey_done_cells" || journey__script_error "the cell of $product was already run" + mkdir -- "$JOURNEY_OUT/$product" || journey_harness_failure "cannot create $JOURNEY_OUT/$product" + _jc_open=1 + _jc_product=$product + _jc_failed=0 + _jc_fail_step='' + _jc_fail_code='' + _jc_unreached='' + _jc_reason='' + _jc_pending='' + _jc_last_step='' + _jc_step_seconds=0.000 + _jc_recorded='' + _jc_assisted_steps='' + _jc_steps=0 + _jc_files=0 + _jc_lines=0 + _jc_chars=0 + _jc_doc_words=0 + _jc_idp=0 + _jc_certs=0 + _jc_refusals=0 + _jc_named=0 + _jc_assist_count=0 + _jc_seconds=0.000 + _jc_concepts='' + _jc_touched='' + _jc_blockers_json='[]' + _jc_t1_json=null + _jc_t2_json=null +} + +journey__require_cell() { + [[ $_jc_open -eq 1 ]] || journey__script_error "no cell is open; call journey_cell_begin first" +} + +journey__check_step() { + if [[ ! "$1" =~ $_journey_re_step ]] || ! journey__in_list "$1" "$_journey_steps"; then + journey__script_error "'$1' is not a step of journey $JOURNEY_NAME (the table lists: ${_journey_steps//$_journey_nl/ })" + fi +} + +journey__require_running() { + [[ $_jc_failed -eq 0 && -z "$_jc_unreached" ]] || + journey__script_error "$_jc_product already stopped at step ${_jc_fail_step:-$_jc_unreached}; a journey stops a product at its first blocker" +} + +journey__require_resolved() { + [[ -z "$_jc_pending" ]] || + journey__script_error "the command of step $_jc_pending failed and no outcome was recorded for it (journey_fail, journey_needs or journey_blocker)" +} + +journey__require_step_start() { + journey__require_cell + journey__check_step "$1" + journey__require_running + journey__require_resolved + ! journey__in_list "$1" "$_jc_recorded" || journey__script_error "step $1 of $_jc_product was already recorded" +} + +journey__declare_concepts() { + local rest="$1," concept + [[ -n "$1" ]] || return 0 + while [[ -n "$rest" ]]; do + concept=${rest%%,*} + rest=${rest#*,} + journey__in_list "$concept" "$_journey_concept_ids" || journey__script_error "concept '$concept' is not in concepts.yaml" + journey__in_list "$concept" "$_jc_concepts" || _jc_concepts+="$concept"$'\n' + done +} + +journey__count_command() { + _jc_steps=$((_jc_steps + 1)) + _jc_chars=$((_jc_chars + ${#1})) +} + +journey__output_base() { + local _jr_base="$JOURNEY_OUT/$_jc_product/$2" _jr_n=2 + if [[ -e "$_jr_base.stdout" ]]; then + while [[ -e "$_jr_base.$_jr_n.stdout" ]]; do + _jr_n=$((_jr_n + 1)) + done + _jr_base="$_jr_base.$_jr_n" + fi + printf -v "$1" '%s' "$_jr_base" +} + +journey__add_step_time() { + local seconds + journey__elapsed "$2" "$3" seconds + if [[ "$_jc_last_step" == "$1" ]]; then + journey__sum "$_jc_step_seconds" "$seconds" _jc_step_seconds + else + _jc_step_seconds=$seconds + _jc_last_step=$1 + fi + journey__sum "$_jc_seconds" "$seconds" _jc_seconds +} + +# What the reader types for a command: its base name and its arguments. +journey__typed_text() { + local text=${1##*/} argument + shift + for argument in "$@"; do + text+=" $argument" + done + _jo_typed=$text +} + +# Options every step function takes. Sets _jo_* and _jo_shift. +journey__step_options() { + _jo_cwd='' + _jo_stdin=/dev/null + _jo_timeout='' + _jo_settle=2 + _jo_concepts='' + _jo_words=0 + _jo_typed='' + _jo_typed_set=0 + _jo_shift=0 + while [[ $# -gt 0 && "$1" != -- ]]; do + [[ $# -ge 2 ]] || journey__script_error "step option $1 needs a value" + case "$1" in + --cwd) [[ -d "$2" ]] || journey__script_error "--cwd $2 is not a directory" ;; + --stdin) [[ -f "$2" ]] || journey__script_error "--stdin $2 is not a file" ;; + --timeout | --settle) [[ "$2" =~ $_journey_re_posint ]] || journey__script_error "$1 needs a whole number of seconds" ;; + --doc-words) [[ "$2" =~ $_journey_re_uint ]] || journey__script_error "--doc-words needs a count" ;; + --concepts | --typed) ;; + *) journey__script_error "unknown step option $1" ;; + esac + case "$1" in + --cwd) _jo_cwd=$2 ;; + --stdin) _jo_stdin=$2 ;; + --timeout) _jo_timeout=$2 ;; + --settle) _jo_settle=$2 ;; + --doc-words) _jo_words=$2 ;; + --concepts) _jo_concepts=$2 ;; + --typed) + _jo_typed=$2 + _jo_typed_set=1 + ;; + esac + shift 2 + _jo_shift=$((_jo_shift + 2)) + done + [[ "${1:-}" == -- ]] || journey__script_error "put -- before the step's command" + _jo_shift=$((_jo_shift + 1)) +} + +journey__begin_command() { + journey__declare_concepts "$_jo_concepts" + journey__count_command "$_jo_typed" + _jc_doc_words=$((_jc_doc_words + _jo_words)) +} + +# journey_step STEP [--cwd DIR] [--stdin FILE] [--timeout S] [--concepts A,B] +# [--doc-words N] [--typed TEXT] -- COMMAND... +# Run one command a reader would type, as part of STEP of the open cell. Its +# output is saved, redacted, as //.stdout and .stderr +# (a second command of the same step gets .2.*). Returns the command's +# exit status and records nothing: follow with journey_pass, or with +# journey_fail, journey_needs or journey_blocker when it failed. A command +# that runs past its deadline is a harness failure. +journey_step() { + local step=${1:-} base raw_out raw_err started ended status=0 timeout + [[ $# -eq 0 ]] || shift + journey__require_step_start "$step" + journey__step_options "$@" + shift "$_jo_shift" + [[ $# -gt 0 ]] || journey__script_error "step $step needs a command" + [[ $_jo_typed_set -eq 1 ]] || journey__typed_text "$@" + timeout=${_jo_timeout:-$JOURNEY_STEP_TIMEOUT} + journey__begin_command + journey__output_base base "$step" + journey__raw_path raw_out "$step.stdout" + journey__raw_path raw_err "$step.stderr" + journey__now started + journey__run_command "$timeout" "$_jo_cwd" "$_jo_stdin" "$raw_out" "$raw_err" "$@" || status=$? + journey__now ended + journey__redact_into "$raw_out" "$base.stdout" + journey__redact_into "$raw_err" "$base.stderr" + if [[ $_journey_run_timed_out -eq 1 ]]; then + journey_harness_failure "step $step of $_jc_product did not finish within $timeout seconds; its output is in $base.stdout and $base.stderr" + fi + journey__add_step_time "$step" "$started" "$ended" + JOURNEY_STEP_STATUS=$status + JOURNEY_STEP_STDOUT="$base.stdout" + JOURNEY_STEP_STDERR="$base.stderr" + if [[ $status -ne 0 ]]; then + _jc_pending=$step + fi + return "$status" +} + +journey__http_headers() { + local _jh_header + if [[ -n "$1" ]]; then + printf 'Authorization: Bearer %s\n' "${!1}" + fi + shift + for _jh_header in "$@"; do + printf '%s\n' "$_jh_header" + done +} + +# journey_http STEP [--bearer VAR] [--header 'Name: value']... [--form K=V]... +# [--form-secret K=SECRET]... [--data-file FILE] [--cookie-jar NAME] +# [--location] [--capture FILTER VAR]... [--capture-secret FILTER VAR]... +# [--timeout S] [--concepts A,B] [--doc-words N] [--typed TEXT] METHOD URL +# One HTTP request as part of STEP. The token in VAR and every --form-secret +# value reach curl through a file descriptor or a file path, never as an +# argument. Saves .http (status line and response headers), .stdout +# (body) and .stderr, all redacted; request headers are never saved. Sets +# JOURNEY_HTTP_STATUS (000 when no answer came) and JOURNEY_HTTP_PROBLEM_CODE +# (the body's "code" member, or empty). --capture and --capture-secret set VAR +# from a jq filter on a 2xx body; --capture-secret also registers the value +# for redaction. Returns 0 for a 2xx answer whose captures all succeeded. +journey_http() { + local _jh_step=${1:-} _jh_bearer='' _jh_cookie='' _jh_location=0 _jh_data_file='' _jh_timeout=30 + local _jh_method _jh_url _jh_base _jh_raw_headers _jh_raw_body _jh_raw_err _jh_raw_status + local _jh_started _jh_ended _jh_curl_status=0 _jh_code _jh_problem _jh_value _jh_result=0 _jh_index _jh_path + local -a _jh_headers=() _jh_data=() _jh_capture_filters=() _jh_capture_vars=() _jh_capture_secret=() _jh_args=() + [[ $# -eq 0 ]] || shift + journey__require_step_start "$_jh_step" + _jo_concepts='' + _jo_words=0 + _jo_typed='' + _jo_typed_set=0 + while [[ $# -gt 0 && "$1" == --* ]]; do + case "$1" in + --location) + _jh_location=1 + shift + continue + ;; + --capture | --capture-secret) + [[ $# -ge 3 ]] || journey__script_error "$1 needs a jq filter and a variable name" + journey__check_var "$3" + [[ "$3" != _jh_* ]] || journey__script_error "'$3' is not a variable name journey_http can set (names starting with _jh_ are its own)" + _jh_capture_filters+=("$2") + _jh_capture_vars+=("$3") + if [[ "$1" == --capture-secret ]]; then _jh_capture_secret+=(1); else _jh_capture_secret+=(0); fi + shift 3 + continue + ;; + esac + [[ $# -ge 2 ]] || journey__script_error "$1 needs a value" + case "$1" in + --bearer) + journey__check_var "$2" + [[ "$2" != _jh_* ]] || journey__script_error "'$2' is not a variable name journey_http can read (names starting with _jh_ are its own)" + [[ -n "${!2-}" ]] || journey__script_error "the bearer token variable $2 is empty" + _jh_bearer=$2 + ;; + --header) + [[ "$2" =~ $_journey_re_header ]] || journey__script_error "a header is 'Name: value', not '$2'" + [[ ! "$2" =~ $_journey_re_credential_header ]] || journey__script_error "pass a token with --bearer VAR, never as a header" + _jh_headers+=("$2") + ;; + --form) + [[ "$2" == ?*=* ]] || journey__script_error "--form needs KEY=VALUE" + _jh_data+=(--data-urlencode "$2") + ;; + --form-secret) + [[ "$2" == ?*=* ]] || journey__script_error "--form-secret needs KEY=secret-name" + journey_secret_path "${2#*=}" _jh_path + _jh_data+=(--data-urlencode "${2%%=*}@$_jh_path") + ;; + --data-file) + [[ -f "$2" ]] || journey__script_error "--data-file $2 is not a file" + _jh_data_file=$2 + ;; + --cookie-jar) + journey__check_id "cookie jar" "$2" + _jh_cookie="$JOURNEY_OUT/secrets/cookies-$2" + if [[ ! -e "$_jh_cookie" ]]; then + ( + umask 077 + : >"$_jh_cookie" + ) || journey_harness_failure "cannot create cookie jar $2" + journey__own_secret_file "$_jh_cookie" '' + fi + ;; + --timeout) + [[ "$2" =~ $_journey_re_posint ]] || journey__script_error "--timeout needs a whole number of seconds" + _jh_timeout=$2 + ;; + --concepts) _jo_concepts=$2 ;; + --doc-words) + [[ "$2" =~ $_journey_re_uint ]] || journey__script_error "--doc-words needs a count" + _jo_words=$2 + ;; + --typed) + _jo_typed=$2 + _jo_typed_set=1 + ;; + *) journey__script_error "journey_http: unknown option $1" ;; + esac + shift 2 + done + [[ $# -eq 2 ]] || journey__script_error "journey_http needs METHOD and URL after its options" + _jh_method=$1 + _jh_url=$2 + [[ "$_jh_method" =~ ^[A-Z]+$ ]] || journey__script_error "'$_jh_method' is not an HTTP method" + [[ "$_jh_url" =~ ^https?://[^[:space:]]+$ ]] || journey__script_error "'$_jh_url' is not an http or https URL" + if [[ $_jo_typed_set -eq 0 ]]; then + _jo_typed="curl -X $_jh_method $_jh_url" + [[ -z "$_jh_bearer" ]] || _jo_typed+=' -H "Authorization: Bearer $TOKEN"' + fi + journey__begin_command + journey__output_base _jh_base "$_jh_step" + journey__raw_path _jh_raw_headers "$_jh_step.http" + journey__raw_path _jh_raw_body "$_jh_step.stdout" + journey__raw_path _jh_raw_err "$_jh_step.stderr" + journey__raw_path _jh_raw_status "$_jh_step.status" + _jh_args=(--silent --show-error --max-time "$_jh_timeout" --connect-timeout 10 -X "$_jh_method" + --dump-header "$_jh_raw_headers" --output "$_jh_raw_body" --write-out '%{http_code}') + [[ $_jh_location -eq 0 ]] || _jh_args+=(--location) + [[ -z "$_jh_cookie" ]] || _jh_args+=(--cookie "$_jh_cookie" --cookie-jar "$_jh_cookie") + [[ -z "$_jh_data_file" ]] || _jh_args+=(--data-binary "@$_jh_data_file") + journey__now _jh_started + curl "${_jh_args[@]}" ${_jh_data[@]+"${_jh_data[@]}"} \ + -H "@"<(journey__http_headers "$_jh_bearer" ${_jh_headers[@]+"${_jh_headers[@]}"}) \ + "$_jh_url" "$_jh_raw_status" 2>"$_jh_raw_err" || _jh_curl_status=$? + journey__now _jh_ended + _jh_code="$(<"$_jh_raw_status")" + [[ "$_jh_code" =~ ^[0-9]{3}$ ]] || _jh_code=000 + [[ -f "$_jh_raw_headers" ]] || : >"$_jh_raw_headers" + [[ -f "$_jh_raw_body" ]] || : >"$_jh_raw_body" + JOURNEY_HTTP_STATUS=$_jh_code + JOURNEY_HTTP_CAPTURE_FAILED='' + # A body that is not a JSON object has no problem code; that is an answer, + # not an error, so jq's refusal is not reported. + _jh_problem="$(jq -r 'if type == "object" and (.code | type) == "string" then .code else empty end' "$_jh_raw_body" 2>/dev/null)" || _jh_problem='' + JOURNEY_HTTP_PROBLEM_CODE=$_jh_problem + if [[ $_jh_curl_status -ne 0 || ! "$_jh_code" =~ ^2 ]]; then + _jh_result=1 + else + for ((_jh_index = 0; _jh_index < ${#_jh_capture_filters[@]}; _jh_index++)); do + if ! _jh_value="$(jq -er "${_jh_capture_filters[$_jh_index]}" "$_jh_raw_body")" || [[ -z "$_jh_value" ]]; then + JOURNEY_HTTP_CAPTURE_FAILED=${_jh_capture_filters[$_jh_index]} + _jh_result=1 + break + fi + printf -v "${_jh_capture_vars[$_jh_index]}" '%s' "$_jh_value" + if [[ "${_jh_capture_secret[$_jh_index]}" == 1 ]]; then + journey_secret_register "$_jh_step-capture" "${_jh_capture_vars[$_jh_index]}" + fi + done + fi + journey__redact_into "$_jh_raw_headers" "$_jh_base.http" + journey__redact_into "$_jh_raw_body" "$_jh_base.stdout" + journey__redact_into "$_jh_raw_err" "$_jh_base.stderr" + journey__discard "$_jh_raw_status" + journey__add_step_time "$_jh_step" "$_jh_started" "$_jh_ended" + JOURNEY_STEP_STATUS=$_jh_result + JOURNEY_STEP_STDOUT="$_jh_base.stdout" + JOURNEY_STEP_STDERR="$_jh_base.stderr" + JOURNEY_HTTP_HEADERS="$_jh_base.http" + if [[ $_jh_result -ne 0 ]]; then + _jc_pending=$_jh_step + fi + return "$_jh_result" +} + +journey__process_index() { + local _jr_index + for ((_jr_index = 0; _jr_index < ${#_journey_process_keys[@]}; _jr_index++)); do + if [[ "${_journey_process_keys[$_jr_index]}" == "$2" && -n "${_journey_process_pids[$_jr_index]}" ]]; then + printf -v "$1" '%s' "$_jr_index" + return 0 + fi + done + return 1 +} + +journey__refresh_process_logs() { + local index=$1 + journey_redact "${_journey_process_raws[$index]}.stdout" "${_journey_process_bases[$index]}.stdout" && + journey_redact "${_journey_process_raws[$index]}.stderr" "${_journey_process_bases[$index]}.stderr" +} + +journey__finish_process() { + local index=$1 + journey__refresh_process_logs "$index" || journey_harness_failure "cannot redact the log of ${_journey_process_keys[$index]}" + journey__discard "${_journey_process_raws[$index]}.stdout" + journey__discard "${_journey_process_raws[$index]}.stderr" + _journey_process_pids[index]='' +} + +# journey_start STEP NAME [--cwd DIR] [--stdin FILE] [--settle S] +# [--concepts A,B] [--doc-words N] [--typed TEXT] -- COMMAND... +# Start a long-running product process (a server) in the background as STEP. +# Its output is saved, redacted, as //.stdout and .stderr. +# Returns 0 when it is still running after S seconds (default 2). When it +# exits first, returns 1, sets JOURNEY_PROCESS_STATUS and leaves the step for +# journey_fail. Cleanup stops every process still running. +journey_start() { + local step=${1:-} name=${2:-} base raw started ended pid index attempts=0 status=0 + [[ $# -lt 2 ]] || shift 2 + journey__require_step_start "$step" + journey__check_id "process name" "$name" + ! journey__process_index index "$_jc_product/$name" || journey__script_error "process $name of $_jc_product is already running" + journey__step_options "$@" + shift "$_jo_shift" + [[ $# -gt 0 ]] || journey__script_error "step $step needs a command" + [[ $_jo_typed_set -eq 1 ]] || journey__typed_text "$@" + journey__begin_command + journey__output_base base "$step" + journey__raw_path raw "$step.process" + : >"$raw.stdout" + : >"$raw.stderr" + _journey_raw_files+=("$raw.stdout" "$raw.stderr") + journey__now started + ( + if [[ -n "$_jo_cwd" ]]; then + cd -- "$_jo_cwd" || exit 126 + fi + exec "$@" + ) <"$_jo_stdin" >"$raw.stdout" 2>"$raw.stderr" & + pid=$! + _journey_process_keys+=("$_jc_product/$name") + _journey_process_pids+=("$pid") + _journey_process_bases+=("$base") + _journey_process_raws+=("$raw") + index=$((${#_journey_process_pids[@]} - 1)) + printf '%s\t%s\t%s\n' "$pid" "$_jc_product" "$name" >>"$JOURNEY_OUT/processes.txt" || + journey_harness_failure "cannot record process $name in processes.txt" + while ((attempts < _jo_settle * 5)) && journey__process_alive "$pid"; do + sleep 0.2 + attempts=$((attempts + 1)) + done + journey__now ended + journey__add_step_time "$step" "$started" "$ended" + JOURNEY_STEP_STDOUT="$base.stdout" + JOURNEY_STEP_STDERR="$base.stderr" + if journey__process_alive "$pid"; then + JOURNEY_PROCESS_STATUS='' + journey__refresh_process_logs "$index" || journey_harness_failure "cannot redact the log of $name" + return 0 + fi + wait "$pid" || status=$? + JOURNEY_PROCESS_STATUS=$status + journey__finish_process "$index" + _jc_pending=$step + return 1 +} + +# journey_ready STEP NAME [--timeout S] [--cwd DIR] [--concepts A,B] +# [--doc-words N] [--typed TEXT] -- PROBE... +# Poll PROBE once a second until it succeeds while process NAME keeps running, +# for up to S seconds (default 60). The last probe's output is saved. Returns +# 1 when the process exits (JOURNEY_PROCESS_STATUS is set) or time runs out. +journey_ready() { + local step=${1:-} name=${2:-} index base raw_out raw_err started ended deadline remaining status=1 attempt pid + [[ $# -lt 2 ]] || shift 2 + journey__require_step_start "$step" + journey__process_index index "$_jc_product/$name" || journey__script_error "no running process $name for $_jc_product" + journey__step_options "$@" + shift "$_jo_shift" + [[ $# -gt 0 ]] || journey__script_error "step $step needs a probe command" + [[ $_jo_typed_set -eq 1 ]] || journey__typed_text "$@" + journey__begin_command + journey__output_base base "$step" + journey__raw_path raw_out "$step.stdout" + journey__raw_path raw_err "$step.stderr" + : >"$raw_out" + : >"$raw_err" + pid=${_journey_process_pids[$index]} + JOURNEY_PROCESS_STATUS='' + journey__now started + deadline=$((SECONDS + ${_jo_timeout:-60})) + while :; do + if ! journey__process_alive "$pid"; then + attempt=0 + wait "$pid" || attempt=$? + JOURNEY_PROCESS_STATUS=$attempt + journey__finish_process "$index" + break + fi + remaining=$((deadline - SECONDS)) + ((remaining > 0)) || break + attempt=0 + journey__run_command "$remaining" "$_jo_cwd" /dev/null "$raw_out" "$raw_err" "$@" || attempt=$? + if [[ $attempt -eq 0 && $_journey_run_timed_out -eq 0 ]]; then + status=0 + break + fi + sleep 1 + done + journey__now ended + journey__redact_into "$raw_out" "$base.stdout" + journey__redact_into "$raw_err" "$base.stderr" + journey__add_step_time "$step" "$started" "$ended" + JOURNEY_STEP_STDOUT="$base.stdout" + JOURNEY_STEP_STDERR="$base.stderr" + if [[ $status -ne 0 ]]; then + _jc_pending=$step + fi + return "$status" +} + +# journey_stop STEP NAME [--timeout S] [--concepts A,B] [--typed TEXT] +# Stop process NAME as a reader would (SIGTERM), waiting up to S seconds +# (default 30) before SIGKILL. Sets JOURNEY_PROCESS_STATUS. Returns 1 when the +# process had to be killed. +journey_stop() { + local step=${1:-} name=${2:-} index started ended + [[ $# -lt 2 ]] || shift 2 + journey__require_step_start "$step" + journey__process_index index "$_jc_product/$name" || journey__script_error "no running process $name for $_jc_product" + journey__step_options "$@" -- + shift "$((_jo_shift - 1))" + [[ $# -eq 0 ]] || journey__script_error "journey_stop takes options only, not '$*'" + [[ $_jo_typed_set -eq 1 ]] || _jo_typed='^C' + journey__begin_command + journey__now started + journey__terminate "${_journey_process_pids[$index]}" "${_jo_timeout:-30}" + journey__now ended + JOURNEY_PROCESS_STATUS=$_journey_terminate_status + journey__finish_process "$index" + journey__add_step_time "$step" "$started" "$ended" + if [[ $_journey_terminate_killed -eq 1 ]]; then + _jc_pending=$step + return 1 + fi + return 0 +} + +# journey_process_running NAME: true while process NAME of the open cell runs. +journey_process_running() { + local index + journey__require_cell + journey__process_index index "$_jc_product/${1:-}" || return 1 + journey__process_alive "${_journey_process_pids[$index]}" +} + +# journey_process_log NAME VAR: refresh the redacted log of process NAME of +# the open cell and set VAR to its stderr file. +journey_process_log() { + local _jr_name=${1:-} _jr_target=${2:-} _jpl_index + journey__check_var "$_jr_target" + journey__require_cell + journey__process_index _jpl_index "$_jc_product/$_jr_name" || journey__script_error "no running process $_jr_name for $_jc_product" + journey__refresh_process_logs "$_jpl_index" || journey_harness_failure "cannot redact the log of $_jr_name" + printf -v "$_jr_target" '%s' "${_journey_process_bases[$_jpl_index]}.stderr" +} + +journey__work_path() { + [[ "$1" == "$JOURNEY_OUT/work/"* && "$1" != *"/../"* && "$1" != */.. ]] || + journey__script_error "a file the reader writes must be under $JOURNEY_OUT/work/, not $1" + [[ -d "${1%/*}" ]] || journey__script_error "the folder of $1 does not exist" +} + +journey__touch_file() { + journey__in_list "$1" "$_jc_touched" || { + _jc_touched+="$1"$'\n' + _jc_files=$((_jc_files + 1)) + } +} + +# journey_write_file PATH [--concepts A,B] < CONTENT: a file the reader +# creates by hand. Counts the file, its lines and its characters. +journey_write_file() { + local path=${1:-} counts + [[ $# -eq 0 ]] || shift + journey__require_cell + journey__require_running + journey__require_resolved + journey__work_path "$path" + if [[ "${1:-}" == --concepts ]]; then + [[ $# -ge 2 ]] || journey__script_error "--concepts needs a list" + journey__declare_concepts "$2" + elif [[ $# -gt 0 ]]; then + journey__script_error "journey_write_file: unknown option $1" + fi + counts="$(perl -e ' + local $/; my $text = ; $text = "" unless defined $text; + open my $out, ">:raw", $ARGV[0] or die "cannot write $ARGV[0]: $!\n"; + print {$out} $text; close $out or die "cannot write $ARGV[0]: $!\n"; + my $lines = () = $text =~ /\n/g; $lines++ if length($text) && $text !~ /\n\z/; + printf "%d %d\n", $lines, length $text;' "$path")" || journey_harness_failure "cannot write $path" + journey__touch_file "$path" + _jc_lines=$((_jc_lines + ${counts% *})) + _jc_chars=$((_jc_chars + ${counts#* })) +} + +# journey_edit_file PATH SEARCH REPLACE [--concepts A,B]: an edit the reader +# makes by hand. SEARCH must occur exactly once. Counts the file, the lines of +# REPLACE and its characters. +journey_edit_file() { + local path=${1:-} search=${2:-} replace=${3:-} counts + [[ $# -ge 3 ]] || journey__script_error "journey_edit_file needs PATH SEARCH REPLACE" + shift 3 + journey__require_cell + journey__require_running + journey__require_resolved + journey__work_path "$path" + [[ -f "$path" ]] || journey__script_error "cannot edit $path: it does not exist" + [[ -n "$search" ]] || journey__script_error "journey_edit_file needs the text to replace" + if [[ "${1:-}" == --concepts ]]; then + [[ $# -eq 2 ]] || journey__script_error "--concepts needs one list" + journey__declare_concepts "$2" + elif [[ $# -gt 0 ]]; then + journey__script_error "journey_edit_file: unknown option $1" + fi + counts="$(perl -e ' + my ($path, $search, $replace) = @ARGV; + open my $in, "<:raw", $path or die "cannot read $path: $!\n"; + local $/; my $text = <$in>; close $in; $text = "" unless defined $text; + my $count = () = $text =~ /\Q$search\E/g; + die "the text to replace occurs $count times in $path; it must occur once\n" if $count != 1; + substr($text, index($text, $search), length $search) = $replace; + open my $out, ">:raw", $path or die "cannot write $path: $!\n"; + print {$out} $text; close $out or die "cannot write $path: $!\n"; + my $lines = () = $replace =~ /\n/g; $lines++ if length($replace) && $replace !~ /\n\z/; + printf "%d %d\n", $lines, length $replace;' "$path" "$search" "$replace")" || + journey__script_error "cannot edit $path" + journey__touch_file "$path" + _jc_lines=$((_jc_lines + ${counts% *})) + _jc_chars=$((_jc_chars + ${counts#* })) +} + +journey__seconds_for() { + if [[ "$_jc_last_step" == "$1" ]]; then + printf -v "$2" '%s' "$_jc_step_seconds" + else + printf -v "$2" '%s' 0.000 + fi +} + +journey__record_line() { + printf '%s\t%s\t%s\t%s\t%s\n' "$_jc_product" "$1" "$2" "$3" "$4" >>"$JOURNEY_OUT/cells.tsv" || + journey_harness_failure "cannot append to cells.tsv" +} + +journey__check_code() { + local code=$1 kind suffix stage + if [[ "$code" =~ $_journey_re_code_journey ]]; then + kind=${BASH_REMATCH[1]} + suffix=${BASH_REMATCH[2]} + jq -e --arg kind "$kind" --arg suffix "$suffix" \ + 'any((.journeyCodeSuffixes[$kind] // [])[]; . == $suffix)' <<<"$_journey_expected_json" >/dev/null || + journey__script_error "code $code: journeyCodeSuffixes.$kind in the table does not list $suffix" + elif [[ "$code" =~ $_journey_re_code_http ]]; then + stage=${BASH_REMATCH[1]} + jq -e --arg stage "$stage" 'any((.authenticationStages // [])[]; . == $stage)' <<<"$_journey_expected_json" >/dev/null || + journey__script_error "code $code: $stage is not an authentication stage the table lists" + elif [[ ! "$code" =~ $_journey_re_code_product ]]; then + journey__script_error "code '$code' has none of the forms journey.., http.., product." + fi +} + +journey__is_refusal() { + [[ "$1" == http.* || "$1" == product.* ]] +} + +# journey_pass STEP: STEP of the open cell passed. +journey_pass() { + local step=${1:-} seconds + journey__require_cell + journey__check_step "$step" + journey__require_running + if [[ "$_jc_pending" == "$step" ]]; then + journey__script_error "the command of step $step failed; record journey_fail or journey_blocker, not journey_pass" + fi + journey__require_resolved + ! journey__in_list "$step" "$_jc_recorded" || journey__script_error "step $step of $_jc_product was already recorded" + journey__seconds_for "$step" seconds + journey__record_line "$step" pass - "$seconds" + _jc_recorded+="$step"$'\n' +} + +# journey_fail STEP CODE: the open cell stops at STEP with CODE. +journey_fail() { + local step=${1:-} code=${2:-} seconds + journey__require_cell + journey__check_step "$step" + journey__require_running + if [[ -n "$_jc_pending" && "$_jc_pending" != "$step" ]]; then + journey__require_resolved + fi + ! journey__in_list "$step" "$_jc_recorded" || journey__script_error "step $step of $_jc_product was already recorded" + journey__check_code "$code" + journey__seconds_for "$step" seconds + journey__record_line "$step" fail "$code" "$seconds" + _jc_recorded+="$step"$'\n' + _jc_failed=1 + _jc_fail_step=$step + _jc_fail_code=$code + _jc_pending='' + if journey__is_refusal "$code"; then + _jc_refusals=$((_jc_refusals + 1)) + fi +} + +# journey_needs STEP THING: the only way past STEP is one of the things the +# pass rule forbids; the cell stops with journey.needs.THING. +journey_needs() { + journey_fail "${1:-}" "journey.needs.${2:-}" +} + +# journey_unreached STEP REASON: the cell cannot reach STEP by design. +journey_unreached() { + local step=${1:-} reason=${2:-} + journey__require_cell + journey__check_step "$step" + journey__require_running + journey__require_resolved + [[ -n "$reason" ]] || journey__script_error "journey_unreached needs a reason" + journey__plain_text reason "$reason" + journey__record_line "$step" unreached - 0.000 + _jc_unreached=$step + _jc_reason=$reason +} + +# journey_assist_enabled NAME: true when --assist lists NAME. +journey_assist_enabled() { + [[ ",$JOURNEY_ASSISTS," == *",${1:-},"* ]] +} + +# journey_blocker STEP CODE ASSIST [ARGUMENTS]...: STEP meets a blocker CODE. +# With --assist ASSIST, the use is counted, journey_assist_ASSIST runs with +# ARGUMENTS and 0 is returned so the journey continues. Without it the cell +# stops with CODE and 1 is returned. A failing assist is a harness failure. +journey_blocker() { + local step=${1:-} code=${2:-} assist=${3:-} seconds function + journey__require_cell + journey__check_step "$step" + journey__require_running + if [[ -n "$_jc_pending" && "$_jc_pending" != "$step" ]]; then + journey__require_resolved + fi + journey__check_id assist "$assist" + journey__check_code "$code" + if ! journey_assist_enabled "$assist"; then + journey_fail "$step" "$code" + return 1 + fi + [[ $# -lt 3 ]] || shift 3 + journey__seconds_for "$step" seconds + journey__record_line "$step" assisted "$code" "$seconds" + _jc_pending='' + _jc_assisted_steps+="$step"$'\n' + _jc_assist_count=$((_jc_assist_count + 1)) + if journey__is_refusal "$code"; then + _jc_refusals=$((_jc_refusals + 1)) + fi + if [[ "$assist" == certificate ]]; then + _jc_certs=$((_jc_certs + 1)) + fi + _jc_blockers_json="$(jq -c --arg step "$step" --arg code "$code" --arg assist "$assist" \ + '. + [{step: $step, code: $code, assist: $assist}]' <<<"$_jc_blockers_json")" || + journey_harness_failure "cannot record the blocker at $step" + function="journey_assist_${assist//-/_}" + if ! "$function" "$@"; then + journey_harness_failure "assist $assist failed at step $step of $_jc_product" + fi + return 0 +} + +# journey_count COUNTER [N]: add N (default 1) to a counted quantity the +# library cannot see: identity-provider-changes, certificates, +# documentation-words, refusals or errors-that-say-what-to-change. +journey_count() { + local counter=${1:-} amount=${2:-1} + journey__require_cell + [[ "$amount" =~ $_journey_re_uint ]] || journey__script_error "journey_count needs a whole number" + case "$counter" in + identity-provider-changes) _jc_idp=$((_jc_idp + amount)) ;; + certificates) _jc_certs=$((_jc_certs + amount)) ;; + documentation-words) _jc_doc_words=$((_jc_doc_words + amount)) ;; + refusals) _jc_refusals=$((_jc_refusals + amount)) ;; + errors-that-say-what-to-change) _jc_named=$((_jc_named + amount)) ;; + *) journey__script_error "journey_count: unknown counter $counter" ;; + esac +} + +journey__counters_json() { + local _jr_json + _jr_json="$(jq -cn \ + --argjson steps "$_jc_steps" --argjson files "$_jc_files" --argjson lines "$_jc_lines" \ + --argjson characters "$_jc_chars" --argjson words "$_jc_doc_words" --argjson idp "$_jc_idp" \ + --argjson certificates "$_jc_certs" --argjson refusals "$_jc_refusals" --argjson named "$_jc_named" \ + --argjson assists "$_jc_assist_count" --argjson seconds "$_jc_seconds" \ + --arg concepts "$_jc_concepts" --arg files_list "$_jc_touched" --argjson model "$_journey_model_json" \ + '($concepts | split("\n") | map(select(length > 0))) as $c | + { + steps: $steps, filesTouched: $files, files: ($files_list | split("\n") | map(select(length > 0))), + linesWritten: $lines, charactersTyped: $characters, documentationWords: $words, + identityProviderChanges: $idp, certificatesMade: $certificates, concepts: $c, + conceptCount: ($c | length), refusalsMet: $refusals, assistsUsed: $assists, + errorsThatSayWhatToChange: $named, machineSeconds: $seconds, + readerMinutesModelled: (( + $characters / $model.typingCharactersPerMinute + + $words / $model.readingWordsPerMinute + + $lines * $model.secondsPerHandWrittenLine / 60 + + ($c | length) * $model.secondsPerConceptFirstMet / 60 + + $refusals * $model.minutesPerRefusalMet + + $assists * $model.minutesPerAssistUsed) * 100 | round / 100) + }')" || journey_harness_failure "cannot compute the counters of $_jc_product" + printf -v "$1" '%s' "$_jr_json" +} + +# journey_reached t1|t2: the open cell reached an end point of the pass rule +# (t1: the first 2xx authenticated read; t2: the hour). Snapshots the counters. +journey_reached() { + journey__require_cell + journey__require_resolved + case "${1:-}" in + t1) + [[ "$_jc_t1_json" == null ]] || journey__script_error "$_jc_product already reached t1" + journey__counters_json _jc_t1_json + ;; + t2) + [[ "$_jc_t2_json" == null ]] || journey__script_error "$_jc_product already reached t2" + journey__counters_json _jc_t2_json + ;; + *) journey__script_error "journey_reached takes t1 or t2" ;; + esac +} + +# journey_cell_end: close the open cell and write //cell.json. +# A cell that neither failed nor was unreached must have passed the journey's +# last step. +journey_cell_end() { + local outcome total + journey__require_cell + journey__require_resolved + if [[ $_jc_failed -eq 1 ]]; then + outcome=fail + elif [[ -n "$_jc_unreached" ]]; then + outcome=unreached + else + journey__in_list "$_journey_last_step" "$_jc_recorded" || journey__in_list "$_journey_last_step" "$_jc_assisted_steps" || + journey__script_error "the cell of $_jc_product ended without a failure and without its last step $_journey_last_step" + outcome=pass + if [[ $_jc_assist_count -gt 0 ]]; then + outcome=assisted + fi + fi + journey__counters_json total + jq -n \ + --arg product "$_jc_product" --arg outcome "$outcome" \ + --arg step "${_jc_fail_step:-$_jc_unreached}" --arg code "$_jc_fail_code" --arg reason "$_jc_reason" \ + --argjson blockers "$_jc_blockers_json" --argjson t1 "$_jc_t1_json" --argjson t2 "$_jc_t2_json" \ + --argjson total "$total" \ + 'def opt: if . == "" then null else . end; + { + product: $product, outcome: $outcome, step: ($step | opt), code: ($code | opt), reason: ($reason | opt), + blockers: $blockers, toT1: $t1, toT2: $t2, total: $total, + passRule: { + "steps-to-t1": $t1.steps, "files-touched-to-t1": $t1.filesTouched, + "lines-written-to-t1": $t1.linesWritten, + "identity-provider-changes": $total.identityProviderChanges, + "certificates-made": $total.certificatesMade, + "concepts-met-to-t1": $t1.conceptCount, + "reader-time-to-t1-modelled": $t1.readerMinutesModelled, + "reader-time-to-t2-modelled": $t2.readerMinutesModelled, + "machine-time-to-t1": (if $t1 == null then null else ($t1.machineSeconds / 60 * 100 | round / 100) end), + "errors-that-say-what-to-change": $total.errorsThatSayWhatToChange + } + }' >"$JOURNEY_OUT/$_jc_product/cell.json" || journey_harness_failure "cannot write the cell of $_jc_product" + _journey_done_cells+="$_jc_product"$'\n' + _jc_open=0 +} + +# --------------------------------------------------------------------------- +# End of a run + +journey__verdicts() { + local cells=$1 _jr_json + _jr_json="$(jq -n \ + --argjson cells "$cells" --argjson table "$_journey_expected_json" \ + --arg journey "$JOURNEY_NAME" --arg mode "$JOURNEY_MODE" \ + 'def rows($kind; $list): [($list // [])[] | select(.journey == $journey) | . + {kind: $kind}]; + (rows("fail"; $table.expectedFailures) + rows("unreached"; $table.unreached) + rows("pass"; $table.passes)) as $rows | + [$cells[] | . as $cell | + [$rows[] | select(.product == $cell.product)] as $match | + (if ($match | length) == 1 then ($match[0] | {kind, step: (.step // null), code: (.code // null)}) else null end) as $expected | + $cell + {expected: $expected, verdict: ( + if $mode != "ratchet" then (if $cell.outcome == "pass" then "ok" else "not-passed" end) + elif ($match | length) > 1 then "listed-twice" + elif $expected == null then "unlisted" + elif $cell.outcome == "pass" and $expected.kind == "pass" then "ok" + elif $cell.outcome == "pass" then "stale" + elif $cell.outcome == $expected.kind and $cell.step == $expected.step + and ($cell.outcome == "unreached" or $cell.code == $expected.code) then "ok" + else "mismatch" end)}]')" || journey_harness_failure "cannot compare the cells with the table" + printf -v "$2" '%s' "$_jr_json" +} + +# journey_finish: compare every cell with the mode's requirement, write +# summary.json, print one line per cell and exit with the journey's status. +journey_finish() { + local product cells verdicts rows strict='' code=0 missing='' + local -a files=() line=() + [[ $_jc_open -eq 0 ]] || journey__script_error "the cell of $_jc_product is still open at journey_finish" + for product in "${JOURNEY_PRODUCTS[@]}"; do + journey__in_list "$product" "$_journey_done_cells" || missing+=" $product" + files+=("$JOURNEY_OUT/$product/cell.json") + done + [[ -z "$missing" ]] || journey__script_error "the journey recorded no cell for:$missing" + cells="$(jq -s '.' "${files[@]}")" || journey_harness_failure "cannot read the cell files" + journey__verdicts "$cells" verdicts + jq -n --arg journey "$JOURNEY_NAME" --arg run "$JOURNEY_RUN_ID" --arg mode "$JOURNEY_MODE" \ + --argjson strict "$JOURNEY_STRICT" --arg assists "$JOURNEY_ASSISTS" --argjson cells "$verdicts" \ + '{schema: "registry.journey-summary/v1", journey: $journey, runId: $run, mode: $mode, + strict: ($strict == 1), assists: ($assists | split(",") | map(select(length > 0))), cells: $cells}' \ + >"$JOURNEY_OUT/summary.json" || journey_harness_failure "cannot write summary.json" + rows="$(jq -r '.[] | [.product, .outcome, (.step // "-"), (.code // "-"), + (if .expected == null then "not in the table" + else ([.expected.kind, .expected.step, .expected.code] | map(select(. != null)) | join(" ")) end), + .verdict] | @tsv' <<<"$verdicts")" || journey_harness_failure "cannot format the verdicts" + [[ $JOURNEY_STRICT -eq 0 ]] || strict=' (strict)' + printf '%s, %s mode%s, run %s\n' "$JOURNEY_NAME" "$JOURNEY_MODE" "$strict" "$JOURNEY_RUN_ID" + printf '%-18s %-10s %-20s %-36s %-48s %s\n' product outcome step code expected verdict + while IFS=$'\t' read -r -a line; do + printf '%-18s %-10s %-20s %-36s %-48s %s\n' "${line[0]}" "${line[1]}" "${line[2]}" "${line[3]}" "${line[4]}" "${line[5]}" + done <<<"$rows" + if [[ "$JOURNEY_MODE" == ratchet ]]; then + if jq -e 'any(.[]; .verdict == "mismatch" or .verdict == "unlisted" or .verdict == "listed-twice")' <<<"$verdicts" >/dev/null; then + code=1 + fi + if jq -e 'any(.[]; .verdict == "stale")' <<<"$verdicts" >/dev/null; then + if [[ $JOURNEY_STRICT -eq 1 ]]; then + code=1 + journey__say "a listed failure no longer fails: delete its row and add the cell to passes" + else + journey__say "warning: a listed failure no longer fails (stale row); --strict makes this an error" + fi + fi + elif jq -e 'any(.[]; .verdict != "ok")' <<<"$verdicts" >/dev/null; then + code=1 + fi + _journey_finished=1 + exit "$code" +} + +# --------------------------------------------------------------------------- +# Cleanup + +journey__cleanup_problem() { + journey__say "cleanup failure: $*" + _journey_cleanup_failures+="$*"$'\n' +} + +journey__stop_processes() { + local index pid failed=0 + if [[ -n "$_journey_watchdog_pid" ]]; then + journey__end_watchdog "$_journey_watchdog_pid" + _journey_watchdog_pid='' + fi + if [[ -n "$_journey_foreground_pid" ]]; then + journey__terminate "$_journey_foreground_pid" "$JOURNEY_KILL_GRACE" + _journey_foreground_pid='' + fi + for ((index = 0; index < ${#_journey_process_pids[@]}; index++)); do + pid=${_journey_process_pids[$index]} + [[ -n "$pid" ]] || continue + journey__terminate "$pid" "$JOURNEY_KILL_GRACE" + if [[ $_journey_terminate_killed -eq 1 ]]; then + journey__say "process ${_journey_process_keys[$index]} (pid $pid) ignored SIGTERM and was killed" + fi + if journey__refresh_process_logs "$index"; then + rm -f -- "${_journey_process_raws[$index]}.stdout" "${_journey_process_raws[$index]}.stderr" || + { + journey__cleanup_problem "cannot delete the raw log of ${_journey_process_keys[$index]}" + failed=1 + } + else + journey__cleanup_problem "cannot redact the log of ${_journey_process_keys[$index]}" + failed=1 + fi + _journey_process_pids[index]='' + done + return "$failed" +} + +journey__remove_containers() { + local name failed=0 + [[ -f "$JOURNEY_OUT/containers.txt" ]] || return 0 + while IFS= read -r name || [[ -n "$name" ]]; do + [[ -n "$name" ]] || continue + if [[ "$name" != "$JOURNEY_CONTAINER_PREFIX-"* || ! "$name" =~ $_journey_re_container ]]; then + journey__cleanup_problem "containers.txt lists $name, which this run did not name; it was not removed" + failed=1 + continue + fi + if [[ $JOURNEY_KEEP -eq 1 ]]; then + journey__say "kept container $name" + continue + fi + if docker rm --force --volumes "$name" /dev/null; then + journey__say "removed container $name" + else + journey__cleanup_problem "docker rm --force --volumes $name failed; remove it by that name" + failed=1 + fi + done <"$JOURNEY_OUT/containers.txt" + return "$failed" +} + +journey__discard_raw() { + local file failed=0 + for file in ${_journey_raw_files[@]+"${_journey_raw_files[@]}"}; do + if [[ -e "$file" ]] && ! rm -- "$file"; then + journey__cleanup_problem "cannot delete $file" + failed=1 + fi + done + if ! rmdir -- "$JOURNEY_OUT/.raw"; then + journey__cleanup_problem "$JOURNEY_OUT/.raw holds files this run did not create; it was left in place" + failed=1 + fi + return "$failed" +} + +# Scan every saved file outside secrets/, work/ and .raw/ for a registered +# secret value, a private key block or a compact JWT. Exit 1 lists findings. +_journey_perl_scan=' +use strict; +use warnings; +use File::Find; +my ($root) = @ARGV; +open my $list, "<&=", 3 or die "cannot read the secret list: $!\n"; +my @pairs; +while (my $line = <$list>) { + chomp $line; + my ($label, $value) = split /\t/, $line, 2; + push @pairs, [$label, $value] if defined $value && length $value; +} +my @findings; +find({ no_chdir => 1, wanted => sub { + my $path = $File::Find::name; + return if $path eq $root; + my $relative = substr $path, length($root) + 1; + if (-d $path && !-l $path) { + $File::Find::prune = 1 if $relative =~ m{\A(?:secrets|work|\.raw)\z}; + return; + } + return if -l $path || !-f $path; + open my $fh, "<:raw", $path or do { push @findings, "$relative: unreadable"; return }; + local $/; + my $text = <$fh>; + close $fh; + $text = "" unless defined $text; + for my $pair (@pairs) { + push @findings, "$relative: the value of secret $pair->[0]" if index($text, $pair->[1]) >= 0; + } + push @findings, "$relative: a private key block" if $text =~ /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/; + push @findings, "$relative: a compact JWT" if $text =~ /\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/; +} }, $root); +print "$_\n" for @findings; +exit(@findings ? 1 : 0); +' + +journey__scan_saved_output() { + local findings status=0 line + findings="$(perl -e "$_journey_perl_scan" "$JOURNEY_OUT" 3< <(journey__secret_lines))" || status=$? + case "$status" in + 0) _journey_secret_scan=clean ;; + 1) + _journey_secret_scan=found + while IFS= read -r line; do + journey__say "secret found in saved output: $line" + done <<<"$findings" + ;; + *) + _journey_secret_scan=found + journey__say "the scan of saved output for secrets could not run (exit status $status); the run is treated as leaking" + ;; + esac +} + +journey__dispose_secrets() { + local index file failed=0 directory + if [[ $JOURNEY_KEEP -eq 1 ]]; then + : >"$JOURNEY_OUT/kept" || { + journey__cleanup_problem "cannot write $JOURNEY_OUT/kept" + failed=1 + } + journey__say "kept the secrets in $JOURNEY_OUT/secrets (mode 0600) for a later run; they are deleted by the run that takes this one over" + return "$failed" + fi + for ((index = 0; index < ${#_journey_secret_files[@]}; index++)); do + file=${_journey_secret_files[$index]} + if [[ -e "$file" ]] && ! rm -- "$file"; then + journey__cleanup_problem "cannot delete secret file $file" + failed=1 + fi + done + for directory in ${_journey_secret_dirs[@]+"${_journey_secret_dirs[@]}"}; do + if [[ -d "$directory" ]] && ! rmdir -- "$directory"; then + journey__cleanup_problem "$directory still holds files this run did not create; it was left in place" + failed=1 + fi + done + return "$failed" +} + +journey__cleanup() { + local index failed=0 + for ((index = ${#_journey_cleanup_hooks[@]} - 1; index >= 0; index--)); do + if ! "${_journey_cleanup_hooks[$index]}"; then + journey__cleanup_problem "cleanup hook ${_journey_cleanup_hooks[$index]} failed" + failed=1 + fi + done + journey__stop_processes || failed=1 + journey__adopt_pending_container || failed=1 + journey__remove_containers || failed=1 + journey__discard_raw || failed=1 + journey__scan_saved_output + journey__dispose_secrets || failed=1 + return "$failed" +} + +# A signal during cleanup is noted and cleanup carries on, so a second Ctrl-C +# cannot leave containers behind. A handler, not an ignored signal, so the +# watchdogs cleanup starts can still trap TERM. +journey__signal_during_cleanup() { + journey__say "cleanup is running; the signal waits until it ends" +} + +journey__on_exit() { + local status=$? cleanup_status=0 + trap journey__signal_during_cleanup HUP INT TERM + trap - EXIT + set +e + if [[ $_journey_cleaned -eq 1 ]]; then + exit "$status" + fi + _journey_cleaned=1 + if [[ $_journey_finished -ne 1 ]]; then + case "$status" in + 2 | 3) ;; + 129 | 130 | 143) journey__say "interrupted (exit status $status); cleaning up" ;; + *) + _journey_harness_message="the journey script stopped before journey_finish (exit status $status)" + journey__say "harness failure: $_journey_harness_message" + status=3 + ;; + esac + fi + journey__cleanup + cleanup_status=$? + if [[ "$_journey_secret_scan" == found ]]; then + status=3 + elif [[ $cleanup_status -ne 0 && ($status -eq 0 || $status -eq 1) ]]; then + status=3 + fi + _journey_exit_status=$status + if ! journey__write_run_json end; then + journey__say "cleanup failure: cannot write $JOURNEY_OUT/run.json" + [[ $status -ne 0 ]] || status=3 + fi + exit "$status" +} diff --git a/products/platform/journeys/products.yaml b/products/platform/journeys/products.yaml new file mode 100644 index 0000000000..eeb4f36aad --- /dev/null +++ b/products/platform/journeys/products.yaml @@ -0,0 +1,191 @@ +# The product column of the acceptance journeys: every runtime binary that loads +# a runtime file on `main`, one row each. The list matches the sixteen runtime +# formats in products/platform/config-formats.yaml. +# +# tier: primary the journeys start it and walk it to a first call. +# tier: supporting it runs beside a parent product and shares that product's +# setup, so each journey records it as unreached until its +# parent's cell passes. +# +# ctl names the crate of the matching tool. It is null where the tool is a +# binary of the runtime's own crate (coordinatorctl) or where none exists. +# +# usesPostgres, verifiesTokens and rstackDevPlan describe `main`. A milestone +# that changes one edits the row in the same commit. + +schema: registry.journey-products/v1 + +# The identity provider the own-provider journey starts. The image reference is +# the one products/breg/scripts/test-issuer-portability.py pins, and the static +# check fails when the two differ. +ownProviderIssuer: + name: keycloak + image: quay.io/keycloak/keycloak:26.7.3@sha256:ff4257d0d64efbe99ed1ddfaf07765cc3c36dc7518bf8324d41961327f441c54 + +products: + - id: breg + tier: primary + binary: breg + crate: registry-breg + ctl: registry-bregctl + cargoPackages: [registry-breg, registry-bregctl] + cargoFeatures: [registry-breg/runtime] + usesPostgres: true + verifiesTokens: true + rstackDevPlan: true + - id: casework + tier: primary + binary: casework + crate: registry-casework + ctl: registry-caseworkctl + cargoPackages: [registry-casework, registry-caseworkctl] + cargoFeatures: [] + usesPostgres: true + verifiesTokens: true + rstackDevPlan: true + - id: messaging + tier: primary + binary: messaging + crate: registry-messaging + ctl: registry-messagingctl + cargoPackages: [registry-messaging, registry-messagingctl] + cargoFeatures: [] + usesPostgres: true + verifiesTokens: true + rstackDevPlan: true + - id: evidence + tier: primary + binary: evidence + crate: registry-evidence + ctl: registry-evidencectl + cargoPackages: [registry-evidence, registry-evidencectl] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: true + rstackDevPlan: true + - id: scheduling + tier: primary + binary: scheduling + crate: registry-scheduling + ctl: registry-schedulingctl + cargoPackages: [registry-scheduling, registry-schedulingctl] + cargoFeatures: [] + usesPostgres: true + verifiesTokens: true + rstackDevPlan: false + - id: documents + tier: primary + binary: documents + crate: registry-documents + ctl: registry-documentsctl + cargoPackages: [registry-documents, registry-documentsctl] + cargoFeatures: [] + usesPostgres: true + verifiesTokens: true + rstackDevPlan: false + - id: coordinator + tier: primary + binary: coordinator + crate: registry-coordinator + ctl: null + cargoPackages: [registry-coordinator] + cargoFeatures: [] + usesPostgres: true + verifiesTokens: true + rstackDevPlan: false + - id: adapter + tier: primary + binary: adapter + crate: registry-adapter + ctl: registry-adapterctl + cargoPackages: [registry-adapter, registry-adapterctl] + cargoFeatures: [] + usesPostgres: true + verifiesTokens: true + rstackDevPlan: false + - id: render + tier: primary + binary: registry-render + crate: registry-render + ctl: null + cargoPackages: [registry-render] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: true + rstackDevPlan: false + - id: discovery + tier: primary + binary: discovery + crate: registry-discovery + ctl: registry-discoveryctl + cargoPackages: [registry-discovery, registry-discoveryctl] + cargoFeatures: [registry-discovery/server] + usesPostgres: false + verifiesTokens: false + rstackDevPlan: false + - id: breg-mcp + tier: supporting + parent: breg + binary: breg-mcp + crate: registry-breg-mcp + ctl: registry-bregctl + cargoPackages: [registry-breg-mcp] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: true + rstackDevPlan: false + - id: breg-review + tier: supporting + parent: breg + binary: breg-review + crate: registry-breg-review + ctl: registry-bregctl + cargoPackages: [registry-breg-review] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: true + rstackDevPlan: false + - id: registry-mcp + tier: supporting + parent: adapter + binary: registry-mcp + crate: registry-mcp + ctl: null + cargoPackages: [registry-mcp] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: true + rstackDevPlan: false + - id: evidence-oid4vci + tier: supporting + parent: evidence + binary: evidence-oid4vci + crate: registry-evidence-oid4vci + ctl: registry-evidencectl + cargoPackages: [registry-evidence-oid4vci] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: true + rstackDevPlan: false + - id: evidence-oid4vp + tier: supporting + parent: evidence + binary: evidence-oid4vp + crate: registry-evidence-oid4vp + ctl: null + cargoPackages: [registry-evidence-oid4vp] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: true + rstackDevPlan: false + - id: adapter-job + tier: supporting + parent: adapter + binary: adapter-job + crate: registry-adapter-job + ctl: registry-adapterctl + cargoPackages: [registry-adapter-job] + cargoFeatures: [] + usesPostgres: true + verifiesTokens: false + rstackDevPlan: false diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py new file mode 100644 index 0000000000..ff3b1557ce --- /dev/null +++ b/products/platform/journeys/test_journey_tables.py @@ -0,0 +1,280 @@ +"""Static check of the acceptance journey tables. + +It reads the data files in this folder and the journey scripts if present. It +starts no container and builds no binary. Run it with PyYAML available: + + uv run --no-project --with PyYAML==6.0.2 python3 -m unittest products/platform/journeys/test_journey_tables.py + +The JOURNEY_TABLES_DIR environment variable points the test at another folder +with the same layout, which is how the test is shown to fail on a broken copy. +""" + +from __future__ import annotations + +import os +import re +import unittest +from pathlib import Path + +import yaml + +HERE = Path(__file__).resolve().parent +TABLES = Path(os.environ.get("JOURNEY_TABLES_DIR", HERE)).resolve() +REPO = HERE.parents[2] + +JOURNEYS = ("own-provider", "rstack-dev", "promote") +BASES = ("predicted", "observed") +TIERS = ("primary", "supporting") +HARD_CONDITIONS = ( + "certificate", + "token-hook-or-mapper", + "provisioning-sql", + "image-build", + "signature-verifier", + "no-refusal", +) +# A journey script may call only product binaries, docker (run, rm, port, +# inspect, logs), curl, jq and perl. Each of these is something the pass rule +# forbids a reader to do, so only lib-assists.sh may use it. +FORBIDDEN_TOOLS = ("openssl", "mkcert", "keytool", "psql") +FORBIDDEN_DOCKER = re.compile(r"\bdocker\s+(build|exec)\b") +FORBIDDEN_IN_SCRIPTS = re.compile(r"(? tuple[str, str]: + return (row["journey"], row["product"]) + + +class ProductsTable(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.data = load("products.yaml") + cls.products = cls.data["products"] + + def test_schema_and_row_keys(self): + self.assertEqual(self.data["schema"], "registry.journey-products/v1") + keys = { + "id", "tier", "binary", "crate", "ctl", "cargoPackages", "cargoFeatures", + "usesPostgres", "verifiesTokens", "rstackDevPlan", + } + for product in self.products: + allowed = keys | ({"parent"} if product["tier"] == "supporting" else set()) + self.assertEqual(set(product), allowed, product["id"]) + self.assertIn(product["tier"], TIERS, product["id"]) + for flag in ("usesPostgres", "verifiesTokens", "rstackDevPlan"): + self.assertIsInstance(product[flag], bool, f"{product['id']}.{flag}") + + def test_sixteen_unique_runtimes(self): + ids = [p["id"] for p in self.products] + self.assertEqual(len(ids), len(set(ids)), "duplicate product id") + self.assertEqual(len(ids), 16) + + def test_supporting_runtimes_name_a_primary_parent(self): + primary = {p["id"] for p in self.products if p["tier"] == "primary"} + for product in self.products: + if product["tier"] == "supporting": + self.assertIn(product["parent"], primary, product["id"]) + + def test_crates_and_binaries_exist_in_the_repository(self): + for product in self.products: + manifest = REPO / "crates" / product["crate"] / "Cargo.toml" + self.assertTrue(manifest.is_file(), f"{product['id']}: no {manifest}") + text = manifest.read_text(encoding="utf-8") + self.assertRegex(text, r'(?m)^name = "%s"$' % re.escape(product["binary"]), + f"{product['id']}: binary {product['binary']} not in {manifest.name}") + for package in product["cargoPackages"]: + self.assertTrue((REPO / "crates" / package / "Cargo.toml").is_file(), + f"{product['id']}: package {package}") + if product["ctl"] is not None: + self.assertTrue((REPO / "crates" / product["ctl"] / "Cargo.toml").is_file(), + f"{product['id']}: ctl {product['ctl']}") + + def test_rstack_dev_plan_flag_matches_the_plan_product_type(self): + plan = (REPO / "crates/registry-rstack-dev/src/plan.rs").read_text(encoding="utf-8") + match = re.search(r"pub\(super\) enum Product \{(.*?)\}", plan, re.S) + self.assertIsNotNone(match, "plan.rs no longer has the Product enum") + members = {m.lower() for m in re.findall(r"\b([A-Z][a-z]+)\b,", match.group(1))} + flagged = {p["id"] for p in self.products if p["rstackDevPlan"]} + self.assertEqual(flagged, members) + + def test_own_provider_image_matches_the_repository_pin(self): + script = (REPO / "products/breg/scripts/test-issuer-portability.py").read_text(encoding="utf-8") + match = re.search(r'^KEYCLOAK = "([^"]+)"', script, re.M) + self.assertIsNotNone(match, "the portability journey no longer pins KEYCLOAK") + issuer = self.data["ownProviderIssuer"] + self.assertEqual(issuer["name"], "keycloak") + self.assertEqual(issuer["image"], match.group(1)) + + +class PassRule(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.rule = load("first-hour-pass-rule.yaml") + + def test_end_points_and_exclusions(self): + self.assertEqual(set(self.rule["endPoints"]), {"t1", "t2"}) + self.assertTrue(self.rule["notCounted"]) + + def test_hard_conditions_are_the_six(self): + self.assertEqual(tuple(c["id"] for c in self.rule["hardConditions"]), HARD_CONDITIONS) + for condition in self.rule["hardConditions"]: + self.assertTrue(condition["text"].strip()) + + def test_ten_counters_with_both_thresholds(self): + counters = self.rule["counters"] + self.assertEqual([c["id"] for c in counters], list(range(1, 11))) + self.assertEqual(len({c["name"] for c in counters}), 10) + for counter in counters: + for path in ("rstackDev", "ownProvider"): + value = counter[path] + self.assertIs(type(value), int, f"counter {counter['id']} {path}") + self.assertGreaterEqual(value, 0) + self.assertTrue(counter["how"].strip()) + planted = counters[9] + self.assertEqual(planted["direction"], "at-least") + self.assertEqual((planted["rstackDev"], planted["ownProvider"]), (3, 3)) + + def test_the_rstack_dev_path_is_never_looser_than_own_provider(self): + for counter in self.rule["counters"]: + if counter.get("direction") == "at-least": + continue + self.assertLessEqual(counter["rstackDev"], counter["ownProvider"], + f"counter {counter['id']}") + + def test_reader_time_model_constants(self): + model = self.rule["readerTimeModel"] + self.assertEqual( + set(model), + { + "typingCharactersPerMinute", "readingWordsPerMinute", "secondsPerHandWrittenLine", + "secondsPerConceptFirstMet", "minutesPerRefusalMet", "minutesPerAssistUsed", + }, + ) + for name, value in model.items(): + self.assertIs(type(value), int, name) + self.assertGreater(value, 0, name) + + def test_pass_definition(self): + self.assertEqual(self.rule["pass"], "all-hard-conditions-and-all-counters") + + +class Concepts(unittest.TestCase): + def test_closed_list_is_well_formed(self): + data = load("concepts.yaml") + ids = [c["id"] for c in data["concepts"]] + self.assertEqual(len(ids), len(set(ids)), "duplicate concept id") + self.assertGreaterEqual(len(ids), 24) + for concept in data["concepts"]: + self.assertEqual(set(concept), {"id", "meaning"}) + self.assertRegex(concept["id"], r"^[a-z0-9]+(-[a-z0-9]+)*$") + self.assertTrue(concept["meaning"].strip(), concept["id"]) + + +class ExpectedFailures(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.data = load("expected-failures.yaml") + products = load("products.yaml")["products"] + cls.product_ids = [p["id"] for p in products] + cls.rows = ( + [("failure", r) for r in cls.data["expectedFailures"]] + + [("unreached", r) for r in cls.data["unreached"]] + ) + + def test_schema_and_journeys(self): + self.assertEqual(self.data["schema"], "registry.journey-expected-failures/v1") + self.assertEqual(tuple(self.data["journeys"]), JOURNEYS) + for journey, body in self.data["journeys"].items(): + self.assertEqual(len(body["steps"]), len(set(body["steps"])), journey) + + def test_every_cell_has_exactly_one_disposition(self): + seen: dict[tuple[str, str], list[str]] = {} + for kind, row in self.rows: + seen.setdefault(cell(row), []).append(kind) + for product in self.data["passes"]: + seen.setdefault(cell(product), []).append("pass") + for journey in JOURNEYS: + for product in self.product_ids: + self.assertEqual(len(seen.get((journey, product), [])), 1, + f"{journey} x {product}: {seen.get((journey, product))}") + self.assertEqual(set(seen), {(j, p) for j in JOURNEYS for p in self.product_ids}, + "a row names an unknown journey or product") + + def test_steps_belong_to_their_journey(self): + for kind, row in self.rows: + steps = self.data["journeys"][row["journey"]]["steps"] + self.assertIn(row["step"], steps, f"{kind} {cell(row)}") + + def test_basis_is_recorded_on_every_row(self): + for kind, row in self.rows: + self.assertIn(row["basis"], BASES, f"{kind} {cell(row)}") + if row["basis"] == "observed": + self.assertTrue(str(row.get("observedOn", "")).strip(), f"observed row needs observedOn {cell(row)}") + + def test_every_row_says_why(self): + for kind, row in self.rows: + self.assertTrue(row["reason"].strip(), f"{kind} {cell(row)}") + + def test_failure_rows_name_a_code_and_the_milestone_that_removes_them(self): + milestones = set(self.data["milestones"]) + for row in self.data["expectedFailures"]: + self.assertEqual( + set(row) - {"finding", "observedOn"}, + {"journey", "product", "step", "code", "removedBy", "basis", "reason"}, + cell(row), + ) + self.assertIn(row["removedBy"], milestones, cell(row)) + self.assertTrue(self.code_is_valid(row["code"]), f"{cell(row)}: {row['code']}") + + def test_unreached_rows_have_no_code(self): + for row in self.data["unreached"]: + self.assertEqual(set(row) - {"observedOn"}, + {"journey", "product", "step", "basis", "reason"}, cell(row)) + + def test_passes_are_listed_by_cell_only(self): + for row in self.data["passes"]: + self.assertEqual(set(row) - {"observedOn"}, {"journey", "product", "basis"}, cell(row)) + + def test_supporting_runtimes_are_never_listed_as_failures(self): + supporting = {p["id"] for p in load("products.yaml")["products"] if p["tier"] == "supporting"} + for row in self.data["expectedFailures"]: + self.assertNotIn(row["product"], supporting, cell(row)) + + def code_is_valid(self, code: str) -> bool: + suffixes = self.data["journeyCodeSuffixes"] + parts = code.split(".") + if parts[0] == "journey" and len(parts) == 3: + return parts[1] in suffixes and parts[2] in suffixes[parts[1]] + if parts[0] == "http" and len(parts) == 3: + return bool(re.fullmatch(r"[1-5][0-9]{2}", parts[1])) and parts[2] in self.data["authenticationStages"] + if parts[0] == "product" and len(parts) >= 2: + return all(re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", part) for part in parts[1:]) + return False + + +class JourneyFiles(unittest.TestCase): + """Checks that apply to files the journey scripts add. They pass when the files are absent.""" + + def test_scripts_stay_inside_the_allowed_tools(self): + for script in sorted(TABLES.glob("*.sh")): + if script.name == ASSIST_SCRIPT: + continue + for number, line in enumerate(script.read_text(encoding="utf-8").splitlines(), 1): + code = line.split("#", 1)[0] + self.assertIsNone(FORBIDDEN_IN_SCRIPTS.search(code), f"{script.name}:{number}: {line.strip()}") + self.assertIsNone(FORBIDDEN_DOCKER.search(code), f"{script.name}:{number}: {line.strip()}") + + def test_realm_import_has_no_protocol_mappers(self): + realm = TABLES / "keycloak" / "realm.json" + if realm.is_file(): + self.assertNotIn("protocolMappers", realm.read_text(encoding="utf-8")) + + +if __name__ == "__main__": + unittest.main() diff --git a/products/platform/journeys/test_lib.sh b/products/platform/journeys/test_lib.sh new file mode 100644 index 0000000000..1756d95cc8 --- /dev/null +++ b/products/platform/journeys/test_lib.sh @@ -0,0 +1,2056 @@ +#!/usr/bin/env bash +# Self-test of lib.sh, the shared helpers of the acceptance journeys. Fake +# docker, curl, cargo and uname commands stand in for the real ones, so the +# test starts no container, builds nothing and reaches no network. +# +# bash products/platform/journeys/test_lib.sh +# +# The file plays three parts. Run plainly, it is the test: each case starts +# this file again as a journey script (--driver) in its own bash process and +# checks the exit status, what the run saved and what the fakes were asked to +# do. Started through the wrappers the test writes on PATH (--fake NAME), it +# is a fake command. Everything the fakes record stays in the test's scratch +# directory, which is deleted at the end. +# +# JOURNEY_LIB_UNDER_TEST names another copy of lib.sh to test. The copy needs +# the four tables beside it and scripts/cargo-runtime-library-path.sh with +# scripts/cargo_runtime_library_path.py three folders up, as in the +# repository. TEST_LIB_KEEP=1 keeps the scratch directory. +set -euo pipefail + +self="$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)/${BASH_SOURCE[0]##*/}" +test_image='registry.test/fake/postgres:17@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef' +nl=$'\n' +alpha='' + +# --------------------------------------------------------------------------- +# Shared by every part + +mode_of() { + perl -e 'printf "%o\n", (stat $ARGV[0])[2] & 07777' "$1" +} + +random_hex() { + od -An -N"$1" -tx1 /dev/urandom | tr -d ' \n' +} + +# --------------------------------------------------------------------------- +# The fakes. Each appends its arguments, one invocation per line, to +# $FAKE_STATE/.argv and answers from the marker files a case leaves in +# $FAKE_STATE. + +fake_record() { + local name=$1 + shift + printf '%s\n' "$*" >>"$FAKE_STATE/$name.argv" +} + +# docker: version, inspect, run, port, rm and logs; any other verb fails. +# Markers: daemon-down, inspect-fails, every-name-exists, stopped, fail-start, +# fail-after-create, hang-before-cidfile (the container exists, the cidfile +# is not yet written), hang-after-create, rm-fails. It keeps containers/, +# publish (one --publish value per line) and env-file. (a copy of the +# --env-file it was given). +fake_docker() { + local verb=${1:-} name='' cidfile='' env_file='' image='' format='' port line host + fake_record docker "$@" + [[ $# -eq 0 ]] || shift + case "$verb" in + version) + if [[ -e "$FAKE_STATE/daemon-down" ]]; then + printf 'Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?\n' >&2 + return 1 + fi + printf '27.0.0\n' + ;; + inspect) + while [[ $# -gt 1 ]]; do + case "$1" in + --type) shift 2 ;; + --format) + format=$2 + shift 2 + ;; + *) shift ;; + esac + done + name=${1:-} + if [[ -e "$FAKE_STATE/inspect-fails" ]]; then + printf 'Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?\n' >&2 + return 1 + fi + if [[ ! -e "$FAKE_STATE/containers/$name" && ! -e "$FAKE_STATE/every-name-exists" ]]; then + printf 'Error: No such object: %s\n' "$name" >&2 + return 1 + fi + case "$format" in + '{{.State.Running}}') + if [[ -e "$FAKE_STATE/stopped" ]]; then printf 'false\n'; else printf 'true\n'; fi + ;; + '{{.NetworkSettings.IPAddress}}') printf '172.17.0.9\n' ;; + *) printf '[{"Name": "/%s"}]\n' "$name" ;; + esac + ;; + run) + while [[ $# -gt 0 ]]; do + case "$1" in + --name) + name=$2 + shift 2 + ;; + --cidfile) + cidfile=$2 + shift 2 + ;; + --env-file) + env_file=$2 + shift 2 + ;; + --publish) + printf '%s\n' "$2" >>"$FAKE_STATE/publish" + shift 2 + ;; + --label | --pull | -e | --env | -v | --volume | --user | --tmpfs) shift 2 ;; + --detach) shift ;; + -*) + printf 'fake docker: run option %s is not known to the fake\n' "$1" >&2 + return 125 + ;; + *) + image=$1 + break + ;; + esac + done + if [[ -z "$name" || -z "$cidfile" || -z "$image" ]]; then + printf 'fake docker: run needs --name, --cidfile and an image\n' >&2 + return 125 + fi + if [[ -e "$FAKE_STATE/containers/$name" ]]; then + printf 'docker: Error response from daemon: Conflict. The container name "/%s" is already in use.\n' "$name" >&2 + return 125 + fi + if [[ -e "$FAKE_STATE/fail-start" ]]; then + printf 'docker: Error response from daemon: fake start failure.\n' >&2 + return 125 + fi + printf '%s\n' "$image" >"$FAKE_STATE/containers/$name" + if [[ -n "$env_file" ]]; then + cp -- "$env_file" "$FAKE_STATE/env-file.$name" + fi + if [[ -e "$FAKE_STATE/hang-before-cidfile" ]]; then + exec sleep 30 + fi + printf 'f00d%060d\n' 0 >"$cidfile" + if [[ -e "$FAKE_STATE/fail-after-create" ]]; then + printf 'docker: Error response from daemon: fake failure after create.\n' >&2 + return 125 + fi + if [[ -e "$FAKE_STATE/hang-after-create" ]]; then + exec sleep 30 + fi + cat -- "$cidfile" + ;; + port) + name=${1:-} + port=${2:-} + port=${port%/tcp} + if [[ ! -e "$FAKE_STATE/containers/$name" ]]; then + printf 'Error: No such container: %s\n' "$name" >&2 + return 1 + fi + if [[ -f "$FAKE_STATE/publish" ]]; then + while IFS= read -r line; do + if [[ "$line" == 127.0.0.1:*:"$port" ]]; then + host=${line#127.0.0.1:} + host=${host%%:*} + printf '127.0.0.1:%s\n' "${host:-49153}" + return 0 + fi + done <"$FAKE_STATE/publish" + fi + printf 'Error: No public port %s/tcp published for %s\n' "$port" "$name" >&2 + return 1 + ;; + rm) + if [[ "${1:-}" != --force || "${2:-}" != --volumes || $# -ne 3 ]]; then + printf 'fake docker: rm expects --force --volumes NAME\n' >&2 + return 1 + fi + if [[ -e "$FAKE_STATE/rm-fails" ]]; then + printf 'Error response from daemon: fake removal failure\n' >&2 + return 1 + fi + if [[ -e "$FAKE_STATE/containers/$3" ]]; then + rm -- "$FAKE_STATE/containers/$3" + fi + printf '%s\n' "$3" + ;; + logs) + printf 'fake log of %s\n' "${1:-}" + ;; + *) + printf 'fake docker: the journeys never call docker %s\n' "$verb" >&2 + return 1 + ;; + esac +} + +# curl: answers its Nth call with http-status.N and http-body.N (default 200 +# and {"ok": true}). It keeps curl.headers (the headers -H @FILE read), +# curl.form (each --data-urlencode value, with NAME@FILE read from the file) +# and curl.urls. Marker: curl-fails. +fake_curl() { + local headers_file='' body_file='' write_out='' value status=200 body='{"ok": true}' count=0 + fake_record curl "$@" + while [[ $# -gt 0 ]]; do + case "$1" in + --dump-header) + headers_file=$2 + shift 2 + ;; + --output) + body_file=$2 + shift 2 + ;; + --write-out) + write_out=$2 + shift 2 + ;; + -H) + if [[ "$2" == @* ]]; then + cat -- "${2#@}" >>"$FAKE_STATE/curl.headers" + else + printf '%s\n' "$2" >>"$FAKE_STATE/curl.headers" + fi + shift 2 + ;; + --data-urlencode) + if [[ "$2" == *@* && "${2%%@*}" != *=* ]]; then + value="$(<"${2#*@}")" + printf '%s=%s\n' "${2%%@*}" "$value" >>"$FAKE_STATE/curl.form" + else + printf '%s\n' "$2" >>"$FAKE_STATE/curl.form" + fi + shift 2 + ;; + --max-time | --connect-timeout | -X | --cookie | --cookie-jar | --data-binary) shift 2 ;; + --silent | --show-error | --location) shift ;; + -*) + printf 'fake curl: option %s is not known to the fake\n' "$1" >&2 + return 2 + ;; + *) + printf '%s\n' "$1" >>"$FAKE_STATE/curl.urls" + shift + ;; + esac + done + if [[ -e "$FAKE_STATE/curl-fails" ]]; then + printf 'curl: (7) Failed to connect to 127.0.0.1 port 38099: Connection refused\n' >&2 + printf '000' + return 7 + fi + if [[ -f "$FAKE_STATE/curl.count" ]]; then + count="$(<"$FAKE_STATE/curl.count")" + fi + count=$((count + 1)) + printf '%s\n' "$count" >"$FAKE_STATE/curl.count" + if [[ -f "$FAKE_STATE/http-status.$count" ]]; then + status="$(<"$FAKE_STATE/http-status.$count")" + fi + if [[ -f "$FAKE_STATE/http-body.$count" ]]; then + body="$(<"$FAKE_STATE/http-body.$count")" + fi + if [[ -n "$headers_file" ]]; then + printf 'HTTP/1.1 %s Fake\r\ncontent-type: application/json\r\n\r\n' "$status" >"$headers_file" + fi + if [[ -n "$body_file" ]]; then + printf '%s\n' "$body" >"$body_file" + fi + if [[ "$write_out" == '%{http_code}' ]]; then + printf '%s' "$status" + fi +} + +# cargo: records its arguments and CARGO_TARGET_DIR (cargo.target). Asked for +# JSON messages, it prints the build-script message of aws-lc-fips-sys with +# out_dir $FAKE_STATE/fips-out. Marker: cargo-fails. +fake_cargo() { + local argument json=0 + fake_record cargo "$@" + printf '%s\n' "${CARGO_TARGET_DIR:-unset}" >>"$FAKE_STATE/cargo.target" + if [[ -e "$FAKE_STATE/cargo-fails" ]]; then + printf 'error: could not compile registry-alpha (fake)\n' >&2 + return 101 + fi + for argument in "$@"; do + if [[ "$argument" == --message-format=json-render-diagnostics ]]; then + json=1 + fi + done + if [[ $json -eq 1 ]]; then + printf '{"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#aws-lc-fips-sys@0.13.7","linked_libs":["dylib=aws_lc_fips_0_13_7_crypto"],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"%s"}\n' "$FAKE_STATE/fips-out" + printf '{"reason":"build-finished","success":true}\n' + fi +} + +fake_uname() { + case "${1:-}" in + -s) printf '%s\n' "${FAKE_UNAME_S:?}" ;; + -m) printf 'arm64\n' ;; + *) + printf 'fake uname: only -s and -m are answered\n' >&2 + return 1 + ;; + esac +} + +# The product binary alpha. The long-running commands write their pid to +# $FAKE_STATE/alpha.pid. +fake_alpha() { + case "${1:-}" in + ok) printf 'alpha: ready\n' ;; + fail) + printf 'alpha: product.config.unknown-field: remove the field color from alpha.yaml\n' >&2 + return 4 + ;; + print-env) + printf 'carrier=%s\n' "${REGISTRY_CARGO_RUNTIME_LIBRARY_PATH-unset}" + printf 'dyld=%s\n' "${DYLD_FALLBACK_LIBRARY_PATH-unset}" + ;; + cat) cat -- "$2" ;; + pwd-and-stdin) + printf 'cwd=%s\n' "$(pwd -P)" + printf 'stdin=%s\n' "$(cat)" + ;; + sleep) + printf '%s\n' "$$" >"$FAKE_STATE/alpha.pid" + exec sleep "$2" + ;; + stubborn) + printf '%s\n' "$$" >"$FAKE_STATE/alpha.pid" + trap '' TERM + printf 'ignoring TERM\n' + while :; do sleep 0.2; done + ;; + serve) + printf '%s\n' "$$" >"$FAKE_STATE/alpha.pid" + trap 'printf "stopping\n"; exit 0' TERM + printf 'serving\n' + if [[ -n "${3:-}" ]]; then + printf 'loaded key %s\n' "$(<"$3")" >&2 + fi + : >"$2" + while :; do sleep 0.2; done + ;; + exit-now) + printf 'alpha: product.start.refused: no runtime file\n' >&2 + return 5 + ;; + *) + printf 'alpha: unknown command %s\n' "${1:-}" >&2 + return 64 + ;; + esac +} + +fake_main() { + local name=${1:-} + [[ $# -eq 0 ]] || shift + case "$name" in + docker) fake_docker "$@" ;; + curl) fake_curl "$@" ;; + cargo) fake_cargo "$@" ;; + uname) fake_uname "$@" ;; + alpha) fake_alpha "$@" ;; + *) + printf 'test_lib: no fake named %s\n' "$name" >&2 + return 2 + ;; + esac +} + +# --------------------------------------------------------------------------- +# The journey script each case runs (--driver). SCENARIO picks what it does. +# It appends KEY=VALUE lines to $REPORT, and every raw secret value it +# handles to $PATTERNS so the test can look for them in what the run saved. + +report() { + printf '%s=%s\n' "$1" "$2" >>"$REPORT" +} + +remember() { + printf '%s\n' "$1" >>"$PATTERNS" +} + +driver_binaries() { + if [[ -n "${DRIVER_DYLD:-}" ]]; then + # Set here, not inherited: a protected launcher drops DYLD_* variables. + export DYLD_FALLBACK_LIBRARY_PATH=$DRIVER_DYLD + fi + journey_resolve_binaries "${JOURNEY_PRODUCTS[@]}" + report bin_dir "$JOURNEY_BIN_DIR" + report carrier "${REGISTRY_CARGO_RUNTIME_LIBRARY_PATH-unset}" + report dyld "${DYLD_FALLBACK_LIBRARY_PATH-unset}" + journey_bin "${BIN_NAME:-alpha}" alpha +} + +# The cell of PRODUCT as CELL_ describes it: pass, fail:STEP:CODE, +# needs:STEP:THING, poll:STEP (a journey_poll that runs out of time), +# unreached:STEP, blocker:STEP:CODE:ASSIST or harness:STEP. The default is the +# product's row in the synthetic table. +driver_cell() { + local product=$1 plan_name plan kind stop code assist step + plan_name="CELL_$product" + plan=${!plan_name:-} + if [[ -z "$plan" ]]; then + case "$product" in + beta) plan=fail:call:http.401.issuer ;; + gamma) plan=unreached:prepare ;; + delta) plan=fail:start:product.config.unknown-field ;; + *) plan=pass ;; + esac + fi + IFS=: read -r kind stop code assist <<<"$plan" + journey_cell_begin "$product" + for step in prepare start call stop; do + if [[ "$step" == "${stop:-}" ]]; then + case "$kind" in + unreached) + journey_unreached "$step" "runs beside its parent" + break + ;; + fail) + if ! journey_step "$step" -- "$alpha" fail; then + journey_fail "$step" "$code" + fi + break + ;; + needs) + journey_needs "$step" "$code" + break + ;; + poll) + if ! journey_step "$step" -- journey_poll 2 -- false; then + journey_fail "$step" product.poll.timed-out + fi + break + ;; + blocker) + if ! journey_step "$step" -- "$alpha" fail; then + journey_blocker "$step" "$code" "$assist" "$JOURNEY_OUT/work" || break + fi + continue + ;; + harness) journey_harness_failure "a harness failure the test asked for" ;; + esac + fi + if [[ "$step" == prepare ]]; then + journey_step prepare --concepts runtime-file -- "$alpha" "${PREPARE:-ok}" + fi + journey_pass "$step" + done + journey_cell_end +} + +driver_all_cells() { + local product + for product in "${JOURNEY_PRODUCTS[@]}"; do + driver_cell "$product" + done +} + +# A cleanup hook: records whether the container still existed when it ran +# (hooks run before containers are removed) and fails when HOOK=fail. +driver_cleanup_hook() { + local name + journey_container_name db name + if [[ -e "$FAKE_STATE/containers/$name" ]]; then + printf 'container-present\n' >>"$FAKE_STATE/hook-ran" + else + printf 'container-absent\n' >>"$FAKE_STATE/hook-ran" + fi + [[ "${HOOK:-ok}" != fail ]] +} + +driver_containers() { + local path port address + local -a options=() ports=(--port 5432) + journey_require_docker + journey_at_cleanup driver_cleanup_hook + journey_set_address_class bridge + journey_secret_new db-password + journey_secret_path db-password path + remember "$(<"$path")" + if [[ -n "${CONTAINER_OPTS:-}" ]]; then + read -r -a options <<<"$CONTAINER_OPTS" + fi + if [[ -n "${EXTRA_PORT:-}" ]]; then + ports+=(--port "$EXTRA_PORT") + fi + journey_container_run db "${ports[@]}" --secret-env POSTGRES_PASSWORD=db-password -e PLAIN=1 \ + ${options[@]+"${options[@]}"} -- "${CONTAINER_IMAGE:-$test_image}" + journey_container_port db 5432 port + report port "$port" + journey_container_address db address + report address "$address" + journey_container_wait db "${WAIT_SECONDS:-5}" -- "${WAIT_PROBE:-true}" + journey_container_logs db + if ! journey_check_absent stackrun-m0-libtest-foreign stackrun-m0-libtest-absent; then + report leftover found + fi + driver_binaries + if [[ "${START_SERVER:-0}" == 1 ]]; then + journey_cell_begin alpha + journey_pass prepare + journey_start start server --settle 1 -- "$alpha" serve "$FAKE_STATE/ready" + journey_pass start + journey_pass call + journey_pass stop + journey_cell_end + else + driver_all_cells + fi +} + +driver_takeover() { + local from + journey_option_value from from + journey_take_over_run "$from" + driver_binaries + journey_cell_begin alpha + journey_step prepare -- "$alpha" cat "$from/secrets/db-password" + journey_pass prepare + journey_pass start + journey_pass call + journey_pass stop + journey_cell_end +} + +driver_secrets() { + local path value env_path token variable input jwt_head='ey' jwt_payload jwt + local pem_body basic cookie bearer url_password json_token json_password + journey_secret_new api-key + journey_secret_path api-key path + value="$(<"$path")" + remember "$value" + report secret-mode "$(mode_of "$path")" + report secret-length "${#value}" + journey_secret_env_file app env_path API_KEY=api-key + report env-mode "$(mode_of "$env_path")" + if [[ "$(<"$env_path")" == "API_KEY=$value" ]]; then + report env-file ok + fi + token="tok$(random_hex 12)" + remember "$token" + # Registered through a variable named like a local of journey_secret_register, + # to show the value is read from the caller. + # shellcheck disable=SC2034 # read by name + variable=$token + journey_secret_register access-token variable + pem_body="$(random_hex 24)" + jwt_payload="$(random_hex 12)" + jwt="${jwt_head}J$(random_hex 8).$jwt_payload.$(random_hex 8)" + basic="$(random_hex 12)" + cookie="$(random_hex 12)" + bearer="$(random_hex 12)" + url_password="$(random_hex 12)" + json_token="$(random_hex 12)" + json_password="$(random_hex 12)" + for value in "$pem_body" "$jwt_payload" "$basic" "$cookie" "$bearer" "$url_password" "$json_token" "$json_password"; do + remember "$value" + done + journey__raw_path input redact-input + { + printf 'api key: %s\n' "$(<"$path")" + printf 'token in text: %s\n' "$token" + printf -- '-----BEGIN %s-----\n%s\n-----END %s-----\n' 'PRIVATE KEY' "$pem_body" 'PRIVATE KEY' + printf 'jwt: %s\n' "$jwt" + printf 'Authorization: Basic %s\n' "$basic" + printf '> Cookie: session=%s\n' "$cookie" + printf 'the server said Bearer %s\n' "$bearer" + printf 'url: postgres://registry:%s@127.0.0.1:38010/registry\n' "$url_password" + printf '{"access_token": "%s", "password": "%s", "note": "kept"}\n' "$json_token" "$json_password" + } >"$input" + journey_redact "$input" "$JOURNEY_OUT/redacted.txt" + report redacted "$JOURNEY_OUT/redacted.txt" + driver_binaries + driver_all_cells +} + +driver_leak() { + local path jwt_head='ey' + journey_secret_new api-key + journey_secret_path api-key path + remember "$(<"$path")" + case "${LEAK:-secret}" in + secret) cp -- "$path" "$JOURNEY_OUT/leak.txt" ;; + jwt) printf '%sJ%s.%s.%s\n' "$jwt_head" "$(random_hex 8)" "$(random_hex 8)" "$(random_hex 8)" >"$JOURNEY_OUT/leak.txt" ;; + esac + driver_binaries + driver_all_cells +} + +driver_http() { + local path step + journey_secret_new client-secret + journey_secret_path client-secret path + remember "$(<"$path")" + journey_cell_begin alpha + journey_pass prepare + journey_http start --form grant_type=client_credentials --form-secret client_secret=client-secret --cookie-jar session \ + --capture-secret .access_token step POST http://127.0.0.1:38001/token + journey_pass start + # The token is held in a variable named step, a word journey_http also uses, + # to show the caller's variable is the one set and read. + report token-length "${#step}" + if ! journey_http call --bearer step --header 'Accept: application/json' GET http://127.0.0.1:38001/records; then + report http-status "$JOURNEY_HTTP_STATUS" + report problem-code "$JOURNEY_HTTP_PROBLEM_CODE" + journey_fail call "http.$JOURNEY_HTTP_STATUS.issuer" + fi + journey_cell_end +} + +# The options of journey_step and journey_http that the other scenarios leave +# out: --cwd, --stdin, --doc-words and --typed of a step, and --data-file and +# --location of a request that gets no answer. +driver_options() { + local dir + driver_binaries + journey_cell_begin alpha + journey_workdir alpha dir + printf 'reader input\n' >"$dir/input.txt" + journey_step prepare --cwd "$dir" --stdin "$dir/input.txt" --doc-words 40 --typed 'alpha check' -- "$alpha" pwd-and-stdin + journey_pass prepare + if ! journey_http start --data-file "$dir/input.txt" --location POST http://127.0.0.1:38001/upload; then + report curl-status "$JOURNEY_HTTP_STATUS" + journey_fail start product.http.no-answer + fi + journey_cell_end +} + +# One way of breaking the rules a cell keeps; each is a journey script error. +driver_discipline() { + driver_binaries + case "${DISCIPLINE:?}" in + pass-after-fail) + journey_cell_begin alpha + journey_step prepare -- "$alpha" fail || report prepare failed + journey_pass prepare + ;; + begin-twice) + journey_cell_begin alpha + journey_cell_begin alpha + ;; + end-without-last) + journey_cell_begin alpha + journey_pass prepare + journey_cell_end + ;; + unknown-step) + journey_cell_begin alpha + journey_pass deploy + ;; + unresolved) + journey_cell_begin alpha + journey_step prepare -- "$alpha" fail || report prepare failed + journey_pass start + ;; + unknown-concept) + journey_cell_begin alpha + journey_step prepare --concepts warp-drive -- "$alpha" ok + ;; + unknown-suffix) + journey_cell_begin alpha + journey_fail prepare journey.needs.magic + ;; + unknown-stage) + journey_cell_begin alpha + journey_fail call http.401.moon + ;; + bad-code) + journey_cell_begin alpha + journey_fail call refused + ;; + after-stop) + journey_cell_begin alpha + journey_fail prepare product.config.bad + journey_pass start + ;; + unknown-counter) + journey_cell_begin alpha + journey_count coffee-breaks + ;; + library-name) + journey_cell_begin alpha + journey_workdir alpha _jr_target + ;; + missing-cell) ;; + esac +} + +driver_ready_probe() { + [[ -f "$FAKE_STATE/ready" ]] +} + +driver_processes() { + local path log + journey_secret_new server-key + journey_secret_path server-key path + remember "$(<"$path")" + driver_binaries + journey_cell_begin alpha + journey_pass prepare + case "${PROCESS_MODE:-serve}" in + serve) + journey_start start server --settle 1 -- "$alpha" serve "$FAKE_STATE/ready" "$path" + journey_pass start + journey_ready call server --timeout 10 -- driver_ready_probe + journey_pass call + if journey_process_running server; then + report running yes + fi + journey_process_log server log + report log "$log" + journey_stop stop server --timeout 5 + report stop-status "$JOURNEY_PROCESS_STATUS" + journey_pass stop + ;; + stubborn) + journey_start start server --settle 1 -- "$alpha" stubborn + journey_pass start + journey_pass call + if ! journey_stop stop server --timeout 1; then + journey_fail stop product.stop.ignored-signal + fi + ;; + exit-now) + if ! journey_start start server --settle 1 -- "$alpha" exit-now; then + report start-status "$JOURNEY_PROCESS_STATUS" + journey_fail start product.start.refused + fi + ;; + esac + journey_cell_end +} + +driver_files() { + local dir + journey_cell_begin alpha + journey_workdir alpha dir + journey_pass prepare + case "${FILES_MODE:-count}" in + count) + journey_write_file "$dir/alpha.yaml" --concepts runtime-file < <(printf 'ab: 1\ncd: 2\nef: 3\n') + journey_reached t1 + journey_edit_file "$dir/alpha.yaml" 'cd: 2' 'cd: 20' --concepts issuer + ;; + outside) + journey_write_file "$JOURNEY_OUT/alpha.yaml" "$patterns" +} + +# check DESCRIPTION COMMAND...: COMMAND must succeed. +check() { + local description=$1 + shift + checks=$((checks + 1)) + if ! "$@"; then + problem "$description" + fi +} + +check_equal() { + checks=$((checks + 1)) + if [[ "$2" != "$3" ]]; then + problem "$1" "expected '$2', got '$3'" + fi +} + +has() { + [[ -f "$2" ]] && grep -qF -- "$1" "$2" +} + +lacks() { + [[ ! -f "$2" ]] || ! grep -qF -- "$1" "$2" +} + +no_file() { + [[ ! -e "$1" && ! -L "$1" ]] +} + +contents() { + if [[ -f "$1" ]]; then + printf '%s' "$(<"$1")" + fi +} + +directory_empty() ( + shopt -s nullglob dotglob + set -- "$1"/* + [[ $# -eq 0 ]] +) + +# only_entry DIR NAME: DIR holds NAME and nothing else. +only_entry() ( + shopt -s nullglob dotglob + set -- "$1"/* "$2" + [[ $# -eq 2 && "${1##*/}" == "$2" ]] +) + +run_id_ok() { + [[ "$1" =~ ^[0-9]{14}-[0-9a-f]{4}$ ]] +} + +# row_words PRODUCT FILE: the words of the printed table row of PRODUCT. +row_words() { + local line + local -a words=() + if [[ -f "$2" ]]; then + while IFS= read -r line; do + if [[ "$line" == "$1 "* ]]; then + read -r -a words <<<"$line" + printf '%s' "${words[*]}" + return 0 + fi + done <"$2" + fi +} + +# value KEY: the last KEY=VALUE line the latest driver run reported. +value() { + local line found='' + if [[ -f "$report" ]]; then + while IFS= read -r line; do + if [[ "$line" == "$1="* ]]; then + found=${line#*=} + fi + done <"$report" + fi + printf '%s' "$found" +} + +json() { + if [[ -f "$2" ]]; then + jq -r "$1" "$2" 2>/dev/null || printf 'unreadable' + else + printf 'missing' + fi +} + +line_of() { + local line + if [[ -f "$2" ]]; then + while IFS= read -r line; do + if [[ "$line" == "$1"* ]]; then + printf '%s' "$line" + return 0 + fi + done <"$2" + fi +} + +verb_count() { + local line count=0 + if [[ -f "$2" ]]; then + while IFS= read -r line; do + if [[ "$line" == "$1 "* || "$line" == "$1" ]]; then + count=$((count + 1)) + fi + done <"$2" + fi + printf '%s' "$count" +} + +# Every rm the fake docker saw names exactly NAME, and there was one. +only_rm_of() { + local line found=0 + [[ -f "$2" ]] || return 1 + while IFS= read -r line; do + if [[ "$line" == rm* ]]; then + [[ "$line" == "rm --force --volumes $1" ]] || return 1 + found=1 + fi + done <"$2" + [[ $found -eq 1 ]] +} + +# None of the recorded secret values is in PATH... (secrets/ folders aside). +# Only file names are printed, never a value. +no_secret_in() { + local found status=0 + if [[ ! -s "$patterns" ]]; then + printf ' no secret values were recorded to look for\n' + return 1 + fi + found="$(grep -rlF --exclude-dir=secrets -f "$patterns" -- "$@")" || status=$? + case "$status" in + 1) return 0 ;; + 0) printf ' a secret value is in: %s\n' "${found//$nl/ }" ;; + *) printf ' grep could not search %s\n' "$*" ;; + esac + return 1 +} + +# The env file Docker was given sets the generated password, by value. +env_file_carries_secret() { + local text + [[ -f "$1" ]] || return 1 + text="$(<"$1")" + [[ "$text" =~ ^POSTGRES_PASSWORD=([0-9a-f]{48})$ ]] || return 1 + grep -qxF -- "${BASH_REMATCH[1]}" "$patterns" +} + +# curl received NAME= as a form value. +form_has_secret() { + local line + [[ -f "$1" ]] || return 1 + while IFS= read -r line; do + if [[ "$line" == "$2="* ]] && grep -qxF -- "${line#*=}" "$patterns"; then + return 0 + fi + done <"$1" + return 1 +} + +process_gone() { + local tries=0 + [[ "${1:-}" =~ ^[0-9]+$ ]] || return 1 + while kill -0 "$1" 2>/dev/null; do + tries=$((tries + 1)) + ((tries <= 60)) || return 1 + sleep 0.05 + done +} + +wait_for_file() { + local tries=0 + while [[ ! -s "$1" ]]; do + tries=$((tries + 1)) + ((tries <= 200)) || return 1 + sleep 0.05 + done +} + +wait_for_container() { + local tries=0 + while directory_empty "$state/containers"; do + tries=$((tries + 1)) + ((tries <= 200)) || return 1 + sleep 0.05 + done +} + +# /bin/bash and the other system binaries drop DYLD_* variables on macOS. +bash_is_protected() { + [[ "$(command -p uname -s)" == Darwin ]] || return 1 + case "$BASH" in + /bin/* | /usr/bin/* | /sbin/* | /usr/sbin/*) return 0 ;; + esac + return 1 +} + +driver_environment() { + unset CARGO_TARGET_DIR REGISTRY_CARGO_RUNTIME_LIBRARY_PATH DYLD_FALLBACK_LIBRARY_PATH JOURNEY_PORT_BASE \ + JOURNEY_ASSISTS_FILE JOURNEY_STEP_TIMEOUT + export PATH="$test_path" FAKE_STATE="$state" REPORT="$report" PATTERNS="$patterns" \ + JOURNEY_LIB_UNDER_TEST="$lib" JOURNEY_TABLES_DIR="$work/tables" \ + JOURNEY_CONTAINER_PREFIX=stackrun-m0-libtest JOURNEY_KILL_GRACE=1 TMPDIR="$work/tmp" \ + FAKE_UNAME_S=Linux SCENARIO=cells +} + +# Start the driver through perl: INT and TERM back to their default (a +# background job of a script starts with INT ignored), an alarm after 120 +# seconds so a hung case cannot hang the test, and with GROUP=1 a process +# group of its own so a case can signal the driver and its children at once. +start_driver() { + local group=$1 + shift + drive_count=$((drive_count + 1)) + out="$work/runs/$case_name-$drive_count" + report="$work/reports/$case_name-$drive_count" + last_out="$work/logs/$case_name-$drive_count.out" + last_err="$work/logs/$case_name-$drive_count.err" + : >"$report" + ( + driver_environment + while [[ $# -gt 0 && "$1" != -- ]]; do + # shellcheck disable=SC2163 # each argument is NAME=VALUE + export "$1" + shift + done + [[ $# -eq 0 ]] || shift + if [[ $add_out -eq 1 ]]; then + set -- --out "$out" "$@" + fi + exec perl -e ' + my ($seconds, $group) = splice @ARGV, 0, 2; + $SIG{INT} = $SIG{TERM} = "DEFAULT"; + if ($group) { setpgrp(0, 0) or die "setpgrp: $!\n" } + alarm $seconds; + exec { $ARGV[0] } @ARGV or die "cannot start $ARGV[0]: $!\n";' -- 120 "$group" "$BASH" "$self" --driver "$@" + ) "$last_out" 2>"$last_err" & + launched=$! +} + +# collect STATUS: wait for the driver and compare its exit status. +collect() { + local want=$1 status=0 tail_text + wait "$launched" || status=$? + launched='' + checks=$((checks + 1)) + if [[ $status -ne $want ]]; then + tail_text="$(tail -n 3 "$last_err")" + problem "exit status $status, expected $want" "${tail_text//$nl/ | }" + fi +} + +# drive STATUS [NAME=VALUE]... -- [ARGUMENT]...: run the driver to the end. +drive() { + local want=$1 + shift + start_driver 0 "$@" + collect "$want" +} + +# launch [NAME=VALUE]... -- [ARGUMENT]...: start the driver in its own +# process group and return; collect waits for it. +launch() { + start_driver 1 "$@" +} + +write_wrapper() { + { + printf '#!%s\n' "$BASH" + # shellcheck disable=SC2016 # "$@" belongs to the wrapper + printf 'exec %q %q --fake %q "$@"\n' "$BASH" "$self" "$2" + } >"$1" + chmod 755 "$1" +} + +expected_table() { + cat <<'YAML' +schema: registry.journey-expected-failures/v1 +journeys: + sample: + steps: [prepare, start, call, stop] +journeyCodeSuffixes: + needs: [certificate, hand-written-sql] + promote: [no-input] +authenticationStages: [issuer, audience] +milestones: [M1, M2] +expectedFailures: + - journey: sample + product: beta + step: call + code: http.401.issuer + removedBy: M1 + basis: predicted + reason: The issuer is refused. +YAML + if [[ "${1:-}" != unlisted ]]; then + cat <<'YAML' + - journey: sample + product: delta + step: start + code: product.config.unknown-field + removedBy: M2 + basis: predicted + reason: The runtime file names a field the product does not know. +YAML + fi + if [[ "${1:-}" == twice ]]; then + cat <<'YAML' + - journey: sample + product: alpha + step: call + code: http.401.audience + removedBy: M2 + basis: predicted + reason: Listed twice on purpose. +YAML + fi + cat <<'YAML' +unreached: + - journey: sample + product: gamma + step: prepare + basis: predicted + reason: Runs beside alpha. +passes: + - journey: sample + product: alpha + basis: predicted +YAML +} + +write_tables() { + local dir="$work/tables" + mkdir -p "$dir" "$work/empty" + cat >"$dir/products.yaml" <<'YAML' +schema: registry.journey-products/v1 +products: + - id: alpha + tier: primary + binary: alpha + crate: registry-alpha + ctl: registry-alphactl + cargoPackages: [registry-alpha, registry-alphactl] + cargoFeatures: [registry-alpha/runtime] + usesPostgres: true + verifiesTokens: true + rstackDevPlan: false + - id: beta + tier: primary + binary: beta + crate: registry-beta + ctl: null + cargoPackages: [registry-beta, registry-alphactl] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: true + rstackDevPlan: false + - id: gamma + tier: supporting + parent: alpha + binary: gamma + crate: registry-gamma + ctl: null + cargoPackages: [registry-gamma] + cargoFeatures: [registry-gamma/runtime] + usesPostgres: false + verifiesTokens: false + rstackDevPlan: false + - id: delta + tier: primary + binary: delta + crate: registry-delta + ctl: null + cargoPackages: [registry-delta] + cargoFeatures: [] + usesPostgres: false + verifiesTokens: false + rstackDevPlan: true +YAML + cat >"$dir/concepts.yaml" <<'YAML' +schema: registry.journey-concepts/v1 +concepts: + - id: runtime-file + meaning: The file a product reads when it starts. + - id: issuer + meaning: The identity provider that signs the tokens a product accepts. +YAML + cat >"$dir/first-hour-pass-rule.yaml" <<'YAML' +# lib.sh reads only readerTimeModel; the flow mapping below is outside the +# core YAML reader's subset and must not stop it. +rules: {steps: 12} +readerTimeModel: + typingCharactersPerMinute: 200 + readingWordsPerMinute: 200 + secondsPerHandWrittenLine: 30 + secondsPerConceptFirstMet: 60 + minutesPerRefusalMet: 5 + minutesPerAssistUsed: 10 +YAML + expected_table >"$dir/expected-failures.yaml" + expected_table unlisted >"$dir/expected-unlisted.yaml" + expected_table twice >"$dir/expected-twice.yaml" +} + +write_fixtures() { + local fips="$work/bins/debug/build/aws-lc-fips-sys-0f1e2d/out/build/artifacts" tool + mkdir -p "$work/bin" "$work/cargo-bin" "$work/tools" "$work/tmp" "$work/state" "$work/patterns" \ + "$work/reports" "$work/runs" "$work/logs" "$fips" "$work/bins/debug/build/aws-lc-fips-sys-000000/out" \ + "$work/bare-bins" "$work/target/debug" "$work/carrier" + chmod 700 "$work/tmp" + : >"$fips/libaws_lc_fips_0_13_7_crypto.dylib" + for tool in jq python3; do + ln -s "$(command -v "$tool")" "$work/tools/$tool" + done + write_wrapper "$work/bin/docker" docker + write_wrapper "$work/bin/curl" curl + write_wrapper "$work/bin/uname" uname + write_wrapper "$work/cargo-bin/cargo" cargo + write_wrapper "$work/bins/debug/alpha" alpha + write_wrapper "$work/bare-bins/alpha" alpha + write_wrapper "$work/target/debug/alpha" alpha + ln -s "$work/bins" "$work/bin-link" + cat >"$work/assists.sh" <<'SH' +# Assists of the self-test: each records its arguments. +journey_assist_certificate() { + printf '%s\n' "$*" >>"$FAKE_STATE/assist-ran" +} +SH + write_tables +} + +# --------------------------------------------------------------------------- +# Cases + +case_usage() { + begin_case usage + add_out=0 + drive 2 -- --no-such-option + check "an unknown option is named" has "unknown option --no-such-option" "$last_err" + drive 2 -- --product alpha --strict + check "--strict needs --expected" has "--strict needs --expected" "$last_err" + drive 2 -- --all --product alpha + drive 2 -- --product omega + check "an unknown product lists the known ones" has "products.yaml lists: alpha beta gamma delta" "$last_err" + drive 2 -- --product alpha --expected "$work/no-such-table.yaml" + drive 2 -- --assist certificate --expected "$work/tables/expected-failures.yaml" + check "--assist and --expected exclude each other" has "--assist and --expected exclude each other" "$last_err" + drive 2 -- --out "$work/runs/a" --out "$work/runs/b" + check "an option given twice is refused" has "--out is given twice" "$last_err" + drive 2 JOURNEY_CONTAINER_PREFIX=Bad_Prefix -- --product alpha + drive 2 JOURNEY_PORT_BASE=80 -- --product alpha + drive 2 JOURNEY_TABLES_DIR="$work/empty" -- --product alpha + check "a missing table is named" has "does not exist" "$last_err" + drive 0 -- --help + check "--help prints the usage" has "usage:" "$last_out" + check "no usage error created a run directory" directory_empty "$work/tmp" + check "no usage error created a --out directory" directory_empty "$work/runs" + checks=$((checks + 1)) + local status=0 + "$BASH" "$lib" >/dev/null 2>&1 || status=$? + if [[ $status -ne 2 ]]; then + problem "lib.sh run on its own exits 2" "it exited $status" + fi +} + +case_binaries() { + local artifacts="$work/bins/debug/build/aws-lc-fips-sys-0f1e2d/out/build/artifacts" + local cargo_path="$test_path:$work/cargo-bin" + + begin_case bin-dir-darwin + drive 0 FAKE_UNAME_S=Darwin DRIVER_DYLD=/caller/lib PREPARE=print-env -- --product alpha --bin-dir "$work/bin-link/debug" + check_equal "the binary directory is resolved to its physical path" "$work/bins/debug" "$(value bin_dir)" + check_equal "the FIPS directory is the first artifacts folder under build/" "$artifacts" "$(value carrier)" + check_equal "it goes first in DYLD_FALLBACK_LIBRARY_PATH, the caller's value after it" "$artifacts:/caller/lib" "$(value dyld)" + check_equal "the product sees REGISTRY_CARGO_RUNTIME_LIBRARY_PATH" "carrier=$artifacts" "$(line_of carrier= "$out/alpha/prepare.stdout")" + if bash_is_protected; then + printf 'note %s: %s is a protected binary, so a product started through it never sees DYLD_* variables; that check is skipped under this bash\n' "$case_name" "$BASH" + else + check_equal "the product started directly by bash sees DYLD_FALLBACK_LIBRARY_PATH" "dyld=$artifacts:/caller/lib" "$(line_of dyld= "$out/alpha/prepare.stdout")" + fi + check_equal "run.json records the runtime library path" "$artifacts" "$(json '.binaries.runtimeLibraryPath' "$out/run.json")" + check_equal "run.json records the binaries' source" bin-dir "$(json '.binaries.source' "$out/run.json")" + + begin_case bin-dir-carrier + drive 0 FAKE_UNAME_S=Darwin REGISTRY_CARGO_RUNTIME_LIBRARY_PATH="$work/carrier" -- --product alpha --bin-dir "$work/bins/debug" + check_equal "the caller's REGISTRY_CARGO_RUNTIME_LIBRARY_PATH wins over the build folder" "$work/carrier" "$(value carrier)" + check_equal "DYLD_FALLBACK_LIBRARY_PATH holds it alone" "$work/carrier" "$(value dyld)" + drive 2 FAKE_UNAME_S=Darwin REGISTRY_CARGO_RUNTIME_LIBRARY_PATH="$work/no-such-dir" -- --product alpha --bin-dir "$work/bins/debug" + check "a carrier naming no directory is refused" has "names no directory" "$last_err" + + begin_case bin-dir-linux + drive 0 FAKE_UNAME_S=Linux -- --product alpha --bin-dir "$work/bins/debug" + check_equal "off macOS no FIPS directory is exported" unset "$(value carrier)" + check_equal "off macOS DYLD_FALLBACK_LIBRARY_PATH is left alone" unset "$(value dyld)" + + begin_case bin-dir-without-fips-library + drive 0 FAKE_UNAME_S=Darwin -- --product alpha --bin-dir "$work/bare-bins" + check "a bin dir without the FIPS library warns" has "warning: no AWS-LC FIPS library directory" "$last_err" + check_equal "and exports nothing" unset "$(value carrier)" + + begin_case build-darwin + mkdir -p "$state/fips-out/build/artifacts" + : >"$state/fips-out/build/artifacts/libaws_lc_fips_0_13_7_crypto.dylib" + drive 0 PATH="$cargo_path" FAKE_UNAME_S=Darwin CARGO_TARGET_DIR="$work/target" CELL_beta=pass -- --product alpha --product beta + check_equal "cargo builds each package once, locked, through the repository helper" \ + "build --locked --manifest-path $root/Cargo.toml -p registry-alpha -p registry-alphactl -p registry-beta --features registry-alpha/runtime --bins --message-format=json-render-diagnostics" \ + "$(contents "$state/cargo.argv")" + check_equal "cargo sees the exported CARGO_TARGET_DIR" "$work/target" "$(contents "$state/cargo.target")" + check_equal "the binaries come from its debug folder" "$work/target/debug" "$(value bin_dir)" + check_equal "the FIPS directory comes from cargo's build messages" "$state/fips-out/build/artifacts" "$(value carrier)" + check_equal "and is exported for the dynamic loader" "$state/fips-out/build/artifacts" "$(value dyld)" + check_equal "run.json records a build" build "$(json '.binaries.source' "$out/run.json")" + + begin_case build-linux + drive 0 PATH="$cargo_path" FAKE_UNAME_S=Linux CARGO_TARGET_DIR="$work/target" -- --product alpha + check_equal "off macOS it is a plain cargo build" \ + "build --locked --manifest-path $root/Cargo.toml -p registry-alpha -p registry-alphactl --features registry-alpha/runtime --bins" \ + "$(contents "$state/cargo.argv")" + check_equal "and exports no FIPS directory" unset "$(value carrier)" + + begin_case build-refusals + drive 2 PATH="$cargo_path" CARGO_TARGET_DIR="$root/target" -- --product alpha + check "the repository target/ directory is refused" has "points at the repository target/ directory" "$last_err" + drive 2 PATH="$cargo_path" CARGO_TARGET_DIR="$root/target/journeys" -- --product alpha + check "a folder under it is refused" has "points at the repository target/ directory" "$last_err" + drive 2 -- --product alpha + check "with neither --bin-dir nor CARGO_TARGET_DIR the run stops" has "pass --bin-dir DIR or export CARGO_TARGET_DIR" "$last_err" + drive 2 PATH="$cargo_path" CARGO_TARGET_DIR="$work/target" -- --product alpha --timed + check "--timed refuses a build" has "--timed needs --bin-dir" "$last_err" + drive 2 CARGO_TARGET_DIR="$work/target" -- --product alpha + check "a build needs cargo on PATH" has "cargo is not on PATH" "$last_err" + check "no refused build ran cargo" no_file "$state/cargo.argv" + + begin_case build-fails + : >"$state/cargo-fails" + drive 2 PATH="$cargo_path" CARGO_TARGET_DIR="$work/target" -- --product alpha + check "a failed build stops the run" has "the build of the journey binaries failed" "$last_err" + + begin_case missing-binary + drive 2 BIN_NAME=omega -- --product alpha --bin-dir "$work/bins/debug" + check "a binary missing from the bin dir is named" has "no executable omega" "$last_err" +} + +case_run_directories() { + begin_case out-through-symlink + add_out=0 + mkdir -p "$work/out-real" + ln -s "$work/out-real" "$work/out-link" + drive 0 -- --product alpha --bin-dir "$work/bins/debug" --out "$work/out-link/run" + finished_run="$work/out-real/run" + check_equal "the run directory is resolved to its physical path" "$finished_run" "$(value out)" + check_equal "the run directory has mode 700" 700 "$(mode_of "$finished_run")" + check "cells.tsv records the cell" has $'alpha\tstop\tpass' "$finished_run/cells.tsv" + check "the raw folder is gone after the run" no_file "$finished_run/.raw" + check "the secrets folder is gone after the run" no_file "$finished_run/secrets" + check_equal "run.json ends with exit status 0" 0 "$(json '.exitStatus' "$finished_run/run.json")" + check_equal "summary.json names its schema" registry.journey-summary/v1 "$(json '.schema' "$finished_run/summary.json")" + + begin_case out-refusals + add_out=0 + mkdir -p "$work/out-full" + printf 'keep me\n' >"$work/out-full/note" + drive 2 -- --product alpha --bin-dir "$work/bins/debug" --out "$work/out-full" + check "a non-empty --out is refused" has "is not empty" "$last_err" + check "and left as it was" has "keep me" "$work/out-full/note" + check "nothing was added to it" only_entry "$work/out-full" note + printf 'x\n' >"$work/out-file" + drive 2 -- --product alpha --bin-dir "$work/bins/debug" --out "$work/out-file" + check "a --out that is a file is refused" has "exists and is not a directory" "$last_err" + + begin_case out-default + add_out=0 + drive 0 -- --product alpha --bin-dir "$work/bins/debug" + check_equal "without --out the run goes under TMPDIR, named by prefix, journey and run" \ + "$work/tmp/stackrun-m0-libtest-sample-$(value run)" "$(value out)" + check "the run id is a UTC time and four hexadecimal digits" run_id_ok "$(value run)" +} + +case_containers() { + local name options + local -a alpha_args=(--product alpha --bin-dir "$work/bins/debug") + + begin_case containers + printf '%s\n' "$test_image" >"$state/containers/stackrun-m0-libtest-foreign" + drive 0 SCENARIO=containers -- "${alpha_args[@]}" + name="stackrun-m0-libtest-sample-$(value run)-db" + check_equal "containers.txt lists exactly the container the run made" "$name" "$(contents "$out/containers.txt")" + check "docker run is detached, named and given a cidfile" has "run --detach --name $name --cidfile $out/.raw/" "$state/docker.argv" + check "it is labelled, published on 127.0.0.1 only and given the env file" \ + has "--label registry.journey.run=$(value run) --publish 127.0.0.1::5432 -e PLAIN=1 --env-file $out/secrets/container-db.env $test_image" "$state/docker.argv" + check "no docker network command ran" lacks network "$state/docker.argv" + check_equal "the host port is read back from docker port" 49153 "$(value port)" + check_equal "the bridge address is read from docker inspect" 172.17.0.9 "$(value address)" + check "cleanup removes the container by its exact name and nothing else" only_rm_of "$name" "$state/docker.argv" + check "the fake no longer holds it" no_file "$state/containers/$name" + check "a container the run did not make is still there" test -f "$state/containers/stackrun-m0-libtest-foreign" + check "the leftover check names it" has "leftover container stackrun-m0-libtest-foreign still exists" "$last_err" + check_equal "run.json records the leftover" stackrun-m0-libtest-foreign "$(json '.leftovers | join(",")' "$out/run.json")" + check_equal "run.json records the image by digest" "$test_image" "$(json '.images[0].image' "$out/run.json")" + check "the password reached Docker in the env file" env_file_carries_secret "$state/env-file.$name" + check "the password is on no docker argument list" no_secret_in "$state/docker.argv" + check "the password is in no saved output" no_secret_in "$out" + check "the container log is saved" has "fake log of $name" "$out/containers/db.log.stdout" + check "the secrets folder is gone after the run" no_file "$out/secrets" + check_equal "a cleanup hook runs before the containers are removed" container-present "$(contents "$state/hook-ran")" + check_equal "run.json records the address class" bridge "$(json '.addressClass' "$out/run.json")" + + begin_case cleanup-hook-fails + drive 3 SCENARIO=containers HOOK=fail -- "${alpha_args[@]}" + name="stackrun-m0-libtest-sample-$(value run)-db" + check "a failing cleanup hook is a cleanup failure" has "cleanup failure: cleanup hook driver_cleanup_hook failed" "$last_err" + check "cleanup carries on and removes the container" only_rm_of "$name" "$state/docker.argv" + + begin_case container-timed + drive 0 SCENARIO=containers -- "${alpha_args[@]}" --timed + check "--timed refuses image pulls" has "--env-file $out/secrets/container-db.env --pull never $test_image" "$state/docker.argv" + check_equal "run.json records --timed" true "$(json '.timed' "$out/run.json")" + + begin_case container-not-ready + drive 3 SCENARIO=containers WAIT_PROBE=false WAIT_SECONDS=1 -- "${alpha_args[@]}" + name="stackrun-m0-libtest-sample-$(value run)-db" + check "a container not ready in time is a harness failure" has "was not ready within 1 seconds" "$last_err" + check "its log is saved" has "fake log of $name" "$out/containers/db.log.stdout" + check "it is removed" only_rm_of "$name" "$state/docker.argv" + + begin_case container-port-base + mkdir -p "$work/mount" + drive 0 SCENARIO=containers JOURNEY_PORT_BASE=38040 EXTRA_PORT=8080 CONTAINER_OPTS="-v $work/mount:/data:ro" -- "${alpha_args[@]}" + check "fixed ports count up from JOURNEY_PORT_BASE on 127.0.0.1" \ + has "--publish 127.0.0.1:38040:5432 --publish 127.0.0.1:38041:8080 -e PLAIN=1 -v $work/mount:/data:ro" "$state/docker.argv" + check_equal "the port is read back" 38040 "$(value port)" + + begin_case container-refusals + for options in "--network host" "--network=bridge" "--net host" "-p 5432:5432" "-p5432:5432" \ + "--publish 5432" "--publish-all" "-P" "--privileged" "--name other" "-d" "--detach" "--rm" \ + "--cidfile /dev/null" "--pull always" "--mount type=volume,dst=/data" "-v data:/var/lib/data" "-vdata:/data"; do + drive 3 SCENARIO=containers CONTAINER_OPTS="$options" -- "${alpha_args[@]}" + check "'$options' is refused as a journey script error" has "journey script error" "$last_err" + done + drive 3 SCENARIO=containers CONTAINER_IMAGE=registry.test/fake/postgres:17 -- "${alpha_args[@]}" + check "an image not pinned by digest is refused" has "is not pinned by digest" "$last_err" + check_equal "no refused container reached docker run" 0 "$(verb_count run "$state/docker.argv")" + + begin_case container-occupied + : >"$state/every-name-exists" + drive 3 SCENARIO=containers -- "${alpha_args[@]}" + check "an existing name is a harness failure" has "already exists; the journey never adopts one" "$last_err" + check_equal "docker run never ran" 0 "$(verb_count run "$state/docker.argv")" + check_equal "and nothing was removed" 0 "$(verb_count rm "$state/docker.argv")" + check_equal "containers.txt is empty" '' "$(contents "$out/containers.txt")" + + begin_case container-inspect-error + : >"$state/inspect-fails" + drive 3 SCENARIO=containers -- "${alpha_args[@]}" + check "a Docker error is not taken for an absent container" has "cannot tell whether container" "$last_err" + check_equal "docker run never ran" 0 "$(verb_count run "$state/docker.argv")" + + begin_case container-created-then-failed + : >"$state/fail-after-create" + drive 3 SCENARIO=containers -- "${alpha_args[@]}" + name="stackrun-m0-libtest-sample-$(value run)-db" + check_equal "containers.txt lists the container Docker created" "$name" "$(contents "$out/containers.txt")" + check "cleanup removes it by name" only_rm_of "$name" "$state/docker.argv" + check "the fake no longer holds it" no_file "$state/containers/$name" + check "Docker's error is saved" has "fake failure after create" "$out/containers/db.run.stderr" + check "a harness failure writes no summary" no_file "$out/summary.json" + + begin_case container-start-failed + : >"$state/fail-start" + drive 3 SCENARIO=containers -- "${alpha_args[@]}" + check_equal "a container Docker never created is not listed" '' "$(contents "$out/containers.txt")" + check_equal "and nothing is removed" 0 "$(verb_count rm "$state/docker.argv")" + + begin_case container-run-interrupted + : >"$state/hang-after-create" + launch SCENARIO=containers -- "${alpha_args[@]}" + if wait_for_container; then + kill -TERM -- "-$launched" + else + problem "the fake docker run never created its container" + fi + collect 143 + name="stackrun-m0-libtest-sample-$(value run)-db" + check_equal "a container whose docker run was interrupted is listed" "$name" "$(contents "$out/containers.txt")" + check "and removed" only_rm_of "$name" "$state/docker.argv" + + # Docker writes the cidfile only after the container exists, so an + # interrupt can fall between the two. + begin_case container-run-interrupted-before-cidfile + : >"$state/hang-before-cidfile" + launch SCENARIO=containers -- "${alpha_args[@]}" + if wait_for_container; then + kill -TERM -- "-$launched" + else + problem "the fake docker run never created its container" + fi + collect 143 + name="stackrun-m0-libtest-sample-$(value run)-db" + check_equal "a container created before its cidfile was written is found by its name and listed" \ + "$name" "$(contents "$out/containers.txt")" + check "and removed" only_rm_of "$name" "$state/docker.argv" + check "the fake no longer holds it" directory_empty "$state/containers" + + begin_case container-run-interrupted-unanswered + : >"$state/hang-before-cidfile" + launch SCENARIO=containers -- "${alpha_args[@]}" + if wait_for_container; then + : >"$state/inspect-fails" + kill -TERM -- "-$launched" + else + problem "the fake docker run never created its container" + fi + collect 143 + name="stackrun-m0-libtest-sample-$(value run)-db" + check "a lookup Docker cannot answer is a cleanup failure that names the container" \ + has "cannot tell whether the interrupted docker run created $name" "$last_err" + check_equal "run.json records it" 1 \ + "$(json '[.cleanup.failures[] | select(contains("cannot tell whether"))] | length' "$out/run.json")" + check_equal "nothing is removed on a guess" 0 "$(verb_count rm "$state/docker.argv")" + + begin_case container-stopped + : >"$state/stopped" + drive 3 SCENARIO=containers -- "${alpha_args[@]}" + name="stackrun-m0-libtest-sample-$(value run)-db" + check "a container that stops before it is ready is a harness failure" has "stopped before it was ready" "$last_err" + check "its log is saved" has "fake log of $name" "$out/containers/db.log.stdout" + check "it is removed" only_rm_of "$name" "$state/docker.argv" + + begin_case docker-daemon-down + : >"$state/daemon-down" + drive 2 SCENARIO=containers -- "${alpha_args[@]}" + check "a missing Docker daemon is a missing prerequisite" has "needs a running Docker daemon" "$last_err" + + begin_case cleanup-failure + : >"$state/rm-fails" + drive 3 SCENARIO=containers -- "${alpha_args[@]}" + name="stackrun-m0-libtest-sample-$(value run)-db" + check "the failed removal is reported with the name to remove" has "cleanup failure: docker rm --force --volumes $name failed" "$last_err" + check_equal "run.json records it" 1 "$(json '.cleanup.failures | length' "$out/run.json")" + check_equal "run.json records exit status 3" 3 "$(json '.exitStatus' "$out/run.json")" + + begin_case cleanup-failure-after-product-failure + : >"$state/rm-fails" + drive 3 SCENARIO=containers CELL_alpha=fail:call:product.call.refused -- "${alpha_args[@]}" + check "a cleanup failure outranks a product failure" has "cleanup failure" "$last_err" +} + +case_keep_and_take_over() { + local name kept_run kept_state + local -a alpha_args=(--product alpha --bin-dir "$work/bins/debug") + + begin_case keep + drive 0 SCENARIO=containers START_SERVER=1 -- "${alpha_args[@]}" --keep + kept_run=$out + kept_state=$state + name="stackrun-m0-libtest-sample-$(value run)-db" + check_equal "--keep leaves the container" 0 "$(verb_count rm "$state/docker.argv")" + check "and names it" has "kept container $name" "$last_err" + check "the kept marker is written" test -f "$kept_run/kept" + check_equal "the kept secret keeps mode 600" 600 "$(mode_of "$kept_run/secrets/db-password")" + check_equal "the kept secrets folder keeps mode 700" 700 "$(mode_of "$kept_run/secrets")" + check "the server process is stopped all the same" process_gone "$(contents "$state/alpha.pid")" + check_equal "run.json records --keep" true "$(json '.keep' "$kept_run/run.json")" + check "saved output outside secrets/ holds no secret" no_secret_in "$kept_run" + + begin_case take-over-refusals + drive 2 SCENARIO=takeover JOURNEY_CONTAINER_PREFIX=stackrun-m0-other -- "${alpha_args[@]}" --from "$kept_run" + check "a run of another prefix is refused" has "used container prefix stackrun-m0-libtest" "$last_err" + drive 2 SCENARIO=takeover -- "${alpha_args[@]}" --from "$finished_run" + check "a run that did not end with --keep is refused" has "is not a run that ended with --keep" "$last_err" + check "the kept run is untouched" test -f "$kept_run/secrets/db-password" + + begin_case take-over + state=$kept_state + cat -- "$work/patterns/keep" >>"$patterns" + drive 0 SCENARIO=takeover -- "${alpha_args[@]}" --from "$kept_run" + check "the later run removes the kept container" has "rm --force --volumes $name" "$state/docker.argv" + check "the fake no longer holds it" no_file "$state/containers/$name" + check "the kept secrets are deleted" no_file "$kept_run/secrets" + check "the kept secret is redacted in the later run's output" has "[redacted:db-password]" "$out/alpha/prepare.stdout" + check "no saved output of either run holds it" no_secret_in "$out" "$kept_run" + check_equal "run.json names the run taken over" "$kept_run" "$(json '.takenOver' "$out/run.json")" +} + +case_interrupts() { + local signal want name + local -a alpha_args=(--product alpha --bin-dir "$work/bins/debug") + for signal in TERM INT; do + case "$signal" in + TERM) want=143 ;; + INT) want=130 ;; + esac + begin_case "interrupt-$signal" + launch SCENARIO=interrupt -- "${alpha_args[@]}" + if wait_for_file "$state/alpha.pid"; then + sleep 0.2 + kill "-$signal" "$launched" + else + problem "the step never started" + fi + collect "$want" + name="stackrun-m0-libtest-sample-$(value run)-db" + check "the step's process is stopped" process_gone "$(contents "$state/alpha.pid")" + check "the container is removed" only_rm_of "$name" "$state/docker.argv" + check "the secrets folder is deleted" no_file "$out/secrets" + check "the journey went no further" lacks after-step "$report" + check_equal "run.json records the signal's exit status" "$want" "$(json '.exitStatus' "$out/run.json")" + done + + begin_case script-error + drive 3 SCENARIO=error -- "${alpha_args[@]}" + name="stackrun-m0-libtest-sample-$(value run)-db" + check "an error in the journey script is a harness failure" has "stopped before journey_finish (exit status 1)" "$last_err" + check "cleanup still removes the container" only_rm_of "$name" "$state/docker.argv" + check_equal "run.json records it" 3 "$(json '.exitStatus' "$out/run.json")" +} + +case_secrets() { + local redacted marker + local -a alpha_args=(--product alpha --bin-dir "$work/bins/debug") + + begin_case secrets + drive 0 SCENARIO=secrets -- "${alpha_args[@]}" + check_equal "a generated secret has mode 600" 600 "$(value secret-mode)" + check_equal "it holds 24 random bytes as hexadecimal" 48 "$(value secret-length)" + check_equal "an env file has mode 600" 600 "$(value env-mode)" + check_equal "an env file sets the variable to the secret's value" ok "$(value env-file)" + redacted="$(value redacted)" + for marker in '[redacted:api-key]' '[redacted:access-token]' '[redacted:private-key]' '[redacted:jwt]' \ + 'Authorization: [redacted]' '> Cookie: [redacted]' 'Bearer [redacted]' 'postgres://registry:[redacted]@127.0.0.1' \ + '"access_token": "[redacted]"' '"password": "[redacted]"' '"note": "kept"'; do + check "redaction writes $marker" has "$marker" "$redacted" + done + check "the redacted copy holds no secret value" no_secret_in "$redacted" + check "no saved output holds one" no_secret_in "$out" + check "the secrets folder is gone after the run" no_file "$out/secrets" + check "the raw folder is gone after the run" no_file "$out/.raw" + check_equal "the final scan found nothing" clean "$(json '.secretScan' "$out/run.json")" + + begin_case secret-refusals + drive 3 SCENARIO=secret-short -- --product alpha + check "a secret of fewer than 16 bytes is refused" has "a secret needs at least 16 random bytes" "$last_err" + drive 3 SCENARIO=register-short -- --product alpha + check "a registered value of fewer than 8 characters is refused" has "shorter than 8 characters" "$last_err" + + begin_case leak-secret + drive 3 SCENARIO=leak LEAK=secret -- "${alpha_args[@]}" + check "a secret written past redaction is found and named by label" has "leak.txt: the value of secret api-key" "$last_err" + check "the finding does not print the value" no_secret_in "$last_err" "$last_out" + check_equal "run.json records the finding" found "$(json '.secretScan' "$out/run.json")" + check_equal "a passing run that leaked exits 3" 3 "$(json '.exitStatus' "$out/run.json")" + + begin_case leak-jwt + drive 3 SCENARIO=leak LEAK=jwt -- "${alpha_args[@]}" + check "a compact JWT in saved output is found" has "leak.txt: a compact JWT" "$last_err" +} + +case_http() { + local token + begin_case http + token="tok$(random_hex 16)" + printf '%s\n' "$token" >>"$patterns" + printf 'Authorization: Bearer %s\n' "$token" >"$work/expected-header" + printf '{"access_token": "%s", "token_type": "Bearer", "expires_in": 300}\n' "$token" >"$state/http-body.1" + printf '401\n' >"$state/http-status.2" + printf '{"type": "about:blank", "code": "auth.issuer-refused", "detail": "the issuer is not accepted"}\n' >"$state/http-body.2" + drive 1 SCENARIO=http -- --product alpha + check_equal "the captured token has its full length" "${#token}" "$(value token-length)" + check_equal "the status is read" 401 "$(value http-status)" + check_equal "the problem code is read from the body" auth.issuer-refused "$(value problem-code)" + check "the token reached curl as a header read through a file descriptor" grep -qxF -f "$work/expected-header" "$state/curl.headers" + check "the other header came the same way" grep -qxF 'Accept: application/json' "$state/curl.headers" + check "the client secret reached curl as a form value read from its file" form_has_secret "$state/curl.form" client_secret + check "no curl argument list holds the token or the client secret" no_secret_in "$state/curl.argv" + check "no saved output holds them" no_secret_in "$out" + check "the token in the saved body is redacted" has '"access_token": "[redacted]"' "$out/alpha/start.stdout" + check "the response status line is saved" has "HTTP/1.1 401" "$out/alpha/call.http" + check "request headers are never saved" lacks Authorization "$out/alpha/call.http" + check "the failure is recorded with its code" has $'alpha\tcall\tfail\thttp.401.issuer' "$out/cells.tsv" + check "a cookie jar is kept among the secrets and given to curl both ways" \ + has "--cookie $out/secrets/cookies-session --cookie-jar $out/secrets/cookies-session" "$state/curl.argv" + check "and deleted with them" no_file "$out/secrets" + + begin_case step-and-http-options + : >"$state/curl-fails" + drive 1 SCENARIO=options -- --product alpha --bin-dir "$work/bins/debug" + check "--cwd runs the command in that folder" has "cwd=$out/work/alpha" "$out/alpha/prepare.stdout" + check "--stdin gives it the file as input" has "stdin=reader input" "$out/alpha/prepare.stdout" + check_equal "--doc-words is counted" 40 "$(json '.total.documentationWords' "$out/alpha/cell.json")" + check_equal "--typed replaces the command's own text (11) beside the request's default text (42)" \ + 53 "$(json '.total.charactersTyped' "$out/alpha/cell.json")" + check "--location reaches curl" has "--location" "$state/curl.argv" + check "--data-file reaches curl as a file to read" has "--data-binary @$out/work/alpha/input.txt" "$state/curl.argv" + check_equal "a request with no answer has status 000" 000 "$(value curl-status)" + check "and fails with the journey's code" has $'alpha\tstart\tfail\tproduct.http.no-answer' "$out/cells.tsv" + + begin_case http-credential-header + drive 3 SCENARIO=http-header -- --product alpha + check "a credential passed as a header is refused" has "pass a token with --bearer VAR, never as a header" "$last_err" + check "curl never ran" no_file "$state/curl.argv" +} + +case_modes() { + local table="$work/tables/expected-failures.yaml" + local -a run_args=(--bin-dir "$work/bins/debug") + + begin_case acceptance-all-pass + drive 0 CELL_beta=pass CELL_gamma=pass CELL_delta=pass -- "${run_args[@]}" + check_equal "every cell is ok" 4 "$(json '[.cells[] | select(.verdict == "ok")] | length' "$out/summary.json")" + + begin_case acceptance-failures + drive 1 -- "${run_args[@]}" + check_equal "a failed cell is not-passed" not-passed "$(json '.cells[] | select(.product == "beta") | .verdict' "$out/summary.json")" + check_equal "so is an unreached cell" not-passed "$(json '.cells[] | select(.product == "gamma") | .verdict' "$out/summary.json")" + + begin_case ratchet-equal + drive 0 -- "${run_args[@]}" --expected "$table" + check_equal "every cell equals its row" 4 "$(json '[.cells[] | select(.verdict == "ok")] | length' "$out/summary.json")" + check_equal "summary.json names the mode" ratchet "$(json '.mode' "$out/summary.json")" + check_equal "the printed table shows the cell, its row and the verdict" \ + "beta fail call http.401.issuer fail call http.401.issuer ok" "$(row_words beta "$last_out")" + + begin_case ratchet-equal-strict + drive 0 -- "${run_args[@]}" --expected "$table" --strict + + begin_case ratchet-other-code + drive 1 CELL_beta=fail:call:http.401.audience -- "${run_args[@]}" --expected "$table" + check_equal "another code is a mismatch" mismatch "$(json '.cells[] | select(.product == "beta") | .verdict' "$out/summary.json")" + + begin_case ratchet-other-step + drive 1 CELL_beta=fail:start:http.401.issuer -- "${run_args[@]}" --expected "$table" + check_equal "another step is a mismatch" mismatch "$(json '.cells[] | select(.product == "beta") | .verdict' "$out/summary.json")" + + begin_case ratchet-unreached-elsewhere + drive 1 CELL_gamma=unreached:start -- "${run_args[@]}" --expected "$table" + check_equal "unreached at another step is a mismatch" mismatch "$(json '.cells[] | select(.product == "gamma") | .verdict' "$out/summary.json")" + + begin_case ratchet-stale + drive 0 CELL_beta=pass -- "${run_args[@]}" --expected "$table" + check "a listed failure that passes is a warning" has "warning: a listed failure no longer fails" "$last_err" + check_equal "its verdict is stale" stale "$(json '.cells[] | select(.product == "beta") | .verdict' "$out/summary.json")" + + begin_case ratchet-stale-strict + drive 1 CELL_beta=pass -- "${run_args[@]}" --expected "$table" --strict + check "--strict makes it an error" has "a listed failure no longer fails: delete its row" "$last_err" + + begin_case ratchet-unlisted + drive 1 -- "${run_args[@]}" --expected "$work/tables/expected-unlisted.yaml" + check_equal "a cell with no row is unlisted" unlisted "$(json '.cells[] | select(.product == "delta") | .verdict' "$out/summary.json")" + + begin_case ratchet-listed-twice + drive 1 -- "${run_args[@]}" --expected "$work/tables/expected-twice.yaml" + check_equal "a cell with two rows is listed-twice" listed-twice "$(json '.cells[] | select(.product == "alpha") | .verdict' "$out/summary.json")" + + begin_case needs + drive 1 CELL_alpha=needs:start:hand-written-sql -- --product alpha "${run_args[@]}" + check "journey_needs records journey.needs.THING" has $'alpha\tstart\tfail\tjourney.needs.hand-written-sql' "$out/cells.tsv" + + begin_case poll-runs-out + drive 1 CELL_alpha=poll:call -- --product alpha "${run_args[@]}" + check "journey_poll gives up after its seconds and says so" has "did not succeed within 2 seconds" "$out/alpha/call.stderr" + check "the step then fails with the journey's code" has $'alpha\tcall\tfail\tproduct.poll.timed-out' "$out/cells.tsv" + + begin_case harness-failure + drive 3 CELL_beta=harness:call -- "${run_args[@]}" --expected "$table" + check "a harness failure is named" has "harness failure: a harness failure the test asked for" "$last_err" + check "and never recorded as a product outcome" no_file "$out/summary.json" + check_equal "run.json records it" "a harness failure the test asked for" "$(json '.harnessFailure' "$out/run.json")" +} + +case_discipline() { + local violation + begin_case cell-discipline + for violation in pass-after-fail begin-twice end-without-last unknown-step unresolved unknown-concept \ + unknown-suffix unknown-stage bad-code after-stop unknown-counter library-name missing-cell; do + drive 3 SCENARIO=discipline DISCIPLINE="$violation" -- --product alpha --bin-dir "$work/bins/debug" + check "$violation is a journey script error" has "journey script error" "$last_err" + done +} + +case_steps_and_processes() { + local mode pid + local -a alpha_args=(--product alpha --bin-dir "$work/bins/debug") + for mode in sleep stubborn; do + begin_case "step-timeout-$mode" + drive 3 SCENARIO=timeout TIMEOUT_MODE="$mode" -- "${alpha_args[@]}" + check "a step past its deadline is a harness failure" has "did not finish within 1 seconds" "$last_err" + check "its process is stopped" process_gone "$(contents "$state/alpha.pid")" + check "its output so far is saved" test -f "$out/alpha/prepare.stdout" + done + + begin_case processes + drive 0 SCENARIO=processes -- "${alpha_args[@]}" + pid="$(contents "$state/alpha.pid")" + check_equal "the server runs between start and stop" yes "$(value running)" + check_equal "it stops on SIGTERM with status 0" 0 "$(value stop-status)" + check "processes.txt records it" has "$pid"$'\talpha\tserver' "$out/processes.txt" + check "it is gone after the run" process_gone "$pid" + check "its output is saved" has serving "$out/alpha/start.stdout" + check "including what it printed on SIGTERM" has stopping "$out/alpha/start.stdout" + check "a secret it printed is redacted" has "loaded key [redacted:server-key]" "$out/alpha/start.stderr" + check "no saved output holds the secret" no_secret_in "$out" + check_equal "journey_process_log names the redacted log" "$out/alpha/start.stderr" "$(value log)" + + begin_case process-ignores-term + drive 1 SCENARIO=processes PROCESS_MODE=stubborn -- "${alpha_args[@]}" + check "journey_stop reports a process that had to be killed" has $'alpha\tstop\tfail\tproduct.stop.ignored-signal' "$out/cells.tsv" + check "it is gone" process_gone "$(contents "$state/alpha.pid")" + + begin_case process-exits-at-once + drive 1 SCENARIO=processes PROCESS_MODE=exit-now -- "${alpha_args[@]}" + check_equal "journey_start returns the exit status of a process that stopped" 5 "$(value start-status)" + check "its output is saved" has "product.start.refused" "$out/alpha/start.stderr" +} + +case_assists() { + local -a alpha_args=(--product alpha --bin-dir "$work/bins/debug") + local cell + + begin_case assist-used + drive 1 JOURNEY_ASSISTS_FILE="$work/assists.sh" CELL_alpha=blocker:call:journey.needs.certificate:certificate -- \ + "${alpha_args[@]}" --assist certificate + cell="$out/alpha/cell.json" + check_equal "the assist ran with the journey's arguments" "$out/work" "$(contents "$state/assist-ran")" + check_equal "an assisted cell is not a pass" assisted "$(json '.outcome' "$cell")" + check_equal "the blocker is recorded" journey.needs.certificate "$(json '.blockers[0].code' "$cell")" + check_equal "the assist is counted" 1 "$(json '.total.assistsUsed' "$cell")" + check_equal "a certificate assist counts a certificate" 1 "$(json '.passRule."certificates-made"' "$cell")" + check "cells.tsv records the step as assisted" has $'alpha\tcall\tassisted\tjourney.needs.certificate' "$out/cells.tsv" + check_equal "acceptance mode does not pass it" not-passed "$(json '.cells[0].verdict' "$out/summary.json")" + + begin_case assist-not-enabled + drive 1 JOURNEY_ASSISTS_FILE="$work/assists.sh" CELL_alpha=blocker:call:journey.needs.certificate:certificate -- "${alpha_args[@]}" + check_equal "without --assist the blocker stops the cell" fail "$(json '.outcome' "$out/alpha/cell.json")" + check "and the assist does not run" no_file "$state/assist-ran" + + begin_case assist-refusals + drive 2 JOURNEY_ASSISTS_FILE="$work/assists.sh" -- "${alpha_args[@]}" --assist warp + check "an assist the file does not define is refused" has "defines no journey_assist_warp" "$last_err" + drive 2 JOURNEY_ASSISTS_FILE="$work/no-assists.sh" -- "${alpha_args[@]}" --assist certificate + check "a missing assists file is refused" has "which does not exist" "$last_err" +} + +case_files() { + local cell + begin_case files + drive 0 SCENARIO=files -- --product alpha + cell="$out/alpha/cell.json" + check_equal "the written file is the reader's text with the edit" $'ab: 1\ncd: 20\nef: 3' "$(contents "$out/work/alpha/alpha.yaml")" + check_equal "one file is touched" 1 "$(json '.total.filesTouched' "$cell")" + check_equal "three lines written and one edited" 4 "$(json '.total.linesWritten' "$cell")" + check_equal "18 characters written and 6 typed in the edit" 24 "$(json '.total.charactersTyped' "$cell")" + check_equal "both concepts are counted" 'runtime-file issuer' "$(json '.total.concepts | join(" ")' "$cell")" + check_equal "t1 snapshots the lines written by then" 3 "$(json '.passRule."lines-written-to-t1"' "$cell")" + check_equal "and the concepts met by then" 1 "$(json '.passRule."concepts-met-to-t1"' "$cell")" + check_equal "journey_count adds to the errors that say what to change" 2 "$(json '.passRule."errors-that-say-what-to-change"' "$cell")" + check_equal "and to the identity-provider changes" 1 "$(json '.passRule."identity-provider-changes"' "$cell")" + check_equal "the reader time to t1 follows the model (18/200 + 3*30/60 + 1*60/60)" 2.59 "$(json '.passRule."reader-time-to-t1-modelled"' "$cell")" + check_equal "the reader time to t2 follows the model (24/200 + 4*30/60 + 2*60/60)" 4.12 "$(json '.passRule."reader-time-to-t2-modelled"' "$cell")" + + begin_case file-refusals + drive 3 SCENARIO=files FILES_MODE=outside -- --product alpha + check "a reader's file outside work/ is refused" has "must be under" "$last_err" + drive 3 SCENARIO=files FILES_MODE=twice -- --product alpha + check "an edit whose text occurs twice is refused" has "occurs 2 times" "$last_err" +} + +# The tables beside the library, replayed row by row: every product of +# products.yaml has exactly one row per journey, every code is accepted and +# ratchet mode with --strict exits 0. +case_real_tables() { + local journey + for journey in own-provider rstack-dev promote; do + begin_case "real-table-$journey" + drive 0 TEST_JOURNEY="$journey" SCENARIO=replay JOURNEY_TABLES_DIR= -- --expected "$lib_dir/expected-failures.yaml" --strict + check "the table names at least one product" test "$(value replayed)" -gt 0 + check_equal "every product has a cell" "$(value replayed)" "$(json '.cells | length' "$out/summary.json")" + check_equal "every cell equals its row" 0 "$(json '[.cells[] | select(.verdict != "ok")] | length' "$out/summary.json")" + done +} + +cleanup_work() { + local status=$? + if [[ -n "$launched" ]]; then + kill -KILL -- "-$launched" 2>/dev/null || : + fi + if [[ "${TEST_LIB_KEEP:-0}" == 1 ]]; then + printf 'test_lib: kept %s\n' "$work" >&2 + exit "$status" + fi + case "$work" in + "$tmp_root"/journey-lib-test.??????) ;; + *) + printf 'test_lib: refusing to delete %s\n' "$work" >&2 + exit 3 + ;; + esac + if ! rm -r -- "$work"; then + printf 'test_lib: could not delete %s; delete it by hand\n' "$work" >&2 + [[ $status -ne 0 ]] || status=3 + fi + exit "$status" +} + +test_main() { + local tool + lib="${JOURNEY_LIB_UNDER_TEST:-${self%/*}/lib.sh}" + if [[ ! -f "$lib" ]]; then + printf 'test_lib: no library at %s\n' "$lib" >&2 + exit 2 + fi + lib="$(CDPATH='' cd -- "$(dirname -- "$lib")" && pwd -P)/${lib##*/}" + lib_dir=${lib%/*} + root="$(CDPATH='' cd -- "$lib_dir/../../.." && pwd -P)" + for tool in jq perl python3; do + if ! command -v "$tool" >/dev/null 2>&1; then + printf 'test_lib: needs %s on PATH\n' "$tool" >&2 + exit 2 + fi + done + tmp_root="$(CDPATH='' cd -- "${TMPDIR:-/tmp}" && pwd -P)" + work="$(mktemp -d "$tmp_root/journey-lib-test.XXXXXX")" + trap cleanup_work EXIT + chmod 700 "$work" + test_path="$work/bin:$work/tools:/usr/bin:/bin:/usr/sbin:/sbin" + write_fixtures + # From here the test itself uses the same commands as the journeys it runs. + PATH=$test_path + printf 'test_lib: bash %s, library %s\n' "$BASH_VERSION" "$lib" + case_usage + case_binaries + case_run_directories + case_containers + case_keep_and_take_over + case_interrupts + case_secrets + case_http + case_modes + case_discipline + case_steps_and_processes + case_assists + case_files + case_real_tables + finish_case + if [[ $failed_checks -gt 0 ]]; then + printf 'test_lib: %s of %s checks failed\n' "$failed_checks" "$checks" + exit 1 + fi + printf 'test_lib: all %s checks passed\n' "$checks" +} + +case "${1:-}" in +--fake) + shift + fake_main "$@" + ;; +--driver) + shift + # shellcheck source=/dev/null + source "${JOURNEY_LIB_UNDER_TEST:?}" + driver_main "$@" + ;; +*) + test_main "$@" + ;; +esac diff --git a/scripts/test_cargo_runtime_script_contracts.py b/scripts/test_cargo_runtime_script_contracts.py index 33fff235cf..532d733843 100755 --- a/scripts/test_cargo_runtime_script_contracts.py +++ b/scripts/test_cargo_runtime_script_contracts.py @@ -45,6 +45,11 @@ "REGISTRY_CARGO_RUNTIME_LIBRARY_PATH", "run-config-conformance.py", ), + "products/platform/journeys/lib.sh": ( + "cargo-runtime-library-path.sh", + "registry_cargo_build", + "REGISTRY_CARGO_RUNTIME_LIBRARY_PATH", + ), "products/breg/loadtest/up.sh": ( "cargo-runtime-library-path.sh", "registry_cargo_build", @@ -71,7 +76,7 @@ class CargoRuntimeScriptContractTests(unittest.TestCase): def test_every_reported_gate_keeps_its_runtime_and_override_contract(self): - self.assertEqual(len(CONTRACTS), 17) + self.assertEqual(len(CONTRACTS), 18) for relative, markers in CONTRACTS.items(): with self.subTest(script=relative): source = (ROOT / relative).read_text(encoding="utf-8") From 83f3b5b0a47ee95efa64365b5581d58a4d65a805 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:46:50 +0100 Subject: [PATCH 011/136] feat(scheduling): answer a grant with too much lifetime left with its own code On the offline path a task grant may have at most fifteen minutes left. A grant with more than that was refused as operation.not-authorized, the same answer as a grant that does not cover the offering, so the caller could not tell that it only needed a shorter grant. It now answers 403 grant.lifetime-too-long, and only after the grant's bounds have matched the offering, so the code says nothing about what the grant reaches. Every other refusal keeps its code. Signed-off-by: Jeremi Joslin --- .../client.d.ts | 1 + .../registry_scheduling_client/__init__.pyi | 1 + .../registry-scheduling-core/src/problem.rs | 27 +++- crates/registry-scheduling/src/service.rs | 128 +++++++++++++----- .../tests/postgres_commitments.rs | 69 +++++++++- .../scheduling/client.d.ts | 1 + .../reference/apis/registry-scheduling.mdx | 4 +- .../docs/reference/scheduling-task-grants.mdx | 4 +- .../src/content/docs/security/scheduling.mdx | 5 +- docs/site/src/data/scheduling-api.yaml | 1 + .../identifiers/generated/catalog.v1.json | 87 +++++++----- products/scheduling/CHANGELOG.md | 9 ++ .../contracts/security-invariant-matrix.yaml | 4 +- .../contracts/security-test-traceability.yaml | 3 +- .../generated/fixture/fixture.schema.json | 1 + .../registry-scheduling.openapi.json | 63 ++++++++- .../scheduling/scripts/generate_openapi.py | 17 ++- .../scripts/test_generate_openapi.py | 20 ++- 18 files changed, 352 insertions(+), 93 deletions(-) diff --git a/crates/registry-scheduling-client-node/client.d.ts b/crates/registry-scheduling-client-node/client.d.ts index 85c57ef2f3..4978b07c7a 100644 --- a/crates/registry-scheduling-client-node/client.d.ts +++ b/crates/registry-scheduling-client-node/client.d.ts @@ -316,6 +316,7 @@ export type SchedulingProblemCode = | 'cursor.expired' | 'cursor.invalid' | 'eligibility.unavailable' + | 'grant.lifetime-too-long' | 'hold.expired' | 'hold.released' | 'hook.unavailable' diff --git a/crates/registry-scheduling-client-py/python/registry_scheduling_client/__init__.pyi b/crates/registry-scheduling-client-py/python/registry_scheduling_client/__init__.pyi index 258ca4cfef..d8aafe3d40 100644 --- a/crates/registry-scheduling-client-py/python/registry_scheduling_client/__init__.pyi +++ b/crates/registry-scheduling-client-py/python/registry_scheduling_client/__init__.pyi @@ -400,6 +400,7 @@ SchedulingProblemCode: TypeAlias = Literal[ "cursor.expired", "cursor.invalid", "eligibility.unavailable", + "grant.lifetime-too-long", "hold.expired", "hold.released", "hook.unavailable", diff --git a/crates/registry-scheduling-core/src/problem.rs b/crates/registry-scheduling-core/src/problem.rs index f321411773..112857b9f9 100644 --- a/crates/registry-scheduling-core/src/problem.rs +++ b/crates/registry-scheduling-core/src/problem.rs @@ -26,6 +26,7 @@ pub const CAPACITY_EXHAUSTED_PROBLEM: &str = "capacity.exhausted"; pub const CURSOR_EXPIRED_PROBLEM: &str = "cursor.expired"; pub const CURSOR_INVALID_PROBLEM: &str = "cursor.invalid"; pub const ELIGIBILITY_UNAVAILABLE_PROBLEM: &str = "eligibility.unavailable"; +pub const GRANT_LIFETIME_TOO_LONG_PROBLEM: &str = "grant.lifetime-too-long"; pub const HOLD_EXPIRED_PROBLEM: &str = "hold.expired"; pub const HOLD_RELEASED_PROBLEM: &str = "hold.released"; pub const HORIZON_OUTSIDE_PROBLEM: &str = "horizon.outside"; @@ -63,6 +64,7 @@ pub enum ProblemCode { CursorExpired, CursorInvalid, EligibilityUnavailable, + GrantLifetimeTooLong, HoldExpired, HoldReleased, HookUnavailable, @@ -101,6 +103,7 @@ impl ProblemCode { Self::CursorExpired, Self::CursorInvalid, Self::EligibilityUnavailable, + Self::GrantLifetimeTooLong, Self::HoldExpired, Self::HoldReleased, Self::HookUnavailable, @@ -139,6 +142,7 @@ impl ProblemCode { Self::CursorExpired => CURSOR_EXPIRED_PROBLEM, Self::CursorInvalid => CURSOR_INVALID_PROBLEM, Self::EligibilityUnavailable => ELIGIBILITY_UNAVAILABLE_PROBLEM, + Self::GrantLifetimeTooLong => GRANT_LIFETIME_TOO_LONG_PROBLEM, Self::HoldExpired => HOLD_EXPIRED_PROBLEM, Self::HoldReleased => HOLD_RELEASED_PROBLEM, Self::HorizonOutside => HORIZON_OUTSIDE_PROBLEM, @@ -195,7 +199,9 @@ impl ProblemCode { match self { Self::CursorInvalid | Self::RequestInvalid => 400, Self::AuthenticationRefused => 401, - Self::OperationNotAuthorized | Self::ProfileNotAuthorized => 403, + Self::GrantLifetimeTooLong + | Self::OperationNotAuthorized + | Self::ProfileNotAuthorized => 403, Self::RequestNotFound => 404, Self::RequestMethodNotAllowed => 405, Self::ReceiptUnresolved => 409, @@ -236,6 +242,7 @@ impl ProblemCode { Self::CursorExpired => "Cursor expired", Self::CursorInvalid => "Cursor invalid", Self::EligibilityUnavailable => "Eligibility unavailable", + Self::GrantLifetimeTooLong => "Task grant lifetime too long", Self::HoldExpired => "Hold expired", Self::HoldReleased => "Hold released", Self::HookUnavailable => "Hook unavailable", @@ -290,6 +297,9 @@ impl ProblemCode { Self::EligibilityUnavailable => { "A required eligibility check could not run. Retry; do not treat this as permission." } + Self::GrantLifetimeTooLong => { + "The task grant has more than 900 seconds left before it expires. Present a task grant that expires within 900 seconds." + } Self::HoldExpired => { "The hold expired before confirmation. Its capacity is bookable again; start a new request." } @@ -368,7 +378,7 @@ mod tests { #[test] fn the_vocabulary_is_complete_and_closed() { - assert_eq!(ProblemCode::ALL.len(), 33); + assert_eq!(ProblemCode::ALL.len(), 34); for code in ProblemCode::ALL { assert_eq!(ProblemCode::from_code(code.code()), Some(*code)); } @@ -434,6 +444,19 @@ mod tests { /// The request-edge family is Casework's, pinned one status per code, so /// the runtime's edge and every client agree on what a rejected request /// looks like. + #[test] + fn a_grant_with_too_much_lifetime_left_has_its_own_code_and_keeps_the_status() { + let code = ProblemCode::GrantLifetimeTooLong; + assert_eq!(code.code(), "grant.lifetime-too-long"); + assert_eq!(code.http_status(), 403); + assert_eq!( + type_uri(code.code()), + format!("{SCHEDULING_PROBLEM_TYPE_BASE}grant/lifetime-too-long") + ); + assert_eq!(code.title(), "Task grant lifetime too long"); + assert!(code.detail().contains("900 seconds")); + } + #[test] fn the_request_edge_family_pins_casework_s_statuses() { assert_eq!(ProblemCode::RequestInvalid.http_status(), 400); diff --git a/crates/registry-scheduling/src/service.rs b/crates/registry-scheduling/src/service.rs index d48977b43c..18e37d28d5 100644 --- a/crates/registry-scheduling/src/service.rs +++ b/crates/registry-scheduling/src/service.rs @@ -2290,7 +2290,11 @@ impl SchedulingService { /// grant reaches would leave no audit entry. Each refusal is one `response` /// entry with a correlation of its own. What the audit gains is the /// attribution: the answer stays the same closed code, naming neither - /// the bound that failed nor whether a grant was carried at all. + /// the bound that failed nor whether a grant was carried at all. The one + /// later answer that does say a grant was carried is a current-grant + /// refusal for too much lifetime left, and it is given only after this + /// check has passed, so it tells a caller nothing about which services + /// and locations a grant reaches. async fn require_permission( &self, caller: &Caller, @@ -2418,7 +2422,7 @@ impl SchedulingService { ServiceError::internal("the task-grant clock observation is not representable") })?; let verdict = if online_required && self.task_grant_status.is_none() { - Err(TaskGrantError::Refused) + GrantVerdict::Refused } else { task_grant_verdict( self.task_grant_status.as_deref(), @@ -2429,8 +2433,8 @@ impl SchedulingService { .await }; match verdict { - Ok(()) => Ok(()), - Err(TaskGrantError::Refused) => { + GrantVerdict::Current => Ok(()), + refused @ (GrantVerdict::Refused | GrantVerdict::LifetimeTooLong) => { self.record_refusal( Uuid::new_v4(), audit_record( @@ -2444,13 +2448,19 @@ impl SchedulingService { ), ) .await?; - Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)) + Err(ServiceError::Problem( + if refused == GrantVerdict::LifetimeTooLong { + ProblemCode::GrantLifetimeTooLong + } else { + ProblemCode::OperationNotAuthorized + }, + )) } - Err(TaskGrantError::Unavailable) => { + GrantVerdict::Unavailable => { tracing::warn!("the task-grant authority could not establish current status"); Err(ServiceError::Problem(ProblemCode::ServiceUnavailable)) } - Err(TaskGrantError::Configuration) => { + GrantVerdict::Configuration => { tracing::error!("the activated task-grant status registry became unusable"); Err(ServiceError::Problem(ProblemCode::ServiceUnavailable)) } @@ -2977,29 +2987,54 @@ impl SchedulingService { } } +/// The outcome of deciding whether a task grant is current. +#[derive(Debug, PartialEq, Eq)] +enum GrantVerdict { + Current, + /// Expired, inactive, unlisted, or unbound. + Refused, + /// Unexpired on the offline path, with more than + /// `OFFLINE_TASK_GRANT_REMAINING_SECONDS` left. + LifetimeTooLong, + Unavailable, + Configuration, +} + +impl From> for GrantVerdict { + fn from(verdict: Result<(), TaskGrantError>) -> Self { + match verdict { + Ok(()) => Self::Current, + Err(TaskGrantError::Refused) => Self::Refused, + Err(TaskGrantError::Unavailable) => Self::Unavailable, + Err(TaskGrantError::Configuration) => Self::Configuration, + } + } +} + /// Decide whether one verified task grant is current at `now`, in Unix /// seconds. Listed status authorities are authoritative for every source: a /// grant without the signed subjects its status binding needs, or from a /// source no authority is listed for, is refused and never reaches the /// offline path. Without them, the offline path accepts a grant only while it -/// is unexpired with at most fifteen minutes left, and asks no authority. +/// is unexpired with at most fifteen minutes left, and asks no authority. An +/// unexpired grant with more left is `LifetimeTooLong`, distinct from `Refused` +/// so the caller learns to present a shorter-lived grant. async fn task_grant_verdict( status: Option<&TaskGrantStatusRegistry>, subjects: Option>, grant: &GrantClaims, now: u64, -) -> Result<(), TaskGrantError> { +) -> GrantVerdict { match status { Some(status) => match subjects .and_then(|subjects| TaskGrantStatusBinding::from_verified(grant, subjects).ok()) { - Some(binding) => status.check(&binding).await, - None => Err(TaskGrantError::Refused), + Some(binding) => status.check(&binding).await.into(), + None => GrantVerdict::Refused, }, - None if grant.exp() > now && grant.exp() - now <= OFFLINE_TASK_GRANT_REMAINING_SECONDS => { - Ok(()) - } - None => Err(TaskGrantError::Refused), + None if grant.exp() <= now => GrantVerdict::Refused, + None if grant.exp() - now <= OFFLINE_TASK_GRANT_REMAINING_SECONDS => GrantVerdict::Current, + None => GrantVerdict::LifetimeTooLong, } } @@ -4771,23 +4806,23 @@ mod tests { } #[tokio::test] - async fn the_offline_path_accepts_only_an_unexpired_grant_with_at_most_fifteen_minutes_left() { + async fn the_offline_path_tells_a_grant_with_too_much_lifetime_from_an_expired_one() { let now = u64::try_from(at(9, 0).timestamp()).expect("a representable instant"); for (case, expires_at, expected) in [ - ("one second left", now + 1, Ok(())), - ("exactly fifteen minutes left", now + 900, Ok(())), + ("one second left", now + 1, GrantVerdict::Current), ( - "one second more than fifteen minutes left", - now + 901, - Err(TaskGrantError::Refused), + "exactly fifteen minutes left", + now + 900, + GrantVerdict::Current, ), - ("an hour left", now + 3_600, Err(TaskGrantError::Refused)), ( - "expiring at request entry", - now, - Err(TaskGrantError::Refused), + "one second more than fifteen minutes left", + now + 901, + GrantVerdict::LifetimeTooLong, ), - ("expired", now - 60, Err(TaskGrantError::Refused)), + ("a day left", now + 86_400, GrantVerdict::LifetimeTooLong), + ("expiring at request entry", now, GrantVerdict::Refused), + ("expired", now - 60, GrantVerdict::Refused), ] { let grant = verified_grant(STATUS_SOURCE, expires_at, now - 600); for subjects in [None, Some(status_subjects())] { @@ -4813,13 +4848,13 @@ mod tests { let unlisted = verified_grant("https://other-authority.test", now + 600, now); assert_eq!( task_grant_verdict(Some(®istry), Some(status_subjects()), &unlisted, now).await, - Err(TaskGrantError::Refused), + GrantVerdict::Refused, "an unlisted source is refused" ); let unbound = verified_grant(STATUS_SOURCE, now + 600, now); assert_eq!( task_grant_verdict(Some(®istry), None, &unbound, now).await, - Err(TaskGrantError::Refused), + GrantVerdict::Refused, "a grant without signed subjects is refused" ); assert_eq!( @@ -4836,9 +4871,9 @@ mod tests { let mut active = active_answer(&grant); active["grant"]["subjects"] = json!({}); for (response, expected) in [ - (active, Ok(())), - (active_answer(&grant), Err(TaskGrantError::Refused)), - (json!({"active":false}), Err(TaskGrantError::Refused)), + (active, GrantVerdict::Current), + (active_answer(&grant), GrantVerdict::Refused), + (json!({"active":false}), GrantVerdict::Refused), ] { let (server, registry) = listed_authority(wiremock::ResponseTemplate::new(200).set_body_json(response)) @@ -4855,6 +4890,31 @@ mod tests { } } + #[tokio::test] + async fn a_listed_authority_never_answers_lifetime_too_long() { + let now = unix_now(); + let grant = verified_grant(STATUS_SOURCE, now + 86_400, now); + for (case, response, expected) in [ + ( + "active", + wiremock::ResponseTemplate::new(200).set_body_json(active_answer(&grant)), + GrantVerdict::Current, + ), + ( + "inactive", + wiremock::ResponseTemplate::new(200).set_body_json(json!({"active": false})), + GrantVerdict::Refused, + ), + ] { + let (_server, registry) = listed_authority(response).await; + assert_eq!( + task_grant_verdict(Some(®istry), Some(status_subjects()), &grant, now).await, + expected, + "{case}" + ); + } + } + #[tokio::test] async fn a_listed_authority_answer_decides_the_grant() { let now = unix_now(); @@ -4864,17 +4924,17 @@ mod tests { ( "active", wiremock::ResponseTemplate::new(200).set_body_json(active_answer(&grant)), - Ok(()), + GrantVerdict::Current, ), ( "inactive", wiremock::ResponseTemplate::new(200).set_body_json(json!({"active": false})), - Err(TaskGrantError::Refused), + GrantVerdict::Refused, ), ( "unavailable", wiremock::ResponseTemplate::new(503), - Err(TaskGrantError::Unavailable), + GrantVerdict::Unavailable, ), ] { let (server, registry) = listed_authority(response).await; diff --git a/crates/registry-scheduling/tests/postgres_commitments.rs b/crates/registry-scheduling/tests/postgres_commitments.rs index e8b18087c5..3984ce2aeb 100644 --- a/crates/registry-scheduling/tests/postgres_commitments.rs +++ b/crates/registry-scheduling/tests/postgres_commitments.rs @@ -8834,7 +8834,10 @@ async fn an_unlisted_source_is_refused_and_never_reaches_the_offline_path() { /// SEC-03. On the offline path that `unchecked-final-fifteen-minutes` /// selects, a grant with one second more than fifteen minutes left is refused -/// and one with exactly fifteen minutes left books. +/// with `grant.lifetime-too-long` and one with exactly fifteen minutes left +/// books. The new answer follows the bounds check: a caller with no grant, or +/// whose grant does not cover the offering, still gets +/// `operation.not-authorized`. #[tokio::test] async fn the_offline_path_accepts_at_most_fifteen_minutes_of_remaining_lifetime() { let fx = fixture().await; @@ -8849,6 +8852,70 @@ async fn the_offline_path_accepts_at_most_fifteen_minutes_of_remaining_lifetime( ) .await; assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "grant.lifetime-too-long"); + + let a_day_left = agent_token_with_grant_exp(pinned_now().timestamp() + 86_400); + let (status, problem) = fx + .post( + "/v1/appointments", + &a_day_left, + "a-day-left", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "grant.lifetime-too-long"); + + let no_grant = token(json!({ + "sub": "principal-agent", + "azp": CLIENT, + "registry_scopes": "scheduling-read scheduling-explain", + "registry_actor_kind": "service", + })); + let (status, problem) = fx + .post( + "/v1/appointments", + &no_grant, + "no-grant-order", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "operation.not-authorized"); + + let mut uncovered = grant_claims(); + uncovered["registry_grant_exp"] = json!(pinned_now().timestamp() + 86_400); + uncovered["registry_grant_bounds"]["permissions"] = json!([{ + "service": "registry-other", + "location": "south-counter", + "actions": ["appointment.create"], + }]); + let mut claims = json!({ + "sub": "principal-agent", + "azp": CLIENT, + "registry_scopes": "scheduling-read scheduling-explain", + "registry_actor_kind": "service", + }); + claims + .as_object_mut() + .expect("claims are an object") + .extend( + uncovered + .as_object() + .expect("grant claims are an object") + .iter() + .map(|(key, value)| (key.clone(), value.clone())), + ); + let (status, problem) = fx + .post( + "/v1/appointments", + &token(claims), + "uncovered-order", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "operation.not-authorized"); let at_the_cap = agent_token_with_grant_exp(pinned_now().timestamp() + 900); let (status, booked) = fx diff --git a/crates/registry-stack-client-node/scheduling/client.d.ts b/crates/registry-stack-client-node/scheduling/client.d.ts index 85c57ef2f3..4978b07c7a 100644 --- a/crates/registry-stack-client-node/scheduling/client.d.ts +++ b/crates/registry-stack-client-node/scheduling/client.d.ts @@ -316,6 +316,7 @@ export type SchedulingProblemCode = | 'cursor.expired' | 'cursor.invalid' | 'eligibility.unavailable' + | 'grant.lifetime-too-long' | 'hold.expired' | 'hold.released' | 'hook.unavailable' diff --git a/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx b/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx index 7706c66f47..936db918f2 100644 --- a/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx +++ b/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx @@ -164,7 +164,9 @@ also obtains a fresh exact answer from the authority selected by the signed sour commitment and idempotent receipt replay. The authority must say the grant is active and reproduce its exact identity, bounds, signed subjects, and deadline. An inactive, mismatched, unlisted, or incompletely bound grant answers `operation.not-authorized`; an authority or service -credential outage, including an unusable authority response, answers `service.unavailable`. Positive answers +credential outage, including an unusable authority response, answers `service.unavailable`. On the offline path +(`unchecked-final-fifteen-minutes`), an unexpired grant with more than 900 seconds left answers +`grant.lifetime-too-long` once its bounds have matched; an expired grant answers `operation.not-authorized`. Positive answers are not cached, and the complete attempt is limited to ten seconds. No capacity lock is held during the outbound call. This is a fresh observation rather than a distributed transaction: withdrawal after a positive answer can race the in-flight local commit. diff --git a/docs/site/src/content/docs/reference/scheduling-task-grants.mdx b/docs/site/src/content/docs/reference/scheduling-task-grants.mdx index 135b6093ee..6ffa83e255 100644 --- a/docs/site/src/content/docs/reference/scheduling-task-grants.mdx +++ b/docs/site/src/content/docs/reference/scheduling-task-grants.mdx @@ -97,7 +97,7 @@ Inside the transaction, after every lock wait and immediately before commit, Reg A credential that expires after the status answer cannot take capacity through a delayed transaction. {/* Evidence: crates/registry-scheduling/src/service.rs - the_offline_path_accepts_only_an_unexpired_grant_with_at_most_fifteen_minutes_left; + the_offline_path_tells_a_grant_with_too_much_lifetime_from_an_expired_one; crates/registry-platform-oidc/src/authorization_claims.rs expiry_uses_earlier_token_or_grant_deadline_and_refuses_exact_deadline; crates/registry-scheduling/tests/postgres_commitments.rs @@ -127,6 +127,8 @@ The answer is a fresh observation, not a distributed transaction with the author `taskGrantStatus: unchecked-final-fifteen-minutes` selects the offline path. No authority is asked, no revocation is observed, and Registry Scheduling accepts a grant only while it is unexpired with no more than 900 seconds remaining at request entry. +An unexpired grant with more than 900 seconds remaining answers `grant.lifetime-too-long`, so the caller knows to present a grant that expires sooner. An expired grant answers `operation.not-authorized`. +The lifetime answer follows the bounds match: a caller with no grant, or whose grant does not cover the offering, still answers `operation.not-authorized`. A listed authority never answers `grant.lifetime-too-long`. A list of authorities disables that path for every source, including an unlisted one, which is refused even with less than 15 minutes left. The token does not name its authorisation mode, so the final 15 minutes of an originally deferred grant can use the offline path on a deployment that writes the keyword. List the task authorities for every deployment that accepts deferred grants. diff --git a/docs/site/src/content/docs/security/scheduling.mdx b/docs/site/src/content/docs/security/scheduling.mdx index 438d6f6841..b87582c38e 100644 --- a/docs/site/src/content/docs/security/scheduling.mdx +++ b/docs/site/src/content/docs/security/scheduling.mdx @@ -171,7 +171,10 @@ it is listed with them. - Condition: the deployment writes `taskGrantStatus: unchecked-final-fifteen-minutes`. The signed token does not say whether the grant was issued in immediate or deferred mode. - Consequence: a grant with 900 seconds or less remaining qualifies for the bounded offline path - with no revocation check. + with no revocation check. An unexpired grant with more than 900 seconds remaining answers + `grant.lifetime-too-long`, only after its bounds have matched, so the answer reveals nothing about + which services and locations a grant reaches. It does reveal to the holder that the deployment has + no status authority listed. The holder already controls its own grant, so this is accepted. Even with status checks, a withdrawal that follows a positive status answer can race the in-flight local commit; the interval is bounded by the short execution credential and by deadline re-checks after every lock wait and before commit. diff --git a/docs/site/src/data/scheduling-api.yaml b/docs/site/src/data/scheduling-api.yaml index a480b10182..f2495b5404 100644 --- a/docs/site/src/data/scheduling-api.yaml +++ b/docs/site/src/data/scheduling-api.yaml @@ -10,6 +10,7 @@ - ['`cursor.expired`', '410', 'A page cursor has expired. Start again without a cursor and deduplicate entries by `id`.'] - ['`cursor.invalid`', '400', 'A page cursor is malformed or was issued for a different request.'] - ['`eligibility.unavailable`', '503', 'A required eligibility check could not run. Reserved: no milestone path answers it yet.'] + - ['`grant.lifetime-too-long`', '403', 'The task grant has more than 900 seconds left before it expires. Present a task grant that expires within 900 seconds.'] - ['`hold.expired`', '410', 'The hold expired before confirmation. Its capacity is bookable again; start a new request.'] - ['`hold.released`', '409', 'The claim is not an active hold. It may already be confirmed or released.'] - ['`hook.unavailable`', '503', 'A required lifecycle hook could not run, so the request was refused rather than half-applied. Reserved: no milestone path answers it yet.'] diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index a71fa93ff5..aab94d6573 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -3994,7 +3994,7 @@ "description": "The bearer credential is missing, invalid, or expired. Sign in again.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "authentication.refused", @@ -4013,7 +4013,7 @@ "description": "An active booking already holds this party's duplicate key. Cancel it, or wait until it has passed, before booking again.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "booking.duplicate-active", @@ -4032,7 +4032,7 @@ "description": "The cancellation cutoff for this appointment has passed, so it can no longer be cancelled.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "cancellation.cutoff-passed", @@ -4051,7 +4051,7 @@ "description": "The party or backing supply does not carry every capability this offering requires.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "capability.unmatched", @@ -4070,7 +4070,7 @@ "description": "The supply is fully committed for the requested interval. Choose another time.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "capacity.exhausted", @@ -4089,7 +4089,7 @@ "description": "This cursor has expired. Start again without a cursor and deduplicate entries by id.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "cursor.expired", @@ -4108,7 +4108,7 @@ "description": "The cursor is invalid for this request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "cursor.invalid", @@ -4127,7 +4127,7 @@ "description": "A required eligibility check could not run. Retry; do not treat this as permission.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "eligibility.unavailable", @@ -4136,6 +4136,25 @@ ] } }, + { + "uri": "https://id.registrystack.org/problems/registry-scheduling/grant/lifetime-too-long", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "scheduling", + "title": "Task grant lifetime too long", + "description": "The task grant has more than 900 seconds left before it expires. Present a task grant that expires within 900 seconds.", + "source": { + "path": "crates/registry-scheduling-core/src/problem.rs", + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + }, + "problem": { + "code": "grant.lifetime-too-long", + "httpStatuses": [ + 403 + ] + } + }, { "uri": "https://id.registrystack.org/problems/registry-scheduling/hold/expired", "kind": "problem", @@ -4146,7 +4165,7 @@ "description": "The hold expired before confirmation. Its capacity is bookable again; start a new request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "hold.expired", @@ -4165,7 +4184,7 @@ "description": "The claim is not an active hold. It may already be confirmed or released.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "hold.released", @@ -4184,7 +4203,7 @@ "description": "A required lifecycle hook could not run, so the request was refused rather than half-applied.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "hook.unavailable", @@ -4203,7 +4222,7 @@ "description": "The requested start is earlier than the lead time allows or further ahead than the horizon allows.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "horizon.outside", @@ -4222,7 +4241,7 @@ "description": "The stored response for this idempotency key has expired. For an appointment command, read the appointment by its external reference or its identifier to learn the original outcome before choosing a new key. A hold cannot be read and expires on its own, so start a new request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "idempotency.expired", @@ -4241,7 +4260,7 @@ "description": "This idempotency key was used for a different request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "idempotency.key-reused", @@ -4260,7 +4279,7 @@ "description": "A closure covers the requested start. Choose a start outside the closure.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "location.closed", @@ -4279,7 +4298,7 @@ "description": "Your current Scheduling authority does not allow this operation.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "operation.not-authorized", @@ -4298,7 +4317,7 @@ "description": "The party is larger than this offering can ever serve, or its size falls outside the published units.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "party.capacity-inadequate", @@ -4317,7 +4336,7 @@ "description": "The policy revision changed before the request committed. Reload the catalogue and try again with the current revision.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "policy.changed", @@ -4336,7 +4355,7 @@ "description": "The appointment changed since you loaded it. Reload and try again.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "precondition.failed", @@ -4355,7 +4374,7 @@ "description": "This mutation requires the revision you loaded, or the duplicate key this offering keys on.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "precondition.required", @@ -4374,7 +4393,7 @@ "description": "The party is missing a prerequisite this offering requires.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "prerequisite.missing", @@ -4393,7 +4412,7 @@ "description": "The selected Scheduling profile does not authorize this request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "profile.not-authorized", @@ -4412,7 +4431,7 @@ "description": "No retained success receipt matches this caller, key, and original request. The original outcome remains unknown; this is not evidence that no effect occurred.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "receipt.unresolved", @@ -4431,7 +4450,7 @@ "description": "The request body exceeds the accepted size.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "request.body-too-large", @@ -4450,7 +4469,7 @@ "description": "The request could not be read as a Scheduling request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "request.invalid", @@ -4469,7 +4488,7 @@ "description": "The route exists but not for this method.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "request.method-not-allowed", @@ -4488,7 +4507,7 @@ "description": "The requested route does not exist.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "request.not-found", @@ -4507,7 +4526,7 @@ "description": "The request body could not be processed.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "request.unprocessable", @@ -4526,7 +4545,7 @@ "description": "The request body is not JSON.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "request.unsupported-media-type", @@ -4545,7 +4564,7 @@ "description": "Every capable member is unavailable for this interval.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "resource.unavailable", @@ -4564,7 +4583,7 @@ "description": "The observed revision is no longer current.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "revision.mismatch", @@ -4583,7 +4602,7 @@ "description": "No published schedule serves that start. Choose a start on the published grid.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "schedule.unpublished", @@ -4602,7 +4621,7 @@ "description": "Scheduling storage is unavailable. Try again after the service recovers.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "2a84c86a852cfeb47db62acfe2fad5fa7f2eeba199003401022f7bcd1a928691" + "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" }, "problem": { "code": "service.unavailable", @@ -6299,7 +6318,7 @@ }, "artifact": { "path": "products/scheduling/generated/fixture/fixture.schema.json", - "sha256": "dbb4bea390c11e37fee5840aef5eab34e39a4f5d34bb72354fcf38f041bbb974", + "sha256": "8a3010dde6db912e705724dbd14bb987fd2cbaf1b6b1c7f2304c8dacab4efedf", "mediaType": "application/schema+json" } }, diff --git a/products/scheduling/CHANGELOG.md b/products/scheduling/CHANGELOG.md index 7125658605..1295ac5d3c 100644 --- a/products/scheduling/CHANGELOG.md +++ b/products/scheduling/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- A task grant with more than 900 seconds left on the offline path + (`taskGrantStatus: unchecked-final-fifteen-minutes`) now answers 403 + `grant.lifetime-too-long` in place of `operation.not-authorized`, so the + caller learns to present a grant that expires sooner. The status is + unchanged. An expired grant, a missing grant, and a grant that does not cover + the offering still answer `operation.not-authorized`, and a deployment that + lists status authorities never answers the new code. Clients that branch on + the code gain the new member in `SchedulingProblemCode`. + ## 0.47.0 - 2026-11-21 - BREAKING: `services`, `offerings`, `holidaySets`, `openings`, and `hooks` in diff --git a/products/scheduling/contracts/security-invariant-matrix.yaml b/products/scheduling/contracts/security-invariant-matrix.yaml index cef4f3ab25..668e2d61e0 100644 --- a/products/scheduling/contracts/security-invariant-matrix.yaml +++ b/products/scheduling/contracts/security-invariant-matrix.yaml @@ -56,7 +56,9 @@ invariants: capacity transaction and receipt replay, without holding a database lock, and refuses a grant from an unlisted source rather than falling back to the offline path. The unchecked-final-fifteen-minutes keyword - admits only grants with at most 900 seconds remaining. The transaction + admits only grants with at most 900 seconds remaining, and answers an + unexpired grant with more left with grant.lifetime-too-long once the + bounds have matched. The transaction re-checks the earlier of the verified access-token and grant deadlines after every lock wait and immediately before commit. Status is an observation, not a distributed transaction: withdrawal after a diff --git a/products/scheduling/contracts/security-test-traceability.yaml b/products/scheduling/contracts/security-test-traceability.yaml index 1c49b74922..155b858cea 100644 --- a/products/scheduling/contracts/security-test-traceability.yaml +++ b/products/scheduling/contracts/security-test-traceability.yaml @@ -110,7 +110,8 @@ entries: - {path: crates/registry-scheduling/tests/postgres_commitments.rs, name: inactive_and_unavailable_task_status_refuse_every_mutation_without_changing_capacity} - {path: crates/registry-scheduling/tests/postgres_commitments.rs, name: an_unlisted_source_is_refused_and_never_reaches_the_offline_path} - {path: crates/registry-scheduling/tests/postgres_commitments.rs, name: the_offline_path_accepts_at_most_fifteen_minutes_of_remaining_lifetime} - - {path: crates/registry-scheduling/src/service.rs, name: the_offline_path_accepts_only_an_unexpired_grant_with_at_most_fifteen_minutes_left} + - {path: crates/registry-scheduling/src/service.rs, name: the_offline_path_tells_a_grant_with_too_much_lifetime_from_an_expired_one} + - {path: crates/registry-scheduling/src/service.rs, name: a_listed_authority_never_answers_lifetime_too_long} - {path: crates/registry-scheduling/src/service.rs, name: listed_authorities_refuse_an_unlisted_source_and_an_unbound_grant_without_the_offline_path} - {path: crates/registry-scheduling/src/service.rs, name: a_listed_authority_answer_decides_the_grant} - {path: crates/registry-scheduling/src/config.rs, name: a_missing_task_grant_status_is_refused_naming_both_choices} diff --git a/products/scheduling/generated/fixture/fixture.schema.json b/products/scheduling/generated/fixture/fixture.schema.json index 0b212bfcf2..bb4cfc10fe 100644 --- a/products/scheduling/generated/fixture/fixture.schema.json +++ b/products/scheduling/generated/fixture/fixture.schema.json @@ -288,6 +288,7 @@ "cursor.expired", "cursor.invalid", "eligibility.unavailable", + "grant.lifetime-too-long", "hold.expired", "hold.released", "hook.unavailable", diff --git a/products/scheduling/generated/registry-scheduling.openapi.json b/products/scheduling/generated/registry-scheduling.openapi.json index baef66a006..904c244fba 100644 --- a/products/scheduling/generated/registry-scheduling.openapi.json +++ b/products/scheduling/generated/registry-scheduling.openapi.json @@ -1575,6 +1575,7 @@ "cursor.expired", "cursor.invalid", "eligibility.unavailable", + "grant.lifetime-too-long", "hold.expired", "hold.released", "hook.unavailable", @@ -1846,6 +1847,33 @@ } ] }, + "ProblemGrantLifetimeTooLong": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "properties": { + "code": { + "const": "grant.lifetime-too-long" + }, + "detail": { + "const": "The task grant has more than 900 seconds left before it expires. Present a task grant that expires within 900 seconds." + }, + "status": { + "const": 403 + }, + "title": { + "const": "Task grant lifetime too long" + }, + "type": { + "const": "https://id.registrystack.org/problems/registry-scheduling/grant/lifetime-too-long" + } + }, + "type": "object" + } + ] + }, "ProblemHoldExpired": { "allOf": [ { @@ -3266,12 +3294,15 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized", + "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -3866,12 +3897,15 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized", + "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -4070,12 +4104,15 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized", + "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -4365,12 +4402,15 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized", + "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -4899,12 +4939,15 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized", + "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -5979,12 +6022,15 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized", + "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -6320,12 +6366,15 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized", + "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" diff --git a/products/scheduling/scripts/generate_openapi.py b/products/scheduling/scripts/generate_openapi.py index d74e9fbc16..9bd0ee01b0 100644 --- a/products/scheduling/scripts/generate_openapi.py +++ b/products/scheduling/scripts/generate_openapi.py @@ -241,6 +241,9 @@ CURSOR = ["cursor.expired", "cursor.invalid"] STORAGE = ["service.unavailable"] AUTHORITY = ["operation.not-authorized"] +# An operation that asks the task grant's own status answers a grant that is +# unexpired but has more than fifteen minutes left on the offline path. +GRANT_LIFETIME = ["grant.lifetime-too-long"] IDEMPOTENCY = ["idempotency.expired", "idempotency.key-reused"] # An operation that resolves a caller-named offering against the deployed # policy answers for one the policy does not publish. The offering listing is @@ -278,29 +281,29 @@ + ["revision.mismatch", "precondition.failed", "resource.unavailable"], ("GET", "/v1/availability/explain"): EDGE + AUTHENTICATION + QUERY + STORAGE + OFFERING, ("GET", "/v1/operational/appointments"): EDGE + AUTHENTICATION + QUERY + CURSOR + STORAGE, - ("POST", "/v1/holds"): EDGE + AUTHENTICATION + JSON_BODY + ADMISSION + IDEMPOTENCY + AUTHORITY + ("POST", "/v1/holds"): EDGE + AUTHENTICATION + JSON_BODY + ADMISSION + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + OFFERING + ["service.unavailable"], # A release carries no caller-chosen key, so `idempotency.key-reused` is # not reachable: the key and the request hash are both the hold's own id. - ("DELETE", "/v1/holds/{hold_id}"): EDGE + AUTHENTICATION + PATH + AUTHORITY + ("DELETE", "/v1/holds/{hold_id}"): EDGE + AUTHENTICATION + PATH + AUTHORITY + GRANT_LIFETIME + ["hold.released", "idempotency.expired", "service.unavailable"], - ("POST", "/v1/appointments"): EDGE + AUTHENTICATION + JSON_BODY + ADMISSION + IDEMPOTENCY + AUTHORITY + ("POST", "/v1/appointments"): EDGE + AUTHENTICATION + JSON_BODY + ADMISSION + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + OFFERING + ["hold.expired", "hold.released", "service.unavailable"], ("POST", "/v1/appointments/receipt"): EDGE + AUTHENTICATION + JSON_BODY + ["receipt.unresolved", "service.unavailable"], ("GET", "/v1/appointments"): EDGE + AUTHENTICATION + QUERY + CURSOR + STORAGE, - ("GET", "/v1/appointments/{appointment_id}"): EDGE + AUTHENTICATION + PATH + AUTHORITY + STORAGE, + ("GET", "/v1/appointments/{appointment_id}"): EDGE + AUTHENTICATION + PATH + AUTHORITY + GRANT_LIFETIME + STORAGE, # A reschedule resolves its offering from the appointment rather than from # the caller, so an unknown offering is operator state, not a refusal the # caller can read. ("POST", "/v1/appointments/{appointment_id}/reschedule"): EDGE + AUTHENTICATION + PATH + JSON_BODY - + ADMISSION + IDEMPOTENCY + AUTHORITY + ["hold.released", "service.unavailable"], + + ADMISSION + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + ["hold.released", "service.unavailable"], # Cancellation is guarded by the observed revision and the cutoff, never by # the policy revision, so it answers no admission refusal at all. ("POST", "/v1/appointments/{appointment_id}/cancel"): EDGE + AUTHENTICATION + PATH + JSON_BODY - + IDEMPOTENCY + AUTHORITY + + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + ["cancellation.cutoff-passed", "hold.released", "revision.mismatch", "service.unavailable"], ("PUT", "/v1/appointments/{appointment_id}/attendance"): EDGE + AUTHENTICATION + PATH + JSON_BODY - + IDEMPOTENCY + AUTHORITY + ["revision.mismatch", "service.unavailable"], + + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + ["revision.mismatch", "service.unavailable"], ("GET", "/v1/appointments/{appointment_id}/history"): EDGE + AUTHENTICATION + PATH + AUTHORITY + QUERY + CURSOR + STORAGE, } diff --git a/products/scheduling/scripts/test_generate_openapi.py b/products/scheduling/scripts/test_generate_openapi.py index 03a999fd16..870db9b874 100644 --- a/products/scheduling/scripts/test_generate_openapi.py +++ b/products/scheduling/scripts/test_generate_openapi.py @@ -231,8 +231,8 @@ def test_every_documented_problem_matches_its_pinned_rust_catalog_entry(self) -> self.assertEqual(entry["title"], properties["title"]["const"]) self.assertEqual(entry["description"], properties["detail"]["const"]) self.assertEqual(entry["httpStatuses"][0], properties["status"]["const"]) - self.assertEqual(33, len(self.contract["entries"])) - self.assertEqual(82, len(self.openapi["components"]["schemas"])) + self.assertEqual(34, len(self.contract["entries"])) + self.assertEqual(83, len(self.openapi["components"]["schemas"])) def test_every_operation_answers_exactly_the_problems_it_was_mapped(self) -> None: for key, expected in GENERATOR.OPERATION_PROBLEMS.items(): @@ -766,6 +766,20 @@ def test_mutating_routes_name_ordinary_and_assisted_task_grant_actions(self) -> self.assertIn("hold.create, hold.release, appointment.create, appointment.reschedule, appointment.cancel", self.openapi["components"]["securitySchemes"]["bearerAuth"]["description"]) + def test_a_grant_gated_operation_documents_the_lifetime_refusal_beside_the_bounds_refusal(self) -> None: + gated = { + key + for key in GENERATOR.ROUTE_HANDLERS + if operation(self.openapi, key)["x-scheduling-authority"] + in ("task-grant", "appointment-detail") + } + self.assertEqual(7, len(gated)) + for key in gated: + self.assertIn("grant.lifetime-too-long", GENERATOR.OPERATION_PROBLEMS[key], key) + self.assertIn("operation.not-authorized", GENERATOR.OPERATION_PROBLEMS[key], key) + for key in set(GENERATOR.ROUTE_HANDLERS) - gated: + self.assertNotIn("grant.lifetime-too-long", GENERATOR.OPERATION_PROBLEMS[key], key) + def test_the_document_carries_no_tag_list_and_no_timestamp(self) -> None: self.assertNotIn("tags", self.openapi) self.assertEqual("3.1.0", self.openapi["openapi"]) @@ -979,7 +993,7 @@ def test_the_problem_envelope_is_the_platform_one(self) -> None: set(problem["properties"])) self.assertEqual(["code", "detail", "status", "title", "traceId", "type"], sorted(problem["required"])) - self.assertEqual(33, len(problem["properties"]["code"]["enum"])) + self.assertEqual(34, len(problem["properties"]["code"]["enum"])) httpsec = GENERATOR.production_source(ROOT, GENERATOR.HTTPSEC_SOURCE) http = GENERATOR.production_source(ROOT, GENERATOR.HTTP_SOURCE) body = GENERATOR.rust_struct_fields(httpsec, "ProblemBody") From 6b86f2008cd9ef50daaadce54379029e5181da44 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:47:38 +0100 Subject: [PATCH 012/136] fix(platform): take the provision report format from the tool's own flag Every tool that offers provision already has a global --format with the values human and json. The shared command declared a second --format of its own, which clap refuses, so the verb could not run in any tool. The command now takes the format the tool parsed, so provision reads the same flag, with the same values, as every other verb. Signed-off-by: Jeremi Joslin --- crates/registry-platform-provision/src/cli.rs | 119 ++++++++++++++---- 1 file changed, 94 insertions(+), 25 deletions(-) diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs index 4681f715dd..99f3db1dc9 100644 --- a/crates/registry-platform-provision/src/cli.rs +++ b/crates/registry-platform-provision/src/cli.rs @@ -29,15 +29,17 @@ pub const REPORT_API_VERSION: &str = "id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1"; pub const REPORT_KIND: &str = "PlatformCliDatabaseProvisionReport"; -/// How the command writes its result. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)] +/// How the command writes its result. A tool maps its own global `--format` +/// (`human | json`) onto this. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum OutputFormat { #[default] - Text, + Human, Json, } -/// The flags of ` provision`. +/// The flags of ` provision`. The output format is the tool's own global +/// `--format` flag, passed to [`run_provision`]. #[derive(clap::Args, Debug, Clone)] pub struct ProvisionArgs { /// The product's runtime file, the one `apply` reads @@ -62,9 +64,6 @@ pub struct ProvisionArgs { /// Print the SQL script and connect to nothing #[arg(long)] pub print_sql: bool, - /// Output format - #[arg(long, value_enum, default_value_t)] - pub format: OutputFormat, } /// What a product's loader hands the runner. A loader refuses with one @@ -527,7 +526,7 @@ impl Output<'_> { fn refusal(&mut self, report: &PlatformCliDatabaseProvisionReport) -> u8 { let written = match self.format { OutputFormat::Json => self.json(report), - OutputFormat::Text => report + OutputFormat::Human => report .diagnostics .iter() .all(|diagnostic| write!(self.stderr, "{}", diagnostic.render_human()).is_ok()), @@ -540,17 +539,21 @@ impl Output<'_> { } } +// The runner's inputs are independent (identity, arguments, format, loader, +// backend, two streams) and each is a test seam, so they stay positional. +#[allow(clippy::too_many_arguments)] fn run_with( tool: &'static str, version: &'static str, args: &ProvisionArgs, + format: OutputFormat, load: impl FnOnce(&Path) -> Result>, backend: Backend<'_>, stdout: &mut dyn Write, stderr: &mut dyn Write, ) -> u8 { let mut output = Output { - format: args.format, + format, version, stdout, stderr, @@ -639,8 +642,8 @@ fn run_with( if args.print_sql { report.ok = true; report.status = ReportStatus::Complete; - let written = match args.format { - OutputFormat::Text => output + let written = match format { + OutputFormat::Human => output .stdout .write_all(render_script(&plan).as_bytes()) .is_ok(), @@ -686,9 +689,9 @@ fn run_with( report.ok = true; report.status = ReportStatus::Complete; report.statements = report_statements(&plan, Some(&outcome)); - let written = match args.format { + let written = match format { OutputFormat::Json => output.json(&report), - OutputFormat::Text => write_summary(output.stdout, &report, outcome.single_role), + OutputFormat::Human => write_summary(output.stdout, &report, outcome.single_role), }; output.write_failed(written) } @@ -749,6 +752,7 @@ pub fn run_provision( tool: &'static str, version: &'static str, args: &ProvisionArgs, + format: OutputFormat, load: impl FnOnce(&Path) -> Result>, ) -> ExitCode { let runtime = match tokio::runtime::Builder::new_current_thread() @@ -765,6 +769,7 @@ pub fn run_provision( tool, version, args, + format, load, &server_backend(&runtime), &mut std::io::stdout().lock(), @@ -862,6 +867,26 @@ mod tests { args: ProvisionArgs, } + /// Splits a test's `--format human|json` off the verb's own flags, as the + /// tool's global flag does. + pub(super) fn split_format<'a>(arguments: &[&'a str]) -> (Vec<&'a str>, OutputFormat) { + let mut rest = Vec::new(); + let mut format = OutputFormat::Human; + let mut iter = arguments.iter().copied(); + while let Some(argument) = iter.next() { + if argument == "--format" { + format = match iter.next() { + Some("json") => OutputFormat::Json, + Some("human") => OutputFormat::Human, + other => panic!("test format {other:?} is not human or json"), + }; + } else { + rest.push(argument); + } + } + (rest, format) + } + fn parse(arguments: &[&str]) -> Result { Harness::try_parse_from(std::iter::once("tool").chain(arguments.iter().copied())) .map(|harness| harness.args) @@ -919,6 +944,7 @@ mod tests { backend: Backend<'_>, ) -> Run { let directory = tempfile::tempdir().expect("scratch directory"); + let (arguments, format) = split_format(arguments); let mut full: Vec = arguments.iter().map(|s| (*s).to_owned()).collect(); if let Some(contents) = admin_file { let path = directory.path().join("admin.url"); @@ -935,6 +961,7 @@ mod tests { "casectl", "1.2.3-test", &args, + format, |_| input, backend, &mut stdout, @@ -1026,14 +1053,56 @@ mod tests { assert!(parse(&["--runtime-config", "r", "--print-sql"]).is_ok()); } + /// A tool declares `--format human|json` globally and mounts the verb + /// beneath it. clap refuses a verb flag that reuses a global flag's name. + #[test] + fn the_verb_mounts_under_a_tool_with_a_global_format_flag() { + #[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] + enum ToolFormat { + Human, + Json, + } + let tool = clap::Command::new("tool") + .arg( + clap::Arg::new("format") + .long("format") + .global(true) + .value_parser(clap::value_parser!(ToolFormat)) + .default_value("human"), + ) + .subcommand(::augment_args( + clap::Command::new("provision"), + )); + tool.clone().debug_assert(); + let matches = tool + .try_get_matches_from([ + "tool", + "provision", + "--runtime-config", + "r", + "--print-sql", + "--format", + "json", + ]) + .expect("the verb parses under the global format flag"); + let verb = matches.subcommand_matches("provision").expect("verb"); + assert_eq!( + verb.get_one::("format"), + Some(&ToolFormat::Json) + ); + } + #[test] - fn the_runtime_config_is_required_and_the_format_is_text_or_json() { + fn the_verb_has_no_format_flag_of_its_own() { + let error = parse(&["--runtime-config", "r", "--print-sql", "--format", "json"]) + .expect_err("format belongs to the tool"); + assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument); + } + + #[test] + fn the_runtime_config_is_required() { assert!(parse(&["--print-sql"]).is_err()); - let args = parse(&["--runtime-config", "r", "--print-sql"]).unwrap(); - assert_eq!(args.format, OutputFormat::Text); - let args = parse(&["--runtime-config", "r", "--print-sql", "--format", "json"]).unwrap(); - assert_eq!(args.format, OutputFormat::Json); - assert!(parse(&["--runtime-config", "r", "--print-sql", "--format", "yaml"]).is_err()); + assert!(parse(&["--runtime-config", "r", "--print-sql"]).is_ok()); } // ---- print mode ---- @@ -1434,8 +1503,6 @@ mod tests { "r", "--admin-url-file", "/nonexistent-provision-admin-url", - "--format", - "json", ]) .unwrap(); let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); @@ -1443,6 +1510,7 @@ mod tests { "casectl", "1", &args, + OutputFormat::Json, |_| Ok(split_input()), &must_not_run, &mut stdout, @@ -1464,8 +1532,6 @@ mod tests { "r", "--admin-url-env", "PROVISION_TEST_UNSET_ADMIN_URL", - "--format", - "json", ]) .unwrap(); let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); @@ -1473,6 +1539,7 @@ mod tests { "casectl", "1", &args, + OutputFormat::Json, |_| Ok(split_input()), &must_not_run, &mut stdout, @@ -1702,7 +1769,7 @@ mod tests { sqlstate: "42710".to_owned(), }) }; - for format in [["--format", "text"], ["--format", "json"]] { + for format in [["--format", "human"], ["--format", "json"]] { let run = execute_run(&format, Some(&admin), Ok(split_input()), &backend); let output = run.all_output(); for secret in [ @@ -1784,7 +1851,8 @@ mod postgres_tests { "--admin-url-file", admin_file.as_str(), ]; - full.extend_from_slice(arguments); + let (arguments, format) = tests::split_format(arguments); + full.extend_from_slice(&arguments); let args = { use clap::Parser; #[derive(Parser)] @@ -1801,6 +1869,7 @@ mod postgres_tests { "casectl", "1.2.3-test", &args, + format, |_| Ok(input), backend, &mut stdout, From fac6cad15769d01a735340ac5413f964ad7b3bec Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:48:13 +0100 Subject: [PATCH 013/136] feat(breg): give the client hook verifiers a default freshness window The Rust, Node and Python verifiers in the BReg clients checked only that a delivery time was well formed and left the window to each receiver, so a receiver that forgot it accepted a replay of any age. They now refuse a delivery more than 300 seconds from the receiver clock with stale-delivery, the window the shared hook receiver uses. A receiver can set another window up to an hour, or keep checking the time itself. The changelog also records the static key set rule. Signed-off-by: Jeremi Joslin --- crates/registry-breg-client-node/README.md | 9 +- .../__test__/facade.test-d.ts | 6 ++ .../__test__/webhook-verification.test.js | 83 +++++++++++++++++ crates/registry-breg-client-node/client.d.ts | 19 +++- crates/registry-breg-client-node/client.js | 19 ++-- crates/registry-breg-client-node/index.d.ts | 18 +++- crates/registry-breg-client-node/src/lib.rs | 38 +++++++- crates/registry-breg-client-py/README.md | 9 +- .../python/registry_breg_client/__init__.pyi | 7 +- crates/registry-breg-client-py/src/lib.rs | 64 +++++++++++-- .../tests/python/test_webhook_verification.py | 89 +++++++++++++++++- crates/registry-breg-client/src/hook.rs | 55 +++++++++--- crates/registry-breg-client/tests/webhook.rs | 90 ++++++++++++++++++- crates/registry-stack-client-node/README.md | 6 +- .../breg/client.d.ts | 19 +++- .../registry-stack-client-node/breg/client.js | 19 ++-- .../breg/index.d.ts | 18 +++- crates/registry-stack-client/src/lib.rs | 36 ++++---- .../content/docs/operate/breg-webhooks.mdx | 13 ++- .../reference/breg-client-capabilities.mdx | 2 +- .../docs/reference/delivery-signing.mdx | 9 +- products/breg/CHANGELOG.md | 17 ++++ .../examples/webhook-receiver/receiver.py | 7 +- .../webhook-receiver/test_receiver.py | 2 +- .../examples/python-composition/service.py | 8 +- .../python-composition/tests/test_service.py | 1 + 26 files changed, 584 insertions(+), 79 deletions(-) diff --git a/crates/registry-breg-client-node/README.md b/crates/registry-breg-client-node/README.md index 430260b0d0..095405278c 100644 --- a/crates/registry-breg-client-node/README.md +++ b/crates/registry-breg-client-node/README.md @@ -50,14 +50,17 @@ Body and key buffers must not use a shared backing store. Accepted buffers are copied before native verification so another worker cannot change the bytes being authenticated. -The helper does not apply clock-skew or deduplication policy. Bound the returned -`deliveryTime` against the receiver clock. `idempotencyKey` collapses automatic +The helper refuses a delivery time more than 300 seconds from the receiver clock +(code `stale-delivery`). Pass `maxSkewSeconds` (a whole number from 1 to 3600) for +another window, or `callerEnforcedFreshness: true` to check only that the time is +well formed and bound `deliveryTime` yourself, but not both. The helper applies no +deduplication policy. `idempotencyKey` collapses automatic retries within one delivery generation; an effect that must remain once-only across operator replay uses a durable apply-once operation keyed by authenticated `source` plus `id`, or by an application business key, before acting on `body`. Refusal throws `BaseRegistryClientError` with kind `hook-verification` and a -code from `missing-header`, `invalid-delivery-time`, `duplicate-header`, `body-too-large`, `invalid-key`, `malformed-signature`, `signature-mismatch`, or `unsupported-version`. +code from `missing-header`, `invalid-delivery-time`, `stale-delivery`, `duplicate-header`, `body-too-large`, `invalid-key`, `malformed-signature`, `signature-mismatch`, or `unsupported-version`. The message names the input to check and never includes a header value, body, or key. diff --git a/crates/registry-breg-client-node/__test__/facade.test-d.ts b/crates/registry-breg-client-node/__test__/facade.test-d.ts index 05346b4a2a..5d9d04d760 100644 --- a/crates/registry-breg-client-node/__test__/facade.test-d.ts +++ b/crates/registry-breg-client-node/__test__/facade.test-d.ts @@ -138,6 +138,12 @@ verifiedHook.idempotencyKey.toUpperCase() verifiedHook.body.byteLength.toFixed() const webhookRefusal: HookVerificationRefusalCode = 'signature-mismatch' webhookRefusal.toUpperCase() +const staleRefusal: HookVerificationRefusalCode = 'stale-delivery' +staleRefusal.toUpperCase() +verifyHookDelivery({ method: 'POST', path: '/', headers: {}, body: Buffer.from('{}'), key: Buffer.alloc(32), maxSkewSeconds: 60 }) +verifyHookDelivery({ method: 'POST', path: '/', headers: {}, body: Buffer.from('{}'), key: Buffer.alloc(32), callerEnforcedFreshness: true }) +// @ts-expect-error The window is a number of seconds. +verifyHookDelivery({ method: 'POST', path: '/', headers: {}, body: Buffer.from('{}'), key: Buffer.alloc(32), maxSkewSeconds: '60' }) // @ts-expect-error Hook bodies must remain exact bytes. verifyHookDelivery({ method: 'POST', path: '/', headers: {}, body: '{}', key: Buffer.alloc(32) }) // @ts-expect-error Header values must be exact strings. diff --git a/crates/registry-breg-client-node/__test__/webhook-verification.test.js b/crates/registry-breg-client-node/__test__/webhook-verification.test.js index 35fbaf10a8..b3f93ed84d 100644 --- a/crates/registry-breg-client-node/__test__/webhook-verification.test.js +++ b/crates/registry-breg-client-node/__test__/webhook-verification.test.js @@ -1,6 +1,7 @@ 'use strict'; const assert = require('node:assert/strict'); +const { createHmac } = require('node:crypto'); const { test } = require('node:test'); const { @@ -37,10 +38,43 @@ function input(overrides = {}) { headers: headers(), body, key, + // The fixed vector is dated 2026-08-30, outside any default window. + callerEnforcedFreshness: true, ...overrides, }; } +// The fixed headers re-signed for `deliveryTime` with the vector's key. +function signedHeaders(deliveryTime) { + const values = { + ...headers(), + 'x-registry-delivery-time': deliveryTime.toISOString().replace(/\.\d{3}Z$/, 'Z'), + }; + const parts = [ + values['Ce-Specversion'], values['CE-ID'], values['ce-source'], values['ce-type'], + values['ce-time'], values['ce-dataschema'], values['x-registry-event-generation'], + values['x-registry-delivery-attempt'], values['x-registry-delivery-time'], + 'POST', '/hooks/registry', 'application/json', values['idempotency-key'], body, + ].map((part) => Buffer.from(part)); + const signed = [Buffer.from('breg-webhook-signature-v1')]; + for (const part of parts) { + const length = Buffer.alloc(8); + length.writeBigUInt64BE(BigInt(part.length)); + signed.push(length, part); + } + values['x-registry-signature'] = `v1=${createHmac('sha256', key) + .update(Buffer.concat(signed)).digest('base64url')}`; + return values; +} + +function fresh(offsetSeconds, overrides = {}) { + return input({ + headers: signedHeaders(new Date(Date.now() + offsetSeconds * 1000)), + callerEnforcedFreshness: undefined, + ...overrides, + }); +} + test('shared language vectors authenticate exact RFC3339 fractions', () => { const vectors = require('../../registry-platform-crypto/tests/fixtures/delivery-signatures.json'); for (const vector of vectors) { @@ -174,3 +208,52 @@ test('refuses shared backing stores before native verification', () => { ); } }); + +test('the default window is 300 seconds in both directions', () => { + for (const offset of [0, -290, 290]) { + assert.equal(verifyHookDelivery(fresh(offset)).attempt, '1'); + } + for (const offset of [-310, 310]) { + assert.throws(() => verifyHookDelivery(fresh(offset)), assertRefusal('stale-delivery')); + } +}); + +test('an application that names no window refuses the old fixed vector', () => { + const { callerEnforcedFreshness, ...bare } = input(); + assert.equal(callerEnforcedFreshness, true); + assert.throws(() => verifyHookDelivery(bare), assertRefusal('stale-delivery')); +}); + +test('maxSkewSeconds replaces the default window', () => { + assert.equal(verifyHookDelivery(fresh(-600, { maxSkewSeconds: 900 })).attempt, '1'); + assert.throws( + () => verifyHookDelivery(fresh(-60, { maxSkewSeconds: 10 })), + assertRefusal('stale-delivery'), + ); + for (const edge of [1, 3600]) { + assert.equal(verifyHookDelivery(fresh(0, { maxSkewSeconds: edge })).attempt, '1'); + } +}); + +test('callerEnforcedFreshness accepts an old delivery', () => { + assert.equal(verifyHookDelivery(input()).attempt, '1'); +}); + +test('refuses freshness options out of range, mistyped or combined', () => { + for (const overrides of [ + { maxSkewSeconds: 0 }, + { maxSkewSeconds: 3601 }, + { maxSkewSeconds: -1 }, + { maxSkewSeconds: 1.5 }, + { maxSkewSeconds: Number.NaN }, + { maxSkewSeconds: '10' }, + { callerEnforcedFreshness: 'yes' }, + { maxSkewSeconds: 10, callerEnforcedFreshness: true }, + ]) { + assert.throws( + () => verifyHookDelivery(fresh(0, overrides)), + (error) => error instanceof BaseRegistryClientError && error.kind === 'invalid-request', + JSON.stringify(overrides), + ); + } +}); diff --git a/crates/registry-breg-client-node/client.d.ts b/crates/registry-breg-client-node/client.d.ts index 4c283e7481..25f291f576 100644 --- a/crates/registry-breg-client-node/client.d.ts +++ b/crates/registry-breg-client-node/client.d.ts @@ -15,6 +15,7 @@ export type SafeInteger = number export type HookVerificationRefusalCode = | 'missing-header' | 'invalid-delivery-time' + | 'stale-delivery' | 'duplicate-header' | 'body-too-large' | 'invalid-key' @@ -30,6 +31,17 @@ export interface HookDeliveryInput { body: Buffer /** Secret bytes in a non-shared backing store. */ key: Buffer + /** + * Window around the receiver clock, in whole seconds from 1 to 3600. With + * neither this nor `callerEnforcedFreshness`, the window is 300 seconds. + * Cannot be combined with `callerEnforcedFreshness`. + */ + maxSkewSeconds?: number + /** + * Check only that the delivery time is well formed. The caller enforces its + * own window. Cannot be combined with `maxSkewSeconds`. + */ + callerEnforcedFreshness?: boolean } export interface VerifiedHookDelivery { @@ -46,8 +58,11 @@ export interface VerifiedHookDelivery { } /** - * Authenticate one exact Base Registry Engine Version 1 hook delivery. - * Apply delivery-time skew and idempotency policy before acting on the body. + * Authenticate one exact Base Registry Engine Version 1 hook delivery. The + * delivery time must be within 300 seconds of the receiver clock unless + * `maxSkewSeconds` or `callerEnforcedFreshness` says otherwise; a time outside + * the window is refused with code `stale-delivery`. Apply idempotency policy + * before acting on the body. */ export declare function verifyHookDelivery(input: HookDeliveryInput): VerifiedHookDelivery diff --git a/crates/registry-breg-client-node/client.js b/crates/registry-breg-client-node/client.js index c5af4483ca..521f23bc96 100644 --- a/crates/registry-breg-client-node/client.js +++ b/crates/registry-breg-client-node/client.js @@ -64,7 +64,7 @@ function inputError(kind) { }); } -function plainDataObject(value, expectedFields) { +function plainDataObject(value, expectedFields, optionalFields = []) { if (value === null || typeof value !== 'object' || Array.isArray(value) || isProxy(value)) { throw inputError('invalid-request'); } @@ -72,10 +72,10 @@ function plainDataObject(value, expectedFields) { if (prototype !== Object.prototype && prototype !== null) throw inputError('invalid-request'); const keys = Reflect.ownKeys(value); if (keys.some((key) => typeof key !== 'string') - || keys.length !== expectedFields.length - || keys.some((key) => !expectedFields.includes(key))) throw inputError('invalid-request'); + || keys.some((key) => !expectedFields.includes(key) && !optionalFields.includes(key)) + || expectedFields.some((field) => !keys.includes(field))) throw inputError('invalid-request'); const result = Object.create(null); - for (const field of expectedFields) { + for (const field of keys) { const descriptor = Object.getOwnPropertyDescriptor(value, field); if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) { throw inputError('invalid-request'); @@ -107,10 +107,17 @@ function hookHeaders(value) { function verifyHookDelivery(value) { try { - const input = plainDataObject(value, ['method', 'path', 'headers', 'body', 'key']); + const input = plainDataObject( + value, + ['method', 'path', 'headers', 'body', 'key'], + ['maxSkewSeconds', 'callerEnforcedFreshness'], + ); if (typeof input.method !== 'string' || typeof input.path !== 'string' || !Buffer.isBuffer(input.body) || !Buffer.isBuffer(input.key) - || isSharedArrayBuffer(input.body.buffer) || isSharedArrayBuffer(input.key.buffer)) { + || isSharedArrayBuffer(input.body.buffer) || isSharedArrayBuffer(input.key.buffer) + || (input.maxSkewSeconds !== undefined && !Number.isSafeInteger(input.maxSkewSeconds)) + || (input.callerEnforcedFreshness !== undefined + && typeof input.callerEnforcedFreshness !== 'boolean')) { throw inputError('invalid-request'); } input.headers = hookHeaders(input.headers); diff --git a/crates/registry-breg-client-node/index.d.ts b/crates/registry-breg-client-node/index.d.ts index 6c98dcc795..6a4720c65e 100644 --- a/crates/registry-breg-client-node/index.d.ts +++ b/crates/registry-breg-client-node/index.d.ts @@ -381,6 +381,17 @@ export interface HookDeliveryInput { headers: Record body: Buffer key: Buffer + /** + * Window around the receiver clock, in whole seconds from 1 to 3600. + * With neither this nor `callerEnforcedFreshness`, the window is 300 + * seconds. + */ + maxSkewSeconds?: number + /** + * Check only that the delivery time is well formed; the caller enforces + * its own window. Cannot be combined with `maxSkewSeconds`. + */ + callerEnforcedFreshness?: boolean } /** Validated product result serialized before the JavaScript number boundary. */ @@ -433,5 +444,10 @@ export interface VerifiedHookDelivery { body: Buffer } -/** Verify a BReg Version 1 hook signature without applying receiver policy. */ +/** + * Verify a BReg Version 1 hook signature. The delivery time must fall within + * 300 seconds of the receiver clock unless `maxSkewSeconds` or + * `callerEnforcedFreshness` says otherwise. Deduplication stays with the + * caller. + */ export declare function verifyHookDelivery(input: HookDeliveryInput): VerifiedHookDelivery diff --git a/crates/registry-breg-client-node/src/lib.rs b/crates/registry-breg-client-node/src/lib.rs index 52c945065b..de740939c6 100644 --- a/crates/registry-breg-client-node/src/lib.rs +++ b/crates/registry-breg-client-node/src/lib.rs @@ -23,7 +23,7 @@ use registry_breg_client::{ BRegCurrentContinuation, BRegCurrentContinuationProjection, BRegCurrentListRequest, BRegDirectWrite, BRegEtag, BRegEventRecordError, BRegGeoJsonContinuation, BRegGeoJsonContinuationProjection, BRegGeoJsonListRequest, BRegGeoJsonOptions, - BRegHookDelivery as CoreHookDelivery, BRegHookVerificationError, + BRegHookDelivery as CoreHookDelivery, BRegHookFreshness, BRegHookVerificationError, BRegIngestionChunk as CoreIngestionChunk, BRegIngestionError, BRegIngestionPrefixDigest as CoreIngestionPrefixDigest, BRegIngestionRunListQuery, BRegIngestionRunRequest, BRegListRequest, BRegLookupRequest, BRegMetadata as CoreMetadata, @@ -75,6 +75,13 @@ pub struct HookDeliveryInput { pub headers: BTreeMap, pub body: Buffer, pub key: Buffer, + /// Window around the receiver clock, in whole seconds from 1 to 3600. + /// With neither this nor `callerEnforcedFreshness`, the window is 300 + /// seconds. + pub max_skew_seconds: Option, + /// Check only that the delivery time is well formed; the caller enforces + /// its own window. Cannot be combined with `maxSkewSeconds`. + pub caller_enforced_freshness: Option, } /// Authenticated BReg hook metadata and exact body. @@ -92,9 +99,35 @@ pub struct VerifiedHookDelivery { pub body: Buffer, } -/// Verify a BReg Version 1 hook signature without applying receiver policy. +const HOOK_MAXIMUM_SKEW_SECONDS: f64 = 3600.0; + +fn hook_freshness( + max_skew_seconds: Option, + caller_enforced_freshness: Option, +) -> Result { + let invalid = || binding_error("invalid-request", "hook freshness options are invalid"); + match (max_skew_seconds, caller_enforced_freshness) { + (None, None | Some(false)) => Ok(BRegHookFreshness::DefaultWindow), + (None, Some(true)) => Ok(BRegHookFreshness::CallerEnforced), + (Some(_), Some(true)) => Err(invalid()), + (Some(seconds), None | Some(false)) => { + if seconds.fract() != 0.0 || !(1.0..=HOOK_MAXIMUM_SKEW_SECONDS).contains(&seconds) { + return Err(invalid()); + } + Ok(BRegHookFreshness::Within { + skew: std::time::Duration::from_secs(seconds as u64), + }) + } + } +} + +/// Verify a BReg Version 1 hook signature. The delivery time must fall within +/// 300 seconds of the receiver clock unless `maxSkewSeconds` or +/// `callerEnforcedFreshness` says otherwise. Deduplication stays with the +/// caller. #[napi] pub fn verify_hook_delivery(input: HookDeliveryInput) -> Result { + let freshness = hook_freshness(input.max_skew_seconds, input.caller_enforced_freshness)?; let headers = input.headers.into_iter().collect::>(); let verified = verify_core_hook_delivery(CoreHookDelivery { method: &input.method, @@ -102,6 +135,7 @@ pub fn verify_hook_delivery(input: HookDeliveryInput) -> Result VerifiedHookDelivery: """Authenticate one exact Base Registry Engine Version 1 hook delivery. - Apply delivery-time skew and deduplication policy before acting on the body.""" + The delivery time must be within 300 seconds of the receiver clock unless + `max_skew_seconds` (1 to 3600) names another window or + `caller_enforced_freshness` leaves the bound to the caller. A time outside + the window raises code `stale-delivery`. Deduplicate before acting on the body.""" ... def event_record_view(arguments: dict[str, JsonValue]) -> dict[str, JsonValue]: diff --git a/crates/registry-breg-client-py/src/lib.rs b/crates/registry-breg-client-py/src/lib.rs index b2e0958ea4..bc39955ad3 100644 --- a/crates/registry-breg-client-py/src/lib.rs +++ b/crates/registry-breg-client-py/src/lib.rs @@ -15,11 +15,12 @@ use breg_client_sdk::{ BRegCurrentContinuationProjection, BRegCurrentListRequest, BRegDirectWrite, BRegEtag, BRegEventRecordError, BRegGeoJsonContinuation, BRegGeoJsonContinuationProjection, BRegGeoJsonListRequest, BRegGeoJsonOptions, BRegHookDelivery as CoreHookDelivery, - BRegHookVerificationError, BRegIdempotencyKey, BRegIngestionChunk as CoreIngestionChunk, - BRegIngestionError, BRegIngestionPrefixDigest as CoreIngestionPrefixDigest, - BRegIngestionRunListQuery, BRegIngestionRunRequest, BRegListRequest, BRegLookupRequest, - BRegMetadata as CoreMetadata, BRegMetadataSelectionError, BRegMetadataSelectionErrorKind, - BRegPage, BRegPatchBinding, BRegPatchRequest, BRegPreparedAction as CorePreparedAction, + BRegHookFreshness, BRegHookVerificationError, BRegIdempotencyKey, + BRegIngestionChunk as CoreIngestionChunk, BRegIngestionError, + BRegIngestionPrefixDigest as CoreIngestionPrefixDigest, BRegIngestionRunListQuery, + BRegIngestionRunRequest, BRegListRequest, BRegLookupRequest, BRegMetadata as CoreMetadata, + BRegMetadataSelectionError, BRegMetadataSelectionErrorKind, BRegPage, BRegPatchBinding, + BRegPatchRequest, BRegPreparedAction as CorePreparedAction, BRegPreparedCreate as CorePreparedCreate, BRegProtocolFailure, BRegRawDocument, BRegRecordFormat, BRegRecordOptions, BRegRelationshipContinuation, BRegRelationshipContinuationProjection, BRegRelationshipListRequest, BRegReleaseSelection, @@ -1045,18 +1046,59 @@ fn event_record_view<'py>( json_to_python(py, view.as_value()) } +const HOOK_MAXIMUM_SKEW_SECONDS: u32 = 3600; + +/// The freshness window of one hook delivery. A `bool` is not a count. +fn hook_freshness( + py: Python<'_>, + max_skew_seconds: Option<&Bound<'_, PyAny>>, + caller_enforced_freshness: bool, +) -> PyResult { + let invalid = || { + to_py_err( + py, + MappedError::binding( + "invalid-request", + "hook freshness options are invalid: max_skew_seconds is a whole number from 1 to 3600 and cannot be combined with caller_enforced_freshness", + ), + ) + }; + let Some(value) = max_skew_seconds.filter(|value| !value.is_none()) else { + return Ok(if caller_enforced_freshness { + BRegHookFreshness::CallerEnforced + } else { + BRegHookFreshness::DefaultWindow + }); + }; + if caller_enforced_freshness || value.is_instance_of::() { + return Err(invalid()); + } + let seconds = value.extract::().map_err(|_| invalid())?; + if !(1..=HOOK_MAXIMUM_SKEW_SECONDS).contains(&seconds) { + return Err(invalid()); + } + Ok(BRegHookFreshness::Within { + skew: Duration::from_secs(u64::from(seconds)), + }) +} + /// Verify one exact Base Registry Engine Version 1 hook delivery with the /// shared Rust verifier and return its authenticated attributes and body. /// /// `path` is the request target the receiver was called on, `headers` is an /// ordered sequence of name/value pairs (matched without regard to ASCII case), `body` is -/// the exact request body, and `key` is the destination's HMAC key. Receiver -/// policy is the caller's: bound `delivery_time` against the receiver clock -/// and deduplicate before acting on `body`. Refusal raises +/// the exact request body, and `key` is the destination's HMAC key. The +/// delivery time must fall within 300 seconds of the receiver clock. Pass +/// `max_skew_seconds` (a whole number from 1 to 3600) for another window, or +/// `caller_enforced_freshness=True` to check only that the time is well formed +/// and bound it yourself, but not both. A time outside the window raises code +/// `stale-delivery`. Deduplication stays the caller's: deduplicate before +/// acting on `body`. Refusal raises /// `BaseRegistryClientError` with kind `hook-verification` and a value-free /// `code`; input of the wrong shape raises kind `invalid-request`. #[pyfunction] -#[pyo3(signature = (*, method, path, headers, body, key))] +#[pyo3(signature = (*, method, path, headers, body, key, max_skew_seconds=None, caller_enforced_freshness=false))] +#[allow(clippy::too_many_arguments)] fn verify_hook_delivery<'py>( py: Python<'py>, method: &Bound<'py, PyAny>, @@ -1064,7 +1106,10 @@ fn verify_hook_delivery<'py>( headers: &Bound<'py, PyAny>, body: &Bound<'py, PyAny>, key: &Bound<'py, PyAny>, + max_skew_seconds: Option<&Bound<'py, PyAny>>, + caller_enforced_freshness: bool, ) -> PyResult> { + let freshness = hook_freshness(py, max_skew_seconds, caller_enforced_freshness)?; let method = hook_text(py, method, "method")?; let path = hook_text(py, path, "path")?; let headers = hook_headers(py, headers)?; @@ -1076,6 +1121,7 @@ fn verify_hook_delivery<'py>( headers: &headers, body: body.as_bytes(), key: key.as_bytes(), + freshness, }) .map_err(|error| hook_verification_error(py, error))?; let result = PyDict::new(py); diff --git a/crates/registry-breg-client-py/tests/python/test_webhook_verification.py b/crates/registry-breg-client-py/tests/python/test_webhook_verification.py index c2db4472e0..3c542c7afa 100644 --- a/crates/registry-breg-client-py/tests/python/test_webhook_verification.py +++ b/crates/registry-breg-client-py/tests/python/test_webhook_verification.py @@ -7,8 +7,12 @@ from __future__ import annotations -import unittest +import base64 +import hashlib +import hmac import json +import unittest +from datetime import datetime, timedelta, timezone from pathlib import Path from bootstrap import ensure_built @@ -57,11 +61,47 @@ def verify(**overrides): "headers": headers(), "body": BODY, "key": KEY, + # The fixed vector is dated 2026-08-30, outside any default window. + "caller_enforced_freshness": True, } arguments.update(overrides) return verify_hook_delivery(**arguments) +def signed_headers(delivery_time: datetime) -> list[tuple[str, str]]: + """The fixed headers re-signed for `delivery_time` with the vector's key.""" + stamp = delivery_time.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + values = replace_header(headers(), "x-registry-delivery-time", stamp) + by_name = {name.lower(): value for name, value in values} + signed = bytearray(b"breg-webhook-signature-v1") + for value in ( + by_name["ce-specversion"].encode(), + by_name["ce-id"].encode(), + by_name["ce-source"].encode(), + by_name["ce-type"].encode(), + by_name["ce-time"].encode(), + by_name["ce-dataschema"].encode(), + by_name["x-registry-event-generation"].encode(), + by_name["x-registry-delivery-attempt"].encode(), + by_name["x-registry-delivery-time"].encode(), + b"POST", + b"/hooks/registry", + b"application/json", + by_name["idempotency-key"].encode(), + BODY, + ): + signed.extend(len(value).to_bytes(8, "big") + value) + digest = hmac.new(KEY, signed, hashlib.sha256).digest() + signature = "v1=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode() + return replace_header(values, "x-registry-signature", signature) + + +def verify_default(delivery_time: datetime, **overrides): + return verify( + headers=signed_headers(delivery_time), caller_enforced_freshness=False, **overrides + ) + + class HookVerificationTests(unittest.TestCase): def test_shared_language_vectors_preserve_exact_rfc3339_fractions(self): fixture = Path(__file__).resolve().parents[3] / "registry-platform-crypto/tests/fixtures/delivery-signatures.json" @@ -113,6 +153,53 @@ def test_fixed_vector_verifies_and_returns_exact_delivery(self) -> None: ) self.assertIsInstance(verified["body"], bytes) + def test_default_window_is_300_seconds_in_both_directions(self) -> None: + now = datetime.now(timezone.utc) + for offset in (0, -290, 290): + with self.subTest(offset=offset): + self.assertEqual( + verify_default(now + timedelta(seconds=offset))["id"], + "00000000-0000-4000-8000-000000000001", + ) + for offset in (-310, 310): + with self.subTest(offset=offset): + with self.assertRaises(BaseRegistryClientError) as raised: + verify_default(now + timedelta(seconds=offset)) + self.assertEqual(raised.exception.kind, "hook-verification") + self.assertEqual(raised.exception.code, "stale-delivery") + + def test_default_window_refuses_the_old_fixed_vector(self) -> None: + self.assert_refused("stale-delivery", caller_enforced_freshness=False) + + def test_max_skew_seconds_replaces_the_default_window(self) -> None: + stamp = datetime.now(timezone.utc) - timedelta(seconds=600) + self.assertEqual(verify_default(stamp, max_skew_seconds=900)["attempt"], "1") + with self.assertRaises(BaseRegistryClientError) as raised: + verify_default(datetime.now(timezone.utc) - timedelta(seconds=60), max_skew_seconds=10) + self.assertEqual(raised.exception.code, "stale-delivery") + + def test_caller_enforced_freshness_accepts_an_old_delivery(self) -> None: + self.assertEqual(verify(caller_enforced_freshness=True)["attempt"], "1") + + def test_refuses_a_freshness_option_out_of_range_or_combined(self) -> None: + for overrides in ( + {"max_skew_seconds": 0}, + {"max_skew_seconds": 3601}, + {"max_skew_seconds": -1}, + {"max_skew_seconds": 1.5}, + {"max_skew_seconds": True}, + {"max_skew_seconds": "10"}, + {"max_skew_seconds": 10, "caller_enforced_freshness": True}, + ): + with self.subTest(overrides=overrides): + with self.assertRaises(BaseRegistryClientError) as raised: + verify(**{"caller_enforced_freshness": False, **overrides}) + self.assertEqual(raised.exception.kind, "invalid-request") + for edge in (1, 3600): + self.assertEqual( + verify_default(datetime.now(timezone.utc), max_skew_seconds=edge)["attempt"], "1" + ) + def test_arguments_are_keyword_only(self) -> None: with self.assertRaises(TypeError): verify_hook_delivery("POST", "/hooks/registry", headers(), BODY, KEY) diff --git a/crates/registry-breg-client/src/hook.rs b/crates/registry-breg-client/src/hook.rs index f25ab7aa7f..244f435f81 100644 --- a/crates/registry-breg-client/src/hook.rs +++ b/crates/registry-breg-client/src/hook.rs @@ -1,7 +1,22 @@ +use std::time::{Duration, SystemTime}; + use registry_platform_hooks::receiver::{ verify_delivery, DeliveryFreshness, ReceiverError, SignedDelivery, }; +/// How the verifier bounds the signed delivery time. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum BRegHookFreshness { + /// Refuse a delivery time further than 300 seconds from the receiver clock. + #[default] + DefaultWindow, + /// Refuse a delivery time further than `skew` from the receiver clock. + Within { skew: Duration }, + /// Check only that the delivery time is well formed. The caller enforces + /// its own window. + CallerEnforced, +} + /// Exact request material supplied to the BReg Version 1 hook verifier. /// /// Header pairs retain order and duplicates; names are matched without regard @@ -13,6 +28,7 @@ pub struct BRegHookDelivery<'a> { pub headers: &'a [(String, String)], pub body: &'a [u8], pub key: &'a [u8], + pub freshness: BRegHookFreshness, } impl std::fmt::Debug for BRegHookDelivery<'_> { @@ -23,9 +39,10 @@ impl std::fmt::Debug for BRegHookDelivery<'_> { /// Authenticated BReg hook attributes and exact body. /// -/// Verification does not apply replay, delivery-time skew, or deduplication -/// policy. Receivers must apply those policies to `delivery_time` and -/// `idempotency_key` before acting on the body. +/// Verification applies the delivery-time window named by +/// [`BRegHookFreshness`], 300 seconds by default. It does not apply replay or +/// deduplication policy. Receivers must deduplicate on `idempotency_key` +/// before acting on the body. #[derive(Clone, Eq, PartialEq)] pub struct BRegVerifiedHookDelivery { pub id: String, @@ -57,6 +74,8 @@ pub enum BRegHookVerificationError { MissingHeader, #[error("the Base Registry Engine hook delivery time is invalid; check the signed delivery time and sender clock")] InvalidDeliveryTime, + #[error("the Base Registry Engine hook delivery time is outside the freshness window; check the receiver clock, or pass a wider window")] + StaleDelivery, #[error("a Base Registry Engine hook header is repeated; remove duplicate signed headers")] DuplicateHeader, #[error( @@ -80,6 +99,7 @@ impl BRegHookVerificationError { match self { Self::MissingHeader => "missing-header", Self::InvalidDeliveryTime => "invalid-delivery-time", + Self::StaleDelivery => "stale-delivery", Self::DuplicateHeader => "duplicate-header", Self::BodyTooLarge => "body-too-large", Self::InvalidKey => "invalid-key", @@ -90,16 +110,30 @@ impl BRegHookVerificationError { } } -/// Verify one exact BReg Version 1 hook delivery without applying receiver policy. +/// Verify one exact BReg Version 1 hook delivery against the system clock. /// /// This delegates header extraction, the signature input, RFC 3339 /// delivery-time validation, and constant-time HMAC comparison to the shared -/// `registry_platform_hooks::receiver::verify_delivery`. Caller-enforced -/// freshness leaves the receiver's clock policy separate; the caller receives -/// the authenticated raw delivery time to enforce its own skew bound. +/// `registry_platform_hooks::receiver::verify_delivery`. The delivery time must +/// fall inside the window `delivery.freshness` names, 300 seconds either way by +/// default. Deduplication stays with the caller. pub fn verify_hook_delivery( delivery: BRegHookDelivery<'_>, ) -> Result { + verify_hook_delivery_at(delivery, SystemTime::now()) +} + +/// Same as [`verify_hook_delivery`], against `now`. For tests and for callers +/// with their own clock. +pub fn verify_hook_delivery_at( + delivery: BRegHookDelivery<'_>, + now: SystemTime, +) -> Result { + let freshness = match delivery.freshness { + BRegHookFreshness::DefaultWindow => DeliveryFreshness::default_at(now), + BRegHookFreshness::Within { skew } => DeliveryFreshness::Within { now, skew }, + BRegHookFreshness::CallerEnforced => DeliveryFreshness::CallerEnforced, + }; let verified = verify_delivery( SignedDelivery { method: delivery.method, @@ -111,7 +145,7 @@ pub fn verify_hook_delivery( body: delivery.body, key: delivery.key, }, - DeliveryFreshness::CallerEnforced, + freshness, ) .map_err(map_receiver_error)?; @@ -132,9 +166,8 @@ pub fn verify_hook_delivery( fn map_receiver_error(error: ReceiverError) -> BRegHookVerificationError { match error { ReceiverError::MissingHeader => BRegHookVerificationError::MissingHeader, - ReceiverError::InvalidDeliveryTime | ReceiverError::Stale => { - BRegHookVerificationError::InvalidDeliveryTime - } + ReceiverError::InvalidDeliveryTime => BRegHookVerificationError::InvalidDeliveryTime, + ReceiverError::Stale => BRegHookVerificationError::StaleDelivery, ReceiverError::DuplicateHeader => BRegHookVerificationError::DuplicateHeader, ReceiverError::BodyTooLarge => BRegHookVerificationError::BodyTooLarge, ReceiverError::InvalidKey => BRegHookVerificationError::InvalidKey, diff --git a/crates/registry-breg-client/tests/webhook.rs b/crates/registry-breg-client/tests/webhook.rs index b4434a3adc..d167b10b03 100644 --- a/crates/registry-breg-client/tests/webhook.rs +++ b/crates/registry-breg-client/tests/webhook.rs @@ -1,7 +1,14 @@ -use registry_breg_client::{verify_hook_delivery, BRegHookDelivery, BRegHookVerificationError}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use registry_breg_client::{ + verify_hook_delivery, verify_hook_delivery_at, BRegHookDelivery, BRegHookFreshness, + BRegHookVerificationError, +}; const KEY: &[u8] = b"webhook-delivery-signing-key-0123456789abcdef"; const BODY: &[u8] = br#"{"entity":"case","values":{"label":"value"}}"#; +/// Unix seconds of the vector's signed delivery time, 2026-08-30T00:00:01Z. +const DELIVERY_EPOCH: u64 = 1_788_048_001; const SIGNATURE: &str = "v1=OzL5k0ghZJb9nPbb-JOVsroWeanipBlZXbeKDd52RcM"; fn headers() -> Vec<(String, String)> { @@ -44,9 +51,24 @@ fn delivery<'a>( headers, body, key, + freshness: BRegHookFreshness::CallerEnforced, + } +} + +fn delivery_with<'a>( + headers: &'a [(String, String)], + freshness: BRegHookFreshness, +) -> BRegHookDelivery<'a> { + BRegHookDelivery { + freshness, + ..delivery(headers, BODY, KEY) } } +fn at(offset_seconds: i64) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(DELIVERY_EPOCH.checked_add_signed(offset_seconds).unwrap()) +} + fn set_header(headers: &mut [(String, String)], name: &str, value: impl Into) { headers .iter_mut() @@ -58,7 +80,11 @@ fn set_header(headers: &mut [(String, String)], name: &str, value: impl Into typeof key !== 'string') - || keys.length !== expectedFields.length - || keys.some((key) => !expectedFields.includes(key))) throw inputError('invalid-request'); + || keys.some((key) => !expectedFields.includes(key) && !optionalFields.includes(key)) + || expectedFields.some((field) => !keys.includes(field))) throw inputError('invalid-request'); const result = Object.create(null); - for (const field of expectedFields) { + for (const field of keys) { const descriptor = Object.getOwnPropertyDescriptor(value, field); if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) { throw inputError('invalid-request'); @@ -107,10 +107,17 @@ function hookHeaders(value) { function verifyHookDelivery(value) { try { - const input = plainDataObject(value, ['method', 'path', 'headers', 'body', 'key']); + const input = plainDataObject( + value, + ['method', 'path', 'headers', 'body', 'key'], + ['maxSkewSeconds', 'callerEnforcedFreshness'], + ); if (typeof input.method !== 'string' || typeof input.path !== 'string' || !Buffer.isBuffer(input.body) || !Buffer.isBuffer(input.key) - || isSharedArrayBuffer(input.body.buffer) || isSharedArrayBuffer(input.key.buffer)) { + || isSharedArrayBuffer(input.body.buffer) || isSharedArrayBuffer(input.key.buffer) + || (input.maxSkewSeconds !== undefined && !Number.isSafeInteger(input.maxSkewSeconds)) + || (input.callerEnforcedFreshness !== undefined + && typeof input.callerEnforcedFreshness !== 'boolean')) { throw inputError('invalid-request'); } input.headers = hookHeaders(input.headers); diff --git a/crates/registry-stack-client-node/breg/index.d.ts b/crates/registry-stack-client-node/breg/index.d.ts index 2d308a4fbd..f10437af65 100644 --- a/crates/registry-stack-client-node/breg/index.d.ts +++ b/crates/registry-stack-client-node/breg/index.d.ts @@ -373,6 +373,17 @@ export interface HookDeliveryInput { headers: Record body: Buffer key: Buffer + /** + * Window around the receiver clock, in whole seconds from 1 to 3600. + * With neither this nor `callerEnforcedFreshness`, the window is 300 + * seconds. + */ + maxSkewSeconds?: number + /** + * Check only that the delivery time is well formed; the caller enforces + * its own window. Cannot be combined with `maxSkewSeconds`. + */ + callerEnforcedFreshness?: boolean } /** Validated product result serialized before the JavaScript number boundary. */ @@ -425,5 +436,10 @@ export interface VerifiedHookDelivery { body: Buffer } -/** Verify a BReg Version 1 hook signature without applying receiver policy. */ +/** + * Verify a BReg Version 1 hook signature. The delivery time must fall within + * 300 seconds of the receiver clock unless `maxSkewSeconds` or + * `callerEnforcedFreshness` says otherwise. Deduplication stays with the + * caller. + */ export declare function verifyHookDelivery(input: HookDeliveryInput): VerifiedHookDelivery diff --git a/crates/registry-stack-client/src/lib.rs b/crates/registry-stack-client/src/lib.rs index 7f16c860c1..7135bf53be 100644 --- a/crates/registry-stack-client/src/lib.rs +++ b/crates/registry-stack-client/src/lib.rs @@ -6,8 +6,8 @@ pub mod breg { pub use registry_breg_client::{ event_record_view, event_record_view_from_json, verify_hook_delivery, - BRegActionApplication, BRegActionBinding, BRegActionBounds, BRegActionDescriptor, - BRegActionError, BRegActionInputBinding, BRegActionInputDescriptor, + verify_hook_delivery_at, BRegActionApplication, BRegActionBinding, BRegActionBounds, + BRegActionDescriptor, BRegActionError, BRegActionInputBinding, BRegActionInputDescriptor, BRegActionInvocationRequest, BRegActionMode, BRegActionReceipt, BRegActionReferenceInputDescriptor, BRegActionResultEffectDescriptor, BRegActionResultReference, BRegActionReview, BRegActionTargetConditions, @@ -15,22 +15,22 @@ pub mod breg { BRegContinuation, BRegContinuationProjection, BRegCreateBinding, BRegCreateRequest, BRegCreationRevision, BRegDirectWrite, BRegEtag, BRegEventRecordDescriptor, BRegEventRecordError, BRegEventRecordEvidence, BRegEventRecordView, BRegHookDelivery, - BRegHookVerificationError, BRegIdempotencyKey, BRegListRequest, BRegLookupRequest, - BRegMetadata, BRegMetadataOperation, BRegMetadataSelectionError, BRegMutationRequestError, - BRegOperationKind, BRegPage, BRegPatchBinding, BRegPatchBuilder, BRegPatchRequest, - BRegPreparedAction, BRegPreparedCreate, BRegPreparedProposal, BRegProbeStatus, - BRegProblemCode, BRegProposal, BRegProposalApplication, BRegProposalAttachment, - BRegProposalAttachmentValue, BRegProposalCollection, BRegProposalDecision, - BRegProposalDecisionStatus, BRegProposalGetBinding, BRegProposalLink, BRegProposalPage, - BRegProposalQuery, BRegProposalResultReference, BRegProposalReviewBinding, - BRegProposalReviewContext, BRegProposalReviewDocument, BRegProposalReviewHandoff, - BRegProposalReviewHandoffReason, BRegProposalReviewHandoffState, BRegProposalReviewResult, - BRegProposalReviewSubject, BRegProposalState, BRegProposalSubmission, - BRegProposalSubmissionApplication, BRegProposalTurn, BRegProtocolFailure, BRegRawDocument, - BRegRecordFormat, BRegRecordOptions, BRegRecoveryHint, BRegRequestError, - BRegResponseMetadata, BRegVerifiedHookDelivery, BaseRegistryClient, - BaseRegistryClientConfig, BaseRegistryClientError, PolicySelection, ReviewProgressCode, - Uuid, EVENT_RECORD_DESCRIPTOR_VERSION, EVENT_RECORD_VIEW_CONTRACT, + BRegHookFreshness, BRegHookVerificationError, BRegIdempotencyKey, BRegListRequest, + BRegLookupRequest, BRegMetadata, BRegMetadataOperation, BRegMetadataSelectionError, + BRegMutationRequestError, BRegOperationKind, BRegPage, BRegPatchBinding, BRegPatchBuilder, + BRegPatchRequest, BRegPreparedAction, BRegPreparedCreate, BRegPreparedProposal, + BRegProbeStatus, BRegProblemCode, BRegProposal, BRegProposalApplication, + BRegProposalAttachment, BRegProposalAttachmentValue, BRegProposalCollection, + BRegProposalDecision, BRegProposalDecisionStatus, BRegProposalGetBinding, BRegProposalLink, + BRegProposalPage, BRegProposalQuery, BRegProposalResultReference, + BRegProposalReviewBinding, BRegProposalReviewContext, BRegProposalReviewDocument, + BRegProposalReviewHandoff, BRegProposalReviewHandoffReason, BRegProposalReviewHandoffState, + BRegProposalReviewResult, BRegProposalReviewSubject, BRegProposalState, + BRegProposalSubmission, BRegProposalSubmissionApplication, BRegProposalTurn, + BRegProtocolFailure, BRegRawDocument, BRegRecordFormat, BRegRecordOptions, + BRegRecoveryHint, BRegRequestError, BRegResponseMetadata, BRegVerifiedHookDelivery, + BaseRegistryClient, BaseRegistryClientConfig, BaseRegistryClientError, PolicySelection, + ReviewProgressCode, Uuid, EVENT_RECORD_DESCRIPTOR_VERSION, EVENT_RECORD_VIEW_CONTRACT, }; } diff --git a/docs/site/src/content/docs/operate/breg-webhooks.mdx b/docs/site/src/content/docs/operate/breg-webhooks.mdx index 5c29a97c8d..42016108e5 100644 --- a/docs/site/src/content/docs/operate/breg-webhooks.mdx +++ b/docs/site/src/content/docs/operate/breg-webhooks.mdx @@ -309,14 +309,23 @@ The receiver should: 1. Verify `X-Registry-Signature` against the exact request bytes, in the signing-input order the [API reference](../../reference/breg-api/#events-and-webhooks) defines. -2. Check `X-Registry-Delivery-Time` for freshness. +2. Check `X-Registry-Delivery-Time` for freshness. The Node, Python and Rust verifiers the client + packages ship refuse a delivery time more than 300 seconds from the receiver clock, either way, + with the code `stale-delivery`. A receiver that sets no window gets that default. Pass + `maxSkewSeconds` (Python `max_skew_seconds`, 1 to 3600) for another window, or + `callerEnforcedFreshness: true` (Python `caller_enforced_freshness=True`) to bound the time + yourself. Coordinator's own receiver stays at 30 seconds until its signed delivery format + changes, which is stricter than the verifier we ship and safe to run beside it. 3. Read the Record type from `data.recordType` and the record from `data.recordId`, and order events for one record by `data.revision`. 4. Deduplicate by `Idempotency-Key`, and answer `2xx` only after it has durably recorded the event. {/* Evidence: crates/registry-bregctl/src/lib.rs, HookSampleArgs and hook_sample(); crates/registry-bregctl/src/hook_lifecycle.rs, sample() and synthetic_field_value(); - crates/registry-breg/src/hooks.rs. */} + crates/registry-breg/src/hooks.rs; + crates/registry-breg-client/src/hook.rs BRegHookFreshness, verify_hook_delivery_at; + crates/registry-platform-hooks/src/receiver.rs DEFAULT_DELIVERY_SKEW; + crates/registry-coordinator/src/event_trigger.rs DELIVERY_SKEW. */} ## Settle local hooks before go-live diff --git a/docs/site/src/content/docs/reference/breg-client-capabilities.mdx b/docs/site/src/content/docs/reference/breg-client-capabilities.mdx index 262e22771c..f1993c1aaf 100644 --- a/docs/site/src/content/docs/reference/breg-client-capabilities.mdx +++ b/docs/site/src/content/docs/reference/breg-client-capabilities.mdx @@ -371,7 +371,7 @@ attribute the failure does not carry is absent in Node and `None` in Python. | `problem` | The server answered with any other Problem | `status`, `traceId`; a known code adds `code` and any `fieldPath`, `constraint`, `refusalCode`, or `reasonCode` | | `protocol` | The response broke the contract | `status`, `traceId` when valid, and `code`: `header-bounds`, `trace-context`, `media-type`, `body`, `problem`, `entity-tag`, `profile-link`, `location`, `cache-policy`, `representation-digest`, `status`, or `protocol` | | `metadata-selection` | No binding matched | `code`: `not-found`, `unbound-source`, `profile-mismatch`, `unsupported-operation`, `required-capability`, or `contract-mismatch` | -| `hook-verification` | A hook delivery failed authentication | `code`: `missing-header`, `invalid-delivery-time`, `duplicate-header`, `body-too-large`, `invalid-key`, `malformed-signature`, `signature-mismatch`, or `unsupported-version` | +| `hook-verification` | A hook delivery failed authentication | `code`: `missing-header`, `invalid-delivery-time`, `stale-delivery`, `duplicate-header`, `body-too-large`, `invalid-key`, `malformed-signature`, `signature-mismatch`, or `unsupported-version` | | `client` | Any other client-side failure | none | A Problem code this client version does not know arrives as kind `problem` with only `status` and diff --git a/docs/site/src/content/docs/reference/delivery-signing.mdx b/docs/site/src/content/docs/reference/delivery-signing.mdx index 70efd7f9ce..8b927f2082 100644 --- a/docs/site/src/content/docs/reference/delivery-signing.mdx +++ b/docs/site/src/content/docs/reference/delivery-signing.mdx @@ -45,11 +45,14 @@ The Node and Python bindings expose the same check as an entry point that takes - Python: `breg.verify_hook_delivery(method=..., path=..., headers=..., body=..., key=...)` Both return the authenticated exact values, including `deliveryTime` (Python `delivery_time`) and `idempotencyKey` (Python `idempotency_key`). -These binding entry points use caller-enforced freshness. -Compare the returned instant with your trusted clock and chosen window, and durably deduplicate on the idempotency key before taking an effect. +These binding entry points refuse a delivery time more than 300 seconds from the receiver clock, with the code `stale-delivery`. +Pass `maxSkewSeconds` (Python `max_skew_seconds`), a whole number from 1 to 3600, for another window. +Pass `callerEnforcedFreshness: true` (Python `caller_enforced_freshness=True`) to check only that the time is well formed, then compare the returned instant with your trusted clock yourself. +The two options cannot be combined. +Durably deduplicate on the idempotency key before taking an effect. Verification alone creates no source, schema, recipient, or business authority. -{/* Evidence: crates/registry-platform-hooks/src/receiver.rs CallerEnforced; +{/* Evidence: crates/registry-platform-hooks/src/receiver.rs CallerEnforced, DEFAULT_DELIVERY_SKEW; crates/registry-breg-client-py/src/lib.rs verify_hook_delivery; crates/registry-breg-client-node/__test__/webhook-verification.test.js verifyHookDelivery, deliveryTime. */} diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 2fa132febd..362cc56951 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +- The Rust, Node and Python hook verifiers in the BReg clients refuse a + delivery time more than 300 seconds from the receiver clock, either way, + with the new code `stale-delivery`. A receiver that passed nothing gets that + window. `maxSkewSeconds` (Python `max_skew_seconds`, 1 to 3600) sets another + window, and `callerEnforcedFreshness: true` (Python + `caller_enforced_freshness=True`) keeps the earlier behaviour of checking + only that the time is well formed. Rust callers that build + `BRegHookDelivery` as a struct literal add the `freshness` member + (`BRegHookFreshness::default()` for the window). +- A pinned static key set (`authentication.oidc.jwksSource.type: static`) + follows the shared public-key rule every product uses. Members BReg does not + name, such as `x5c` or `ext`, and members beside `keys` no longer refuse the + document. A private or symmetric key member, a repeated member name, and a + missing or repeated `kid` are still refused, and the startup refusal names + the rule and the key's position. A listener origin treats an IPv4-mapped + loopback literal, such as `[::ffff:127.0.0.1]`, as loopback. + - Refused Record file downloads use the same attachment audit operation as served downloads, including refusals before database access. The slot suffix names only a declared slot. Caller-supplied undeclared names stay out of audit. diff --git a/products/breg/examples/webhook-receiver/receiver.py b/products/breg/examples/webhook-receiver/receiver.py index ef8af06428..97da0b109b 100644 --- a/products/breg/examples/webhook-receiver/receiver.py +++ b/products/breg/examples/webhook-receiver/receiver.py @@ -53,7 +53,12 @@ def _verify_webhook_request( # generation and attempt are positive decimals. The checks below apply this # receiver's own contract and clock policy to the authenticated values. verified = breg.verify_hook_delivery( - method="POST", path=path, headers=header_pairs, body=body, key=key + method="POST", + path=path, + headers=header_pairs, + body=body, + key=key, + caller_enforced_freshness=True, ) headers: dict[str, str] = {} for name, value in header_pairs: diff --git a/products/breg/examples/webhook-receiver/test_receiver.py b/products/breg/examples/webhook-receiver/test_receiver.py index 8316d9509d..09ca89dd73 100644 --- a/products/breg/examples/webhook-receiver/test_receiver.py +++ b/products/breg/examples/webhook-receiver/test_receiver.py @@ -387,7 +387,7 @@ def test_matches_the_shared_rust_wire_signature_vector(self): ] verified = RECEIVER.breg.verify_hook_delivery( method="POST", path="/hooks/registry", body=body, key=key, - headers=header_pairs, + headers=header_pairs, caller_enforced_freshness=True, ) self.assertEqual(verified["body"], body) diff --git a/products/platform/examples/python-composition/service.py b/products/platform/examples/python-composition/service.py index cb7f2c9079..5ac9b8cf44 100755 --- a/products/platform/examples/python-composition/service.py +++ b/products/platform/examples/python-composition/service.py @@ -154,8 +154,14 @@ def accept( if not body or len(body) > MAXIMUM_BODY: raise WakeRefused("hook body was refused") try: + # The window below uses this receiver's own clock, which tests inject. verified = verify_hook_delivery( - method=method, path=path, headers=headers, body=body, key=key + method=method, + path=path, + headers=headers, + body=body, + key=key, + caller_enforced_freshness=True, ) delivered = datetime.fromisoformat(verified["delivery_time"]) instant = datetime.now(UTC) if now is None else now diff --git a/products/platform/examples/python-composition/tests/test_service.py b/products/platform/examples/python-composition/tests/test_service.py index a9ac99e92a..3f08f0974b 100644 --- a/products/platform/examples/python-composition/tests/test_service.py +++ b/products/platform/examples/python-composition/tests/test_service.py @@ -111,6 +111,7 @@ def verified_proposal(envelope=None): headers=headers(), body=BODY, key=CANARY_KEY, + caller_enforced_freshness=True, ) verified.update( { From 00307a5d53c17cb264c9d947b1d007868faf1a8d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 02:50:12 +0100 Subject: [PATCH 014/136] test(platform): add the rstack dev acceptance journey and its observed stops The journey starts each of the sixteen runtimes with rstack dev and records where a reader stops today. Breg, Casework and Evidence stop at plan, because their init writes no dev.yaml; Scheduling, Documents, Coordinator and Render stop there too, because the plan cannot name them; Messaging reaches a call and loses its state on restart; Adapter and Discovery have no init. The ratchet table now holds these observed rows in place of the predicted ones. Signed-off-by: Jeremi Joslin --- .../platform/journeys/expected-failures.yaml | 133 +++--- products/platform/journeys/rstack-dev.sh | 445 ++++++++++++++++++ 2 files changed, 520 insertions(+), 58 deletions(-) create mode 100644 products/platform/journeys/rstack-dev.sh diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index 34da7e684b..4f995e31d4 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -124,77 +124,88 @@ expectedFailures: basis: predicted reason: Render fixes the token type at at+jwt and Keycloak sends typ JWT. - journey: rstack-dev - product: scheduling + product: breg step: plan - code: product.rstack-dev.plan-unparsed + code: journey.needs.hand-written-plan + finding: FH-4 removedBy: M4 - basis: predicted - reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "bregctl init writes a project with no dev.yaml. rstack dev check refuses it with rstack.dev.check-unavailable (cannot read dev.yaml), so the only way forward is a plan the reader writes." - journey: rstack-dev - product: coordinator + product: casework step: plan - code: product.rstack-dev.plan-unparsed + code: journey.needs.hand-written-plan removedBy: M4 - basis: predicted - reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "caseworkctl init writes casework.yaml with no dev.yaml. rstack dev check refuses it with rstack.dev.check-unavailable. Its own next step tells the reader to write a dev.yaml plan." - journey: rstack-dev - product: documents - step: plan - code: product.rstack-dev.plan-unparsed + product: messaging + step: keep + code: journey.keep.state-lost + finding: FH-3 removedBy: M4 - basis: predicted - reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "init ships a dev.yaml and the run reaches call (HTTP 202). After rstack dev stop and a second rstack dev start of the same project, the message the first run accepted answers HTTP 404, because every start draws fresh databases." - journey: rstack-dev - product: adapter + product: evidence step: plan - code: product.rstack-dev.plan-unparsed + code: journey.needs.hand-written-plan removedBy: M4 - basis: predicted - reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "evidencectl init --profile local --transport sqlite-extract writes a project with no dev.yaml, so rstack dev check refuses it with rstack.dev.check-unavailable. The attach step is not reached." - journey: rstack-dev - product: render + product: scheduling step: plan - code: product.rstack-dev.plan-unparsed + code: product.config.unknown-variant removedBy: M4 - basis: predicted - reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "init succeeds and writes no dev.yaml. A hand-written dev.yaml naming scheduling is refused with config.unknown-variant at /products/0/product: expected one of breg, casework, evidence, messaging." - journey: rstack-dev - product: discovery + product: documents step: plan - code: product.rstack-dev.plan-unparsed + code: product.config.unknown-variant removedBy: M4 - basis: predicted - reason: The plan's product type has four members (breg, casework, evidence, messaging), so a plan that names this product does not parse. The exact message is not yet observed. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "init succeeds and writes no dev.yaml. A hand-written dev.yaml naming documents is refused with config.unknown-variant at /products/0/product: expected one of breg, casework, evidence, messaging." - journey: rstack-dev - product: breg + product: coordinator step: plan - code: journey.needs.hand-written-plan - finding: FH-4 + code: product.config.unknown-variant removedBy: M4 - basis: predicted - reason: bregctl init does not ship dev.yaml or the scenario file. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "init succeeds and writes no dev.yaml. A hand-written dev.yaml naming coordinator is refused with config.unknown-variant at /products/0/product: expected one of breg, casework, evidence, messaging." - journey: rstack-dev - product: casework + product: render step: plan - code: journey.needs.hand-written-plan + code: product.config.unknown-variant removedBy: M4 - basis: predicted - reason: Predicted from the same gap as BReg. What caseworkctl init writes is not yet observed. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "init succeeds and writes no dev.yaml. A hand-written dev.yaml naming render is refused with config.unknown-variant at /products/0/product: expected one of breg, casework, evidence, messaging." - journey: rstack-dev - product: messaging - step: keep - code: journey.keep.state-lost - finding: FH-3 + product: adapter + step: init + code: product.adapterctl.usage-invalid removedBy: M4 - basis: predicted - reason: The starter ships a plan, but every start draws fresh databases, so a written record does not survive a restart. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "adapterctl has no init command. adapterctl --format json init DIR is refused with adapterctl.usage-invalid (unrecognized subcommand), so there is no starter project to plan from." - journey: rstack-dev - product: evidence - step: attach - code: journey.attach.issuer-refused - removedBy: M11 - basis: predicted - reason: Evidence refuses any issuer other than the run's own. No database, so keep does not apply. + product: discovery + step: init + code: product.discovery.usage.invalid-arguments + removedBy: M4 + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "discoveryctl has no init command. discoveryctl init DIR is refused with discovery.usage.invalid-arguments (unrecognized subcommand), so there is no starter project to plan from." + - journey: promote product: breg step: input @@ -305,33 +316,39 @@ unreached: - journey: rstack-dev product: breg-mcp step: init - basis: predicted - reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "Supporting runtime. It has no rstack dev plan type and starts beside its parent." - journey: rstack-dev product: breg-review step: init - basis: predicted - reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "Supporting runtime. It has no rstack dev plan type and starts beside its parent." - journey: rstack-dev product: registry-mcp step: init - basis: predicted - reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "Supporting runtime. It has no rstack dev plan type and starts beside its parent." - journey: rstack-dev product: evidence-oid4vci step: init - basis: predicted - reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "Supporting runtime. It has no rstack dev plan type and starts beside its parent." - journey: rstack-dev product: evidence-oid4vp step: init - basis: predicted - reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "Supporting runtime. It has no rstack dev plan type and starts beside its parent." - journey: rstack-dev product: adapter-job step: init - basis: predicted - reason: Supporting runtime. It has no rstack dev plan type and starts beside its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" + reason: "Supporting runtime. It has no rstack dev plan type and starts beside its parent." - journey: promote product: breg-mcp step: input diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh new file mode 100644 index 0000000000..1383045071 --- /dev/null +++ b/products/platform/journeys/rstack-dev.sh @@ -0,0 +1,445 @@ +#!/usr/bin/env bash +# The rstack-dev acceptance journey: each product from nothing to a development +# run started by `rstack dev`, using the issuer the run starts and no identity +# provider of the reader's own. +# +# Steps, as the pass rule counts them: init, plan, start, issuer, token, call, +# hook, keep, attach, stop. A cell is one product and stops at its first +# failing step. See README.md for the options, the two modes and the exit codes. +# +# What this script starts: nothing of its own except the optional PostgreSQL +# container of the attach step. `rstack dev` starts its own PostgreSQL (and a +# mail sink for a Messaging smtp provider) under the names rstack-dev- and +# rstack-dev-mailpit-. The cleanup hook stops every run still live with +# `rstack dev stop` and reports, never removes, a container that remains. +# +# Recipes. The steps from `start` on need a recipe per product: the person to +# sign in as, the request that makes the first authenticated call and, for +# keep, the record to write and read back. Only the products whose recipe is +# written here can walk those steps; any other product that reaches one is a +# harness failure that names the missing recipe. +# +# Run it from anywhere: +# products/platform/journeys/rstack-dev.sh --bin-dir DIR [--product ID]... +# [--out DIR] [--expected FILE [--strict]] [--keep] + +set -euo pipefail + +# shellcheck disable=SC1091 # lib.sh is checked on its own +source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" + +journey_init rstack-dev -- "$@" +journey_require_docker + +# The tools every selected product's init needs, and rstack itself. +journey_resolve_binaries --package registry-rstack "${JOURNEY_PRODUCTS[@]}" +journey_bin rstack RSTACK_BIN + +# rstack dev reads its tools from these variables and keeps its state in a +# directory that must be owner-only. Both sit inside the run folder, so an +# installed rstack store and an earlier run's state are never read. A variable +# names a path even when the file is absent: a missing tool is then reported +# by rstack and never replaced by an installed one. +STATE_DIR=$JOURNEY_OUT/rstack-state +INSTALL_ROOT=$JOURNEY_OUT/rstack-install +mkdir -m 700 -- "$STATE_DIR" "$INSTALL_ROOT" +export RSTACK_DEV_STATE_DIR=$STATE_DIR +unset RSTACK_DEV_DATABASE_URL RSTACK_DEV_DATABASE_CA +for name in breg casework evidence messaging; do + upper=$(printf '%s' "$name" | tr '[:lower:]' '[:upper:]') + export "RSTACK_${upper}_BIN=$JOURNEY_BIN_DIR/$name" + export "RSTACK_${upper}CTL_BIN=$JOURNEY_BIN_DIR/${name}ctl" +done + +# Runs this script started and has not yet stopped, one id per line. +LIVE_RUNS='' +# The product whose cell is open, for messages. +CELL='' +# The containers `rstack dev` names for a run. +run_containers() { + printf 'rstack-dev-%s\nrstack-dev-mailpit-%s\n' "$1" "$1" +} + +# rstack_dev ARGUMENTS...: `rstack dev` with the run's own state and an empty +# install root, reporting in JSON. +rstack_dev() { + "$RSTACK_BIN" --install-root "$INSTALL_ROOT" --format json dev "$@" +} + +# state_is_empty: no run directory remains in the state directory. A `failed` +# folder only holds kept logs, and a name starting with a dot is a run whose +# files are being deleted. +state_is_empty() { + local entry + for entry in "$STATE_DIR"/* "$STATE_DIR"/.[!.]*; do + [[ -e "$entry" ]] || continue + [[ "${entry##*/}" == failed ]] || return 1 + done + return 0 +} + +# containers_absent RUN: neither container of RUN exists. +containers_absent() { + [[ -z "$(docker ps --all --quiet --filter "name=^rstack-dev-$1\$" --filter "name=^rstack-dev-mailpit-$1\$")" ]] +} + +# stop_run RUN: stop a run through rstack's own `rstack dev stop`, wait for its +# files and containers to go and forget the run. Returns 1 when something +# remains, with the cause on stderr. +stop_run() { + local run=$1 name left=0 + if ! rstack_dev stop "$run" >/dev/null; then + printf 'rstack dev stop %s failed\n' "$run" >&2 + return 1 + fi + LIVE_RUNS=$(printf '%s' "$LIVE_RUNS" | grep -vx -- "$run" || true) + journey_poll 30 -- state_is_empty || { + printf 'the state directory still holds files of run %s\n' "$run" >&2 + left=1 + } + while IFS= read -r name; do + journey_check_absent "$name" || left=1 + done < <(run_containers "$run") + return "$left" +} + +# stop_live_runs: the cleanup hook. Every run this script started and did not +# stop is stopped by rstack. A run that does not stop is a cleanup failure. +stop_live_runs() { + local run status=0 + while IFS= read -r run; do + [[ -n "$run" ]] || continue + stop_run "$run" || status=1 + done <<<"$LIVE_RUNS" + return "$status" +} +journey_at_cleanup stop_live_runs + +# diagnostic_code FILE...: the first diagnostic code a product printed in any +# FILE, from a JSON report or from an error[code] line. Empty when none. +diagnostic_code() { + local file code='' + for file in "$@"; do + code=$(jq -r '(.diagnostics[0].code // .error.code // empty)' "$file" 2>/dev/null || true) + if [[ -z "$code" ]]; then + code=$(perl -ne 'if (/^error\[([a-z0-9.-]+)\]/) { print $1; last }' "$file") + fi + [[ -z "$code" ]] || break + done + printf '%s' "$code" +} + +# fail_with_product_code STEP FILE...: the cell stops at STEP with the code the +# product printed. A refusal that prints no code is a harness failure: the +# journey would otherwise invent one. +fail_with_product_code() { + local step=$1 code + shift + code=$(diagnostic_code "$@") + [[ -n "$code" ]] || journey_harness_failure "step $step of $CELL failed and printed no diagnostic code; see $*" + journey_fail "$step" "product.$code" +} + +# The command that writes a product's starter project, as a reader types it. +# PROJECT is a directory that does not exist yet. A product with no init +# command gets the command a reader would try first. +init_command() { + local product=$1 project=$2 tool + case "$product" in + breg) INIT_COMMAND=("$JOURNEY_BIN_DIR/bregctl" init "$project") ;; + casework) INIT_COMMAND=("$JOURNEY_BIN_DIR/caseworkctl" init "$project") ;; + messaging) INIT_COMMAND=("$JOURNEY_BIN_DIR/messagingctl" init "$project") ;; + evidence) INIT_COMMAND=("$JOURNEY_BIN_DIR/evidencectl" init --profile local --transport sqlite-extract "$project") ;; + scheduling) INIT_COMMAND=("$JOURNEY_BIN_DIR/schedulingctl" init --template standalone-exact-time "$project") ;; + documents) INIT_COMMAND=("$JOURNEY_BIN_DIR/documentsctl" init "$project") ;; + coordinator) INIT_COMMAND=("$JOURNEY_BIN_DIR/coordinatorctl" init --directory "$project") ;; + render) INIT_COMMAND=("$JOURNEY_BIN_DIR/registry-render" init "$project") ;; + adapter) INIT_COMMAND=("$JOURNEY_BIN_DIR/adapterctl" --format json init "$project") ;; + discovery) INIT_COMMAND=("$JOURNEY_BIN_DIR/discoveryctl" init "$project") ;; + *) journey_harness_failure "no init command is written for product $product" ;; + esac + tool=${INIT_COMMAND[0]##*/} + [[ -x "${INIT_COMMAND[0]}" ]] || journey_usage_error "$tool is not in $JOURNEY_BIN_DIR" +} + +# The plan a reader writes for a product that init gave none for, naming the +# product `rstack dev` is asked to start. It is the smallest plan the format +# allows, so a refusal is about the product and not about the plan's other +# parts. +write_probe_plan() { + local product=$1 project=$2 + journey_write_file "$project/dev.yaml" --concepts development-plan,issuer-name,audience </dev/null; then + journey_harness_failure "the start report of $product holds a scenario that did not pass; see $START_FILE" + fi + journey_pass start + local run=$RUN + url=$(run_url "$product") + recipe "$product" + + # issuer: the issuer the run gave the product, read from the runtime file + # the report names. + local runtime_file + runtime_file=$(jq -er --arg product "$product" '.runtimeConfigs[$product]' "$START_FILE") || + journey_harness_failure "the start report names no runtime file for $product" + journey_step issuer --concepts issuer-url,jwks-uri,audience,allowed-clients,scope-claim \ + --typed "jq .authentication.oidc $runtime_file" -- \ + jq '.authentication.oidc | {issuer, audience, allowedClients, scopeClaim, jwksSource: .jwksSource.type}' "$runtime_file" || + journey_harness_failure "cannot read the issuer of $product from $runtime_file" + journey_pass issuer + + # token: a token for the recipe's person. + issue_token token "$run" "$PERSON" token || status=$? + if [[ $status -ne 0 ]]; then + fail_with_product_code token "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" + stop_live_runs + journey_cell_end + return 0 + fi + journey_pass token + + # call: the first authenticated request. + local -a call_options=(--bearer token) + if [[ -n "$CALL_BODY" ]]; then + printf '%s\n' "$CALL_BODY" | journey_write_file "$work/call-body.json" + call_options+=(--header 'Content-Type: application/json' --header 'Idempotency-Key: journey-first-call' --data-file "$work/call-body.json" --capture '.id' message_id) + fi + journey_http call "${call_options[@]}" "$CALL_METHOD" "$url$CALL_PATH" || status=$? + if [[ $status -ne 0 ]]; then + unexpected_answer call + fi + journey_pass call + + # hook: only BReg declares hooks. A product without any has nothing to + # receive, so the step has no command for it. + if [[ "$product" == breg ]]; then + journey_harness_failure "no hook recipe is written for breg; add one to walk_product in rstack-dev.sh" + fi + journey_pass hook + + # keep: write a record, stop the run, start the same project again and + # read the record back. Only Messaging has a recipe, and it needs the + # message the call created. + if [[ "$product" != messaging || -z "$message_id" ]]; then + journey_harness_failure "no keep recipe is written for $product; add one to walk_product in rstack-dev.sh" + fi + journey_step keep --typed "rstack dev stop $run" -- rstack_dev stop "$run" || + journey_harness_failure "rstack dev stop $run failed during keep; see $JOURNEY_STEP_STDERR" + LIVE_RUNS=$(printf '%s' "$LIVE_RUNS" | grep -vx -- "$run" || true) + journey_poll 30 -- state_is_empty || journey_harness_failure "the state of run $run did not go after its stop" + start_run keep "$project" || + journey_harness_failure "the project did not start a second time; see $JOURNEY_STEP_STDERR" + issue_token keep "$RUN" "$PERSON" token2 || + journey_harness_failure "no token for $PERSON on the second run; see $JOURNEY_STEP_STDERR" + record_url=$(run_url "$product")/v1/messages/$message_id + status=0 + journey_http keep --bearer token2 GET "$record_url" || status=$? + if [[ $status -ne 0 ]]; then + if [[ "$JOURNEY_HTTP_STATUS" == 404 ]]; then + journey_fail keep journey.keep.state-lost + stop_live_runs + journey_cell_end + return 0 + fi + unexpected_answer keep + fi + journey_pass keep + + # attach: the same project against a PostgreSQL server the reader owns. + attach_database "$project" || status=$? + if [[ $status -ne 0 ]]; then + stop_live_runs + journey_cell_end + return 0 + fi + + # stop: rstack's own stop, then nothing left of the run. + local last=$RUN + journey_step stop --typed "rstack dev stop $last" -- rstack_dev stop "$last" || + journey_harness_failure "rstack dev stop $last failed; see $JOURNEY_STEP_STDERR" + LIVE_RUNS=$(printf '%s' "$LIVE_RUNS" | grep -vx -- "$last" || true) + journey_poll 30 -- state_is_empty || journey_harness_failure "the state of run $last did not go after its stop" + journey_check_absent "$(run_containers "$last" | head -n 1)" "$(run_containers "$last" | tail -n 1)" || + journey_harness_failure "a container of run $last remains after its stop" + journey_pass stop + journey_cell_end +} + +# attach_database PROJECT: start PROJECT against a PostgreSQL server the reader +# runs: a stock container with no certificate. `rstack dev` accepts only a TLS +# server, so a reader with a plain one has no way forward that the journeys +# allow. The password reaches the child process through the environment, never +# an argument. The run that was live when this step began is stopped first. +# Records the outcome of step attach; returns 1 when the cell stopped. +attach_database() { + local project=$1 port password_file password status=0 + stop_live_runs || journey_harness_failure "cannot stop the run before attach" + journey_secret_new attach-database-password 24 + journey_secret_path attach-database-password password_file + IFS= read -r password <"$password_file" + journey_container_run owned-database --port 5432 --secret-env POSTGRES_PASSWORD=attach-database-password -- \ + postgres:18.7@sha256:2ea8630df176ad090ec92136dee850397c5af8781e4bcf2e4162593691c61bbc + journey_container_port owned-database 5432 port + # shellcheck disable=SC2016 # the probe expands its own argument + journey_container_wait owned-database 60 -- bash -c ': Date: Fri, 27 Nov 2026 03:14:35 +0100 Subject: [PATCH 015/136] feat: add provision to caseworkctl, coordinatorctl and documentsctl over TLS feat(casework): add caseworkctl provision for roles and the database An operator created Casework's two roles and its database by copying SQL from the operations page. caseworkctl provision now creates them from the runtime file's two URLs through the shared provisioning plan, as a non-superuser administrator, idempotently, or prints the SQL with --print-sql and connects to nothing. apply and its grants are unchanged. feat(coordinator): add coordinatorctl provision for roles and the database An operator created Coordinator's migration and runtime roles and its database by hand from the operations page. coordinatorctl provision now creates them from the runtime file's two URLs through the shared provisioning plan, as a non-superuser administrator, idempotently, or prints the SQL with --print-sql. apply still creates the namespace schema and its grants. The dependency-direction gate accepts registry-cli-report beside registry-cli-api: the shared provisioning command reports through it, and it reaches no product. feat(documents): add documentsctl provision for roles and the database An operator created the Document Store roles and database by hand from the operations page. documentsctl provision now creates them from the runtime file's two URLs through the shared provisioning plan, as a non-superuser administrator, idempotently, or prints the SQL with --print-sql. documentsctl keeps its own global --format and passes it to the shared command. test(platform): run every product provision test over one verified-TLS session provision connects only over verified TLS, so its product tests need a TLS server, and their own setup sessions must use TLS too to run against a TLS-only one. A test-support feature in registry-platform-provision gives them the two PROVISION_TEST_DATABASE_* variables and a superuser session built from the crate's own administrator URL rules. Casework, Coordinator and Documents use it in place of their own connections. Signed-off-by: Jeremi Joslin --- Cargo.lock | 5 + crates/registry-caseworkctl/Cargo.toml | 3 + crates/registry-caseworkctl/src/lib.rs | 8 + crates/registry-caseworkctl/src/provision.rs | 129 ++++++ .../registry-caseworkctl/tests/provision.rs | 428 ++++++++++++++++++ crates/registry-coordinator/Cargo.toml | 2 + crates/registry-coordinator/src/cli.rs | 28 +- crates/registry-coordinator/src/lib.rs | 1 + crates/registry-coordinator/src/provision.rs | 139 ++++++ .../tests/provision_cli.rs | 112 +++++ .../tests/provision_postgres.rs | 325 +++++++++++++ crates/registry-documentsctl/Cargo.toml | 8 + crates/registry-documentsctl/src/lib.rs | 22 + crates/registry-documentsctl/src/provision.rs | 104 +++++ .../tests/provision_cli.rs | 200 ++++++++ .../tests/provision_postgres.rs | 300 ++++++++++++ crates/registry-platform-provision/Cargo.toml | 4 + crates/registry-platform-provision/README.md | 5 + .../registry-platform-provision/src/admin.rs | 19 + crates/registry-platform-provision/src/lib.rs | 3 + .../src/test_support.rs | 35 ++ .../src/content/docs/operate/casework.mdx | 47 +- .../src/content/docs/operate/coordinator.mdx | 31 +- .../src/content/docs/operate/documents.mdx | 62 ++- products/casework/AGENTS.md | 5 +- products/coordinator/AGENTS.md | 5 + .../scripts/check_dependency_direction.py | 7 +- .../scripts/test_dependency_direction.py | 10 + products/documents/AGENTS.md | 4 + products/platform/CHANGELOG.md | 4 + 30 files changed, 2005 insertions(+), 50 deletions(-) create mode 100644 crates/registry-caseworkctl/src/provision.rs create mode 100644 crates/registry-caseworkctl/tests/provision.rs create mode 100644 crates/registry-coordinator/src/provision.rs create mode 100644 crates/registry-coordinator/tests/provision_cli.rs create mode 100644 crates/registry-coordinator/tests/provision_postgres.rs create mode 100644 crates/registry-documentsctl/src/provision.rs create mode 100644 crates/registry-documentsctl/tests/provision_cli.rs create mode 100644 crates/registry-documentsctl/tests/provision_postgres.rs create mode 100644 crates/registry-platform-provision/src/test_support.rs diff --git a/Cargo.lock b/Cargo.lock index 7c55207561..34113156ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6618,6 +6618,7 @@ dependencies = [ "registry-cli-report", "registry-platform-buildinfo", "registry-platform-config", + "registry-platform-provision", "registry-platform-yaml", "registry-rstack-dev", "registry-thunderid-tooling", @@ -6629,6 +6630,7 @@ dependencies = [ "tokio", "tokio-postgres", "uuid", + "zeroize", ] [[package]] @@ -6739,6 +6741,7 @@ dependencies = [ "registry-platform-httputil", "registry-platform-metrics", "registry-platform-oidc", + "registry-platform-provision", "registry-platform-script", "registry-platform-testing", "registry-platform-yaml", @@ -7039,6 +7042,7 @@ dependencies = [ "registry-documents-core", "registry-platform-buildinfo", "registry-platform-config", + "registry-platform-provision", "registry-platform-yaml", "serde", "serde_json", @@ -7046,6 +7050,7 @@ dependencies = [ "tokio", "tokio-postgres", "uuid", + "zeroize", ] [[package]] diff --git a/crates/registry-caseworkctl/Cargo.toml b/crates/registry-caseworkctl/Cargo.toml index 70aa878dcf..9208d10618 100644 --- a/crates/registry-caseworkctl/Cargo.toml +++ b/crates/registry-caseworkctl/Cargo.toml @@ -33,6 +33,7 @@ clap.workspace = true jsonschema.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-cli-api.workspace = true @@ -47,7 +48,9 @@ serde_norway.workspace = true tempfile.workspace = true tokio = { workspace = true, features = ["rt"] } uuid = { workspace = true, features = ["serde"] } +zeroize.workspace = true [dev-dependencies] registry-breg.workspace = true +registry-platform-provision = { workspace = true, features = ["test-support"] } tokio-postgres.workspace = true diff --git a/crates/registry-caseworkctl/src/lib.rs b/crates/registry-caseworkctl/src/lib.rs index 5d60f3eee6..9c8b7b8605 100644 --- a/crates/registry-caseworkctl/src/lib.rs +++ b/crates/registry-caseworkctl/src/lib.rs @@ -6,6 +6,7 @@ mod project; mod project_types; mod provider_add; mod provider_pair; +mod provision; mod report; #[cfg(feature = "schema")] pub mod schema; @@ -110,6 +111,8 @@ enum Command { #[arg(long)] backup_reference: Vec, }, + /// Create the migration and runtime roles and the database named by the runtime file. + Provision(registry_platform_provision::ProvisionArgs), /// Call the Casework HTTP API with a saved connection or an explicit URL. Api(Box), /// Manage saved Casework API connections. @@ -314,6 +317,9 @@ pub fn main_entry_from( let Cli { format, command } = cli; let command = match command { Command::Serve(args) => return serve(args, format, format_supplied, stdout, stderr), + Command::Provision(args) => { + return provision::run(args, matches!(format, OutputFormat::Json)); + } Command::Api(args) => return api(*args, format_supplied, stderr), Command::Connection { command } => { return connection(command, format, format_supplied, stderr); @@ -573,6 +579,7 @@ impl Command { Self::Plan(_) => "plan", Self::Status(_) => "status", Self::Apply { .. } => "apply", + Self::Provision(_) => "provision", Self::Api(_) => "api", Self::Connection { .. } => "connection", Self::RstackDev(_) => "rstack-dev", @@ -693,6 +700,7 @@ fn run(command: Command) -> Result { operator_reference, backup_reference, } => project::apply(&runtime_config, operator_reference, backup_reference), + Command::Provision(_) => unreachable!("provision writes its own report"), Command::Api(_) | Command::Connection { .. } => { unreachable!("raw API commands bypass report dispatch") } diff --git a/crates/registry-caseworkctl/src/provision.rs b/crates/registry-caseworkctl/src/provision.rs new file mode 100644 index 0000000000..c865bc129e --- /dev/null +++ b/crates/registry-caseworkctl/src/provision.rs @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `caseworkctl provision`: creates the migration and runtime roles and the +//! database from the two URLs in the runtime file, so each credential is +//! written once. The shared command owns the flags, the plan and the report. + +use std::path::Path; +use std::process::ExitCode; + +use registry_casework::{secret_resolver, RuntimeConfig}; +use registry_platform_config::{describe_secret_failure, SecretResolver}; +use registry_platform_provision::cli::OutputFormat; +use registry_platform_provision::{ + run_provision, ProductDatabase, ProvisionArgs, ProvisionInput, SchemaLayout, +}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +const SECRET_ACTION: &str = + "Provision a runtime-readable secret through the configured provider and retry provision."; + +/// Runs the command with this tool's global `--format`. +pub(crate) fn run(args: ProvisionArgs, json: bool) -> ExitCode { + let format = if json { + OutputFormat::Json + } else { + OutputFormat::Human + }; + run_provision( + "caseworkctl", + registry_platform_buildinfo::DISPLAY_VERSION, + &args, + format, + load, + ) +} + +fn load(path: &Path) -> Result> { + let config = RuntimeConfig::load(path).map_err(|error| { + Box::new(Diagnostic::error( + error.code(), + format!("runtime.yaml:{}", error.pointer()), + "The runtime configuration was refused.", + error.suggested_action(), + )) + })?; + let secrets = secret_resolver(&config).map_err(|_| { + Box::new(Diagnostic::error( + "casework.runtime.secret-unavailable", + "runtime.yaml:/secretProviders", + "The secret provider configuration is invalid.", + SECRET_ACTION, + )) + })?; + let database = &config.database; + let migration_url = text_secret( + &secrets, + "database.migrationUrlRef", + "/database/migrationUrlRef", + &database.migration_url_ref, + )?; + let runtime_url = text_secret( + &secrets, + "database.runtimeUrlRef", + "/database/runtimeUrlRef", + &database.runtime_url_ref, + )?; + let ca_pem = database + .ca_bundle_ref + .as_deref() + .map(|reference| { + secrets + .resolve(reference) + .map(|secret| secret.expose_secret().to_vec()) + .map_err(|error| { + secret_diagnostic( + "database.caBundleRef", + "/database/caBundleRef", + reference, + &error, + ) + }) + }) + .transpose()?; + Ok(ProvisionInput { + product: ProductDatabase { + product: "casework", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + }, + migration_url, + runtime_url, + ca_pem, + }) +} + +fn text_secret( + secrets: &SecretResolver, + field: &str, + pointer: &str, + reference: &str, +) -> Result, Box> { + let secret = secrets + .resolve(reference) + .map_err(|error| secret_diagnostic(field, pointer, reference, &error))?; + let text = std::str::from_utf8(secret.expose_secret()).map_err(|_| { + Box::new(Diagnostic::error( + "casework.runtime.secret-unavailable", + format!("runtime.yaml:{pointer}"), + format!("{field}: the secret value must be non-empty text"), + SECRET_ACTION, + )) + })?; + Ok(Zeroizing::new(text.to_owned())) +} + +fn secret_diagnostic( + field: &str, + pointer: &str, + reference: &str, + error: ®istry_platform_config::SecretError, +) -> Box { + Box::new(Diagnostic::error( + "casework.runtime.secret-unavailable", + format!("runtime.yaml:{pointer}"), + describe_secret_failure(field, reference, error), + SECRET_ACTION, + )) +} diff --git a/crates/registry-caseworkctl/tests/provision.rs b/crates/registry-caseworkctl/tests/provision.rs new file mode 100644 index 0000000000..f539fed0e2 --- /dev/null +++ b/crates/registry-caseworkctl/tests/provision.rs @@ -0,0 +1,428 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `caseworkctl provision`: print mode, usage refusals, and, with a disposable +//! server, provisioning as a non-superuser owner then apply then serve. + +#![cfg(unix)] +#![allow( + clippy::disallowed_methods, + reason = "tests write only their own synthetic project and secrets" +)] + +use serde_json::{json, Value}; +use std::{ + fs, + os::unix::fs::PermissionsExt, + path::{Path, PathBuf}, + process::{Command, Output}, +}; + +const MIGRATION_PASSWORD: &str = "migration-password-canary-0123456789"; +const RUNTIME_PASSWORD: &str = "runtime-password-canary-0123456789"; + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_caseworkctl")) + .args(arguments) + .env_remove("RSTACK_GENERATION_DIR") + .output() + .expect("caseworkctl starts") +} + +fn ctl_ok(arguments: &[&str]) -> Value { + let output = ctl(&[&["--format", "json"], arguments].concat()); + assert!( + output.status.success(), + "caseworkctl {arguments:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("a typed JSON report") +} + +fn secret(path: &Path, value: &str) { + fs::write(path, value).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap(); +} + +/// One synthetic deployment: an authored project, its package, a secret root +/// and a runtime file whose two database URLs name the given roles. +struct Deployment { + _root: tempfile::TempDir, + #[cfg_attr(not(feature = "postgres-test"), allow(dead_code))] + root: PathBuf, + runtime: PathBuf, +} + +struct DatabaseUrls<'a> { + migration: &'a str, + runtime: &'a str, + ca_pem: Option<&'a Path>, + plaintext: bool, + bind: &'a str, +} + +fn deployment(urls: &DatabaseUrls<'_>) -> Deployment { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().canonicalize().unwrap(); + let project = root.join("project"); + ctl_ok(&[ + "init", + project.to_str().unwrap(), + "--template", + "standalone-decision", + ]); + let package = root.join("package"); + ctl_ok(&[ + "package", + project.to_str().unwrap(), + "--output", + package.to_str().unwrap(), + ]); + let secrets = root.join("secrets"); + fs::create_dir(&secrets).unwrap(); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).unwrap(); + secret(&secrets.join("migration-url"), urls.migration); + secret(&secrets.join("runtime-url"), urls.runtime); + secret( + &secrets.join("audit-key"), + "provision-test-audit-key-canary-0123456789", + ); + // The issuer's public key is read from a secret, so serving needs no network. + secret( + &secrets.join("jwks"), + r#"{"keys":[{"kty":"EC","crv":"P-256","use":"sig","alg":"ES256","kid":"provision-test","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}]}"#, + ); + let mut database = json!({ + "runtimeUrlRef":"secret:file/runtime-url", + "migrationUrlRef":"secret:file/migration-url", + }); + if let Some(ca) = urls.ca_pem { + secret(&secrets.join("ca"), &fs::read_to_string(ca).unwrap()); + database["caBundleRef"] = json!("secret:file/ca"); + } + if urls.plaintext { + database["testOnlyPlaintext"] = json!(true); + } + let config = json!({ + "apiVersion":registry_casework::RUNTIME_CONFIG_API_VERSION,"kind":registry_casework::RUNTIME_CONFIG_KIND, + "identity":{"databaseId":"provision-test"},"package":{"root":package}, + "listener":{"bind":urls.bind,"tlsTermination":"development-loopback","networkExposure":"private-address"}, + "secretProviders":{"file":{"root":secrets}}, + "database":database, + "authentication":{"oidc":{"issuer":"https://identity.example.test","audience":"urn:example:casework", + "jwksSource":{"type":"static","documentRef":"secret:file/jwks"}, + "allowedClients":"unrestricted","scopeClaim":"scope","humanIdentity":{"claim":"registry_actor_kind","value":"human"}}}, + "audit":{"path":root.join("audit.ndjson"),"hashKeyRef":"secret:file/audit-key"} + }); + let runtime = root.join("runtime.yaml"); + fs::write(&runtime, serde_norway::to_string(&config).unwrap()).unwrap(); + Deployment { + _root: temporary, + root, + runtime, + } +} + +fn offline_urls() -> (String, String) { + ( + format!("postgresql://cw_migration:{MIGRATION_PASSWORD}@db.example.test:5432/casework_db"), + format!("postgresql://cw_runtime:{RUNTIME_PASSWORD}@db.example.test:5432/casework_db"), + ) +} + +#[test] +fn print_sql_connects_to_nothing_and_prints_no_password() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + let output = ctl(&[ + "provision", + "--runtime-config", + deployment.runtime.to_str().unwrap(), + "--print-sql", + ]); + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let script = String::from_utf8(output.stdout).unwrap(); + for expected in ["cw_migration", "cw_runtime", "casework_db", "CREATE ROLE"] { + assert!(script.contains(expected), "script lacks {expected}"); + } + for private in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + "db.example.test", + "postgresql://", + ] { + assert!(!script.contains(private), "script leaks {private}"); + } + assert!(!String::from_utf8_lossy(&output.stderr).contains(MIGRATION_PASSWORD)); +} + +#[test] +fn print_sql_with_a_global_json_format_reports_without_executing() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + deployment.runtime.to_str().unwrap(), + "--print-sql", + ]); + assert_eq!(output.status.code(), Some(0)); + let text = String::from_utf8(output.stdout).unwrap(); + let report: Value = serde_json::from_str(&text).expect("a JSON report on stdout"); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "casework"); + assert_eq!(report["executed"], false); + assert_eq!(report["migrationRole"], "cw_migration"); + assert_eq!(report["runtimeRole"], "cw_runtime"); + assert!(!text.contains(MIGRATION_PASSWORD) && !text.contains(RUNTIME_PASSWORD)); +} + +#[test] +fn both_administrator_flags_are_a_usage_error() { + let output = ctl(&[ + "provision", + "--runtime-config", + "/nonexistent/runtime.yaml", + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "UNUSED_ADMIN_URL", + ]); + assert_eq!(output.status.code(), Some(2)); + let output = ctl(&[ + "provision", + "--runtime-config", + "/nonexistent/runtime.yaml", + "--print-sql", + "--admin-url-env", + "UNUSED_ADMIN_URL", + ]); + assert_eq!(output.status.code(), Some(2)); + let output = ctl(&["provision", "--runtime-config", "/nonexistent/runtime.yaml"]); + assert_eq!( + output.status.code(), + Some(2), + "an administrator flag is required unless --print-sql is given" + ); +} + +#[cfg(feature = "postgres-test")] +mod served { + use super::*; + use registry_platform_provision::test_support::{connect_verified, provision_test_env}; + use std::io::{Read as _, Write as _}; + use uuid::Uuid; + + fn required(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("the postgres-test feature needs {name}")) + } + + fn hex(length: usize) -> String { + Uuid::new_v4().simple().to_string()[..length].to_owned() + } + + /// Drops the database and roles a test created, even after a failure. + struct Cleanup { + superuser_url: String, + ca_pem: Vec, + database: String, + roles: Vec, + } + + impl Drop for Cleanup { + fn drop(&mut self) { + let (url, ca_pem, database, roles) = ( + self.superuser_url.clone(), + self.ca_pem.clone(), + self.database.clone(), + self.roles.clone(), + ); + std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async { + let client = connect_verified(&url, &ca_pem, None).await; + client + .batch_execute(&format!( + "DROP DATABASE IF EXISTS \"{database}\" WITH (FORCE)" + )) + .await + .expect("drop database"); + for role in roles { + client + .batch_execute(&format!("DROP ROLE IF EXISTS \"{role}\"")) + .await + .expect("drop role"); + } + }); + }) + .join() + .expect("cleanup thread"); + } + } + + fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() + } + + fn get_status(address: &str, path: &str) -> std::io::Result { + let mut stream = std::net::TcpStream::connect(address)?; + stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?; + write!( + stream, + "GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n" + )?; + let mut response = String::new(); + stream.read_to_string(&mut response)?; + Ok(response.lines().next().unwrap_or_default().to_owned()) + } + + #[tokio::test(flavor = "multi_thread")] + async fn provision_then_apply_then_serve_with_split_roles() { + let (superuser_url, ca_pem) = provision_test_env(); + let ca_path = PathBuf::from(required("PROVISION_TEST_DATABASE_CA")); + let server = registry_platform_provision::admin_config(&superuser_url, Some(&ca_pem)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, port) = (server.host().to_owned(), server.port()); + + let suffix = hex(12); + let (owner, migration, runtime, database) = ( + format!("cw_owner_{suffix}"), + format!("cw_mig_{suffix}"), + format!("cw_run_{suffix}"), + format!("cw_db_{suffix}"), + ); + let owner_password = hex(24); + let _cleanup = Cleanup { + superuser_url: superuser_url.clone(), + ca_pem: ca_pem.clone(), + database: database.clone(), + roles: vec![runtime.clone(), migration.clone(), owner.clone()], + }; + let admin = connect_verified(&superuser_url, &ca_pem, None).await; + admin + .batch_execute(&format!( + "CREATE ROLE \"{owner}\" LOGIN CREATEROLE CREATEDB NOSUPERUSER PASSWORD '{owner_password}'" + )) + .await + .unwrap(); + + let bind = format!("127.0.0.1:{}", free_port()); + let endpoint = format!("{host}:{port}/{database}"); + let migration_url = format!("postgresql://{migration}:{MIGRATION_PASSWORD}@{endpoint}"); + let runtime_url = format!("postgresql://{runtime}:{RUNTIME_PASSWORD}@{endpoint}"); + let deployment = deployment(&DatabaseUrls { + migration: &migration_url, + runtime: &runtime_url, + ca_pem: Some(&ca_path), + plaintext: false, + bind: &bind, + }); + let admin_file = deployment.root.join("admin-url"); + secret( + &admin_file, + &format!( + "postgresql://{owner}:{owner_password}@{host}:{port}/postgres?sslmode=verify-full" + ), + ); + let runtime_file = deployment.runtime.to_str().unwrap(); + + let provisioned = Command::new(env!("CARGO_BIN_EXE_caseworkctl")) + .args(["--format", "json", "provision", "--runtime-config"]) + .arg(runtime_file) + .arg("--admin-url-file") + .arg(&admin_file) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&provisioned.stdout).into_owned(); + assert_eq!( + provisioned.status.code(), + Some(0), + "provision refused: {text} {}", + String::from_utf8_lossy(&provisioned.stderr) + ); + let report: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(report["status"], "complete"); + assert_eq!(report["roleMode"], "split"); + for private in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + owner_password.as_str(), + ] { + assert!(!text.contains(private), "the report leaks a password"); + } + + let applied = ctl_ok(&["apply", "--runtime-config", runtime_file]); + assert_eq!(applied["ok"], true, "{applied}"); + let status = ctl_ok(&["status", "--runtime-config", runtime_file]); + assert_eq!(status["ok"], true, "{status}"); + + // A second provision finds everything present and creates nothing. + let again = ctl_ok(&[ + "provision", + "--runtime-config", + runtime_file, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(again["status"], "complete"); + assert!( + again["statements"] + .as_array() + .unwrap() + .iter() + .all(|statement| statement["outcome"] != "created"), + "{again}" + ); + + let server_task = tokio::spawn({ + let runtime = deployment.runtime.clone(); + async move { registry_casework::serve_from_path(runtime).await } + }); + let mut answer = String::new(); + for _ in 0..100 { + assert!( + !server_task.is_finished(), + "the runtime stopped: {:?}", + server_task.await + ); + let probe_address = bind.clone(); + answer = tokio::task::spawn_blocking(move || get_status(&probe_address, "/ready")) + .await + .unwrap() + .unwrap_or_default(); + if answer.contains("200") { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } + server_task.abort(); + assert!( + answer.contains("200"), + "the runtime role serves /ready after provision and apply: {answer:?}" + ); + } +} diff --git a/crates/registry-coordinator/Cargo.toml b/crates/registry-coordinator/Cargo.toml index e65479cc8a..35037fb3d7 100644 --- a/crates/registry-coordinator/Cargo.toml +++ b/crates/registry-coordinator/Cargo.toml @@ -146,6 +146,7 @@ registry-payment-client.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true registry-platform-oidc.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-authcommon.workspace = true registry-platform-buildinfo.workspace = true registry-platform-calendar.workspace = true @@ -185,6 +186,7 @@ zeroize.workspace = true [dev-dependencies] tokio = { workspace = true, features = ["test-util"] } +registry-platform-provision = { workspace = true, features = ["test-support"] } registry-platform-testing = { workspace = true, features = ["test-utils", "test-authorization-server", "migration-pins", "token-fixtures"] } tempfile.workspace = true tower.workspace = true diff --git a/crates/registry-coordinator/src/cli.rs b/crates/registry-coordinator/src/cli.rs index 9cd9351217..3526a4d134 100644 --- a/crates/registry-coordinator/src/cli.rs +++ b/crates/registry-coordinator/src/cli.rs @@ -192,6 +192,8 @@ enum Command { /// Active workflow to retire because its package is no longer listed; repeat for each workflow. remove_workflow: Vec, }, + /// Create the database, the migration and runtime roles, and the grants `apply` expects, as a PostgreSQL administrator. + Provision(registry_platform_provision::cli::ProvisionArgs), /// Apply every listed workflow's package and least-privileged runtime grants using migration credentials. Apply { #[arg(long = "remove-workflow", value_name = "WORKFLOW")] @@ -380,6 +382,7 @@ impl Command { Self::Test { .. } => "test", Self::Package { .. } => "package", Self::Plan { .. } => "plan", + Self::Provision(_) => "provision", Self::Apply { .. } => "apply", Self::DeploymentStatus => "deployment-status", Self::Openapi => "openapi", @@ -587,12 +590,15 @@ fn runtime(cli: &Cli) -> Result { .suggest("Add --runtime-config with the deployment's runtime.yaml.") })?) } -/// `--runtime-config` made absolute against the working directory, with `.` -/// and `..` resolved by name, as the runtime loader requires. fn runtime_config(cli: &Cli) -> Result> { - let Some(path) = cli.runtime_config.as_deref() else { - return Ok(None); - }; + cli.runtime_config + .as_deref() + .map(absolute_runtime_path) + .transpose() +} +/// A `--runtime-config` path made absolute against the working directory, with +/// `.` and `..` resolved by name, as the runtime loader requires. +pub(crate) fn absolute_runtime_path(path: &Path) -> Result { let absolute = std::path::absolute(path).map_err(|_| { CoordinatorError::new( "runtime-config-unresolved", @@ -610,7 +616,7 @@ fn runtime_config(cli: &Cli) -> Result> { other => normal.push(other), } } - Ok(Some(normal)) + Ok(normal) } async fn remote( service: &Service, @@ -818,6 +824,9 @@ async fn execute(cli: &Cli) -> Result { Command::Serve { .. } => { unreachable!("serve replaces the ctl process before report dispatch") } + Command::Provision(_) => { + unreachable!("provision writes its own report before report dispatch") + } Command::Init { directory, id } => { let created = project::init(directory, id.as_deref())?; Ok(json!({"status":"initialized","project":directory,"created":created})) @@ -1168,6 +1177,13 @@ pub async fn run() -> std::process::ExitCode { if let Command::Serve { coordinator_bin } = &cli.command { return serve(&cli, coordinator_bin.as_deref(), format_requested); } + if let Command::Provision(args) = &cli.command { + let format = match cli.format { + Format::Human => registry_platform_provision::cli::OutputFormat::Human, + Format::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + return crate::provision::run(args.clone(), format).await; + } let cli = match cli { Cli { command: Command::Api(args), diff --git a/crates/registry-coordinator/src/lib.rs b/crates/registry-coordinator/src/lib.rs index 45fe4e3802..c71da85b3c 100644 --- a/crates/registry-coordinator/src/lib.rs +++ b/crates/registry-coordinator/src/lib.rs @@ -22,6 +22,7 @@ pub mod problem; pub mod project; mod project_check; pub mod protocol; +mod provision; mod read_in_force; mod record_read; mod review; diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs new file mode 100644 index 0000000000..916cfe8023 --- /dev/null +++ b/crates/registry-coordinator/src/provision.rs @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `coordinatorctl provision`: the database, roles and grants `apply` expects. +//! +//! The shared runner reads the role names, database and passwords from the +//! two URLs this module resolves out of the runtime file, so nothing is +//! written twice. `apply` creates the schema the runtime file's `namespace` +//! names, so provisioning gives the migration role `CREATE` on the database +//! and the runtime role `CONNECT`, and leaves every other grant to `apply`. + +use std::path::Path; +use std::process::ExitCode; + +use registry_platform_config::SecretResolver; +use registry_platform_provision::cli::{ + run_provision, OutputFormat, ProvisionArgs, ProvisionInput, +}; +use registry_platform_provision::{ProductDatabase, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +use crate::runtime::RuntimeConfig; + +/// The diagnostic code the runtime file's own refusals carry. +const RUNTIME_CONFIG_REFUSED: &str = "coordinator.runtime-config.refused"; + +/// Runs the verb. The shared runner owns a runtime of its own, so it runs off +/// the service's executor threads. +pub(crate) async fn run(args: ProvisionArgs, format: OutputFormat) -> ExitCode { + match tokio::task::spawn_blocking(move || { + run_provision( + "coordinatorctl", + registry_platform_buildinfo::DISPLAY_VERSION, + &args, + format, + load, + ) + }) + .await + { + Ok(exit) => exit, + Err(_) => { + eprintln!("coordinatorctl provision stopped unexpectedly"); + ExitCode::from(3) + } + } +} + +fn load(path: &Path) -> Result> { + let path = crate::cli::absolute_runtime_path(path).map_err(|error| first_diagnostic(&error))?; + let runtime = RuntimeConfig::load(&path).map_err(|error| first_diagnostic(&error))?; + let resolver = runtime.secret_providers.resolver().map_err(|_| { + refusal( + "/secretProviders", + "the secret providers could not be set up", + "Correct the secretProviders block of the runtime file.", + ) + })?; + let database = &runtime.database; + let migration_url = secret_text( + &resolver, + &database.migration_url_ref, + "/database/migrationUrlRef", + )?; + let runtime_url = secret_text( + &resolver, + &database.runtime_url_ref, + "/database/runtimeUrlRef", + )?; + let ca_pem = match &database.ca_bundle_ref { + Some(reference) => Some( + secret_text(&resolver, reference, "/database/caBundleRef")? + .as_bytes() + .to_vec(), + ), + None => None, + }; + Ok(ProvisionInput { + product: ProductDatabase { + product: "coordinator", + layout: SchemaLayout::CreatedByApply, + btree_gist: false, + spatial: None, + }, + migration_url, + runtime_url, + ca_pem, + }) +} + +fn secret_text( + resolver: &SecretResolver, + reference: &str, + pointer: &str, +) -> Result, Box> { + let secret = resolver.resolve(reference).map_err(|_| { + refusal( + pointer, + "the referenced secret could not be read", + "Make the secret the runtime file names available to this command.", + ) + })?; + let text = std::str::from_utf8(secret.expose_secret()).map_err(|_| { + refusal( + pointer, + "the referenced secret is not UTF-8 text", + "Supply a UTF-8 PostgreSQL URL or PEM file.", + ) + })?; + Ok(Zeroizing::new(text.to_owned())) +} + +fn refusal(pointer: &str, message: &str, action: &str) -> Box { + Box::new(Diagnostic::error( + RUNTIME_CONFIG_REFUSED, + pointer, + message, + action, + )) +} + +/// The decisive finding of a runtime-file refusal. +fn first_diagnostic(error: &crate::error::CoordinatorError) -> Box { + let report = error.report(); + let diagnostics = report.diagnostics(); + Box::new( + diagnostics + .iter() + .find(|diagnostic| diagnostic.severity == registry_platform_yaml::Severity::Error) + .or_else(|| diagnostics.first()) + .cloned() + .unwrap_or_else(|| { + *refusal( + "", + "the runtime file was refused", + "Correct the runtime file.", + ) + }), + ) +} diff --git a/crates/registry-coordinator/tests/provision_cli.rs b/crates/registry-coordinator/tests/provision_cli.rs new file mode 100644 index 0000000000..bb05e9bfbf --- /dev/null +++ b/crates/registry-coordinator/tests/provision_cli.rs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `coordinatorctl provision` without a server: the printed plan and the +//! usage refusals. +use std::{fs, os::unix::fs::PermissionsExt, path::Path, process::Command}; + +const RUNTIME: &str = + include_str!("../../../products/coordinator/examples/single-flow-runtime.yaml"); +const MIGRATION_PASSWORD: &str = "migration-password-canary"; +const RUNTIME_PASSWORD: &str = "runtime-password-canary"; + +/// A runtime file the loader accepts, whose database references resolve from +/// the environment the command is given. +fn runtime_file(directory: &Path) -> std::path::PathBuf { + let root = directory.canonicalize().unwrap(); + let secrets = root.join("secrets"); + fs::create_dir(&secrets).unwrap(); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).unwrap(); + let root_pem = secrets.join("postgres-root.pem"); + fs::write(&root_pem, "unused in print mode").unwrap(); + fs::set_permissions(&root_pem, fs::Permissions::from_mode(0o600)).unwrap(); + let path = root.join("runtime.yaml"); + fs::write( + &path, + RUNTIME.replace( + "/run/registry-coordinator/secrets", + secrets.to_str().unwrap(), + ), + ) + .unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + path +} + +fn provision(runtime: &Path, extra: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .arg("provision") + .arg("--runtime-config") + .arg(runtime) + .args(extra) + .env( + "COORDINATOR_MIGRATION_URL", + format!("postgres://coordinator_migration:{MIGRATION_PASSWORD}@db.example.org:5432/coordinator"), + ) + .env( + "COORDINATOR_DATABASE_URL", + format!("postgres://coordinator_runtime:{RUNTIME_PASSWORD}@db.example.org:5432/coordinator"), + ) + .output() + .unwrap() +} + +#[test] +fn print_sql_prints_the_plan_without_a_connection_or_a_password() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision(&runtime, &["--print-sql"]); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stdout}{stderr}"); + assert!( + stdout.contains("CREATE ROLE \"coordinator_migration\""), + "{stdout}" + ); + assert!( + stdout.contains("CREATE ROLE \"coordinator_runtime\""), + "{stdout}" + ); + assert!( + stdout.contains("GRANT CREATE ON DATABASE \"coordinator\" TO \"coordinator_migration\""), + "the migration role creates the namespace schema: {stdout}" + ); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD, "postgres://"] { + assert!(!stdout.contains(secret), "the script leaked a secret"); + assert!(!stderr.contains(secret), "stderr leaked a secret"); + } +} + +#[test] +fn both_administrator_sources_are_a_usage_error() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision( + &runtime, + &[ + "--admin-url-file", + "/nonexistent/admin.url", + "--admin-url-env", + "ADMIN_URL", + ], + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{stderr}"); + assert!(output.stdout.is_empty()); + assert!( + stderr.contains("--admin-url"), + "the refusal names the flags: {stderr}" + ); +} + +#[test] +fn an_administrator_source_is_required_unless_printing() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision(&runtime, &[]); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{stderr}"); + assert!( + stderr.contains("--admin-url"), + "the refusal names the flags: {stderr}" + ); +} diff --git a/crates/registry-coordinator/tests/provision_postgres.rs b/crates/registry-coordinator/tests/provision_postgres.rs new file mode 100644 index 0000000000..f4c4073e0f --- /dev/null +++ b/crates/registry-coordinator/tests/provision_postgres.rs @@ -0,0 +1,325 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `coordinatorctl provision` against a real server, then `apply` and the +//! service on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable superuser URL +//! with `sslmode=verify-full` and `PROVISION_TEST_DATABASE_CA` the +//! PEM file the server certificate chains to: provisioning always uses +//! verified TLS, so the suite's plaintext database cannot serve it. +#![cfg(feature = "postgres-test")] +use chrono::Utc; +use registry_coordinator::{ + adapters::HttpAdapters, + deployment, + http::{self, HttpState}, + project, + runtime::RuntimeConfig, +}; +use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use registry_platform_testing::{TestAuthorizationServer, TestClient}; +use serde_json::{json, Value}; +use std::{fs, path::Path, process::Command, sync::Arc}; +use uuid::Uuid; + +const DELAYED: &str = "delayed-follow-up"; +const ADMIN_URL_VARIABLE: &str = "COORDINATOR_PROVISION_ADMIN_URL"; + +fn private(path: &Path, bytes: &[u8]) { + use std::os::unix::fs::PermissionsExt; + fs::write(path, bytes).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap(); +} + +fn yaml_value(text: &str, api_version: &str, kind: &str) -> Value { + use registry_platform_yaml::{ApiVersion, EnvelopeRule, Expect, FormatSpec, Reader}; + let versions = [ApiVersion::current(api_version)]; + let format = FormatSpec { + kind, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &versions, + retired_api_versions: &[], + }, + removed_keys: &[], + }; + Reader::new("fixture.yaml") + .read(text.as_bytes(), &Expect::one(&format)) + .unwrap() + .to_json_value() +} + +fn ctl(runtime: &Path, args: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .args(["--format", "json", "--runtime-config"]) + .arg(runtime) + .args(args) + .output() + .unwrap() +} + +fn provision(runtime: &Path, admin_url: &str) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .args(["--format", "json", "provision", "--runtime-config"]) + .arg(runtime) + .args(["--admin-url-env", ADMIN_URL_VARIABLE]) + .env(ADMIN_URL_VARIABLE, admin_url) + .output() + .unwrap() +} + +struct Names { + migration: String, + runtime: String, + owner: String, + database: String, + namespace: String, +} + +async fn drop_everything(admin: &tokio_postgres::Client, names: &Names) { + for statement in [ + format!("DROP DATABASE IF EXISTS {} WITH (FORCE)", names.database), + format!("DROP ROLE IF EXISTS {}", names.runtime), + format!("DROP ROLE IF EXISTS {}", names.migration), + format!("DROP ROLE IF EXISTS {}", names.owner), + ] { + admin.batch_execute(&statement).await.unwrap(); + } +} + +/// The administrator is a role that can only create roles and databases, the +/// way a managed server's admin is, never the server's superuser. +#[tokio::test] +async fn provision_then_apply_then_serve_with_a_namespace_schema() { + let (superuser_url, ca_pem) = provision_test_env(); + let superuser = connect_verified(&superuser_url, &ca_pem, None).await; + let suffix = Uuid::new_v4().simple().to_string()[..12].to_owned(); + let names = Names { + migration: format!("coord_mig_{suffix}"), + runtime: format!("coord_run_{suffix}"), + owner: format!("coord_own_{suffix}"), + database: format!("coord_db_{suffix}"), + namespace: format!("coordinator_{suffix}"), + }; + let owner_password = Uuid::new_v4().simple().to_string(); + superuser + .batch_execute(&format!( + "CREATE ROLE {} LOGIN CREATEROLE CREATEDB NOSUPERUSER PASSWORD '{owner_password}'", + names.owner + )) + .await + .unwrap(); + let outcome = tokio::spawn(run( + superuser_url.clone(), + ca_pem.clone(), + owner_password, + Names { + migration: names.migration.clone(), + runtime: names.runtime.clone(), + owner: names.owner.clone(), + database: names.database.clone(), + namespace: names.namespace.clone(), + }, + )) + .await; + drop_everything(&superuser, &names).await; + outcome.unwrap(); +} + +async fn run(superuser_url: String, ca_pem: Vec, owner_password: String, names: Names) { + let mut endpoint = url::Url::parse(&superuser_url).unwrap(); + let (host, port) = ( + endpoint.host_str().unwrap().to_owned(), + endpoint.port().unwrap(), + ); + endpoint.set_username(&names.owner).unwrap(); + endpoint.set_password(Some(&owner_password)).unwrap(); + let admin_url = endpoint.to_string(); + + let root = tempfile::tempdir().unwrap(); + let root_path = root.path().canonicalize().unwrap(); + let project_path = root_path.join("project"); + project::init(&project_path, Some(DELAYED)).unwrap(); + let package_path = root_path.join("package"); + let digest = deployment::package(&project_path, &package_path).unwrap(); + let (migration_password, runtime_password) = ( + Uuid::new_v4().simple().to_string(), + Uuid::new_v4().simple().to_string(), + ); + private( + &root_path.join("migration-url"), + format!( + "postgres://{}:{migration_password}@{host}:{port}/{}?sslmode=require", + names.migration, names.database + ) + .as_bytes(), + ); + private( + &root_path.join("runtime-url"), + format!( + "postgres://{}:{runtime_password}@{host}:{port}/{}?sslmode=require", + names.runtime, names.database + ) + .as_bytes(), + ); + private(&root_path.join("ca.pem"), &ca_pem); + for (name, byte) in [("state-key", 71), ("admission-key", 72), ("audit-key", 73)] { + private(&root_path.join(name), &[byte; 32]); + } + for name in ["reader-jwk", "notices-jwk"] { + private( + &root_path.join(name), + registry_platform_testing::fixtures::ED25519_PRIVATE_JWK.as_bytes(), + ); + } + let issuer = TestAuthorizationServer::builder() + .with_signing_key(generate_private_jwk(GeneratedKeyAlgorithm::Es256).unwrap()) + .client(TestClient::new("producer")) + .start() + .await; + let template = include_str!("../../../products/coordinator/examples/single-flow-runtime.yaml"); + let mut doc = yaml_value( + template, + registry_coordinator::runtime::API_VERSION, + registry_coordinator::runtime::KIND, + ); + doc["namespace"] = json!(names.namespace); + doc["secretProviders"]["file"]["root"] = json!(&root_path); + doc["database"]["runtimeUrlRef"] = json!("secret:file/runtime-url"); + doc["database"]["migrationUrlRef"] = json!("secret:file/migration-url"); + doc["database"]["caBundleRef"] = json!("secret:file/ca.pem"); + let d = &mut doc["deployment"]; + d["databaseId"] = json!("provision-test"); + d["runtimeRole"] = json!(names.runtime); + d["packages"] = json!([{"root":package_path,"expectedDigest":digest}]); + d["listener"] = json!({"bind":"127.0.0.1:0","tlsTermination":"development-loopback"}); + d["auditFile"] = json!(root_path.join("audit.jsonl")); + d["stateKeys"] = json!({"1":{"keyRef":"secret:file/state-key"}}); + d["admissionKeyRef"] = json!("secret:file/admission-key"); + d["auditKeyRef"] = json!("secret:file/audit-key"); + d["authentication"] = json!({"issuer":issuer.issuer(),"audience":"urn:coordinator:test","scopeClaim":"scope","jwksSource":{"type":"uri","uri":issuer.jwks_uri()},"policies":{"producer":{"subjects":["owner-a"],"requiredScopes":["coordinator:start"],"workflows":[DELAYED],"actions":["start","status"]}}}); + let path = root_path.join("runtime.yaml"); + fs::write(&path, serde_norway::to_string(&doc).unwrap()).unwrap(); + + // The first run creates both roles, the database and the grant that lets + // `apply` create the namespace schema. + let output = provision(&path, &admin_url); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stdout}{stderr}"); + let report: Value = serde_json::from_str(&stdout).unwrap(); + let outcome = |report: &Value, step: &str| { + report["statements"] + .as_array() + .unwrap() + .iter() + .find(|s| s["step"] == step) + .map(|s| s["outcome"].clone()) + }; + assert_eq!(outcome(&report, "role.migration"), Some("created".into())); + assert_eq!(outcome(&report, "role.runtime"), Some("created".into())); + assert_eq!(outcome(&report, "database.create"), Some("created".into())); + assert!( + outcome(&report, "database.grant-create").is_some(), + "{stdout}" + ); + assert_eq!(report["executed"], true); + for secret in [ + migration_password.as_str(), + runtime_password.as_str(), + owner_password.as_str(), + "postgres://", + ] { + assert!( + !stdout.contains(secret) && !stderr.contains(secret), + "the output leaked a secret" + ); + } + + // A second run finds everything present. + let output = provision(&path, &admin_url); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(outcome(&report, "database.create"), Some("present".into())); + assert_eq!(outcome(&report, "role.runtime"), Some("present".into())); + + // `apply` creates the namespace schema as the migration role. + let output = ctl(&path, &["apply"]); + assert!( + output.status.success(), + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + + // The runtime role holds CONNECT on the database and nothing else there. + let database_admin = connect_verified(&superuser_url, &ca_pem, Some(&names.database)).await; + let schema_owner: String = database_admin + .query_one( + "SELECT pg_get_userbyid(nspowner) FROM pg_namespace WHERE nspname = $1", + &[&names.namespace], + ) + .await + .unwrap() + .get(0); + assert_eq!(schema_owner, names.migration); + let (connect_privilege, create_privilege): (bool, bool) = { + let row = database_admin + .query_one( + "SELECT has_database_privilege($1, $2, 'CONNECT'), has_database_privilege($1, $2, 'CREATE')", + &[&names.runtime, &names.database], + ) + .await + .unwrap(); + (row.get(0), row.get(1)) + }; + assert!(connect_privilege); + assert!(!create_privilege); + + // The service runs as the runtime role and answers a route. + let runtime = Arc::new(RuntimeConfig::load(&path).unwrap()); + let workflows = + Arc::new(deployment::load_workflows(deployment::config(&runtime).unwrap()).unwrap()); + let store = deployment::open(&runtime, false).await.unwrap(); + let authenticator = Arc::new( + deployment::config(&runtime) + .unwrap() + .authentication + .authenticator(&runtime.secret_providers, true) + .await + .unwrap(), + ); + let state = HttpState { + recovery_only: false, + store, + runtime: runtime.clone(), + workflows, + authenticator, + adapters: Arc::new(HttpAdapters::new(&runtime).unwrap()), + }; + 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, http::router(state)).await.unwrap(); + }); + let token = issuer.issue_access_token( + "producer", + "owner-a", + "urn:coordinator:test", + "coordinator:start", + Utc::now().timestamp() + 300, + ); + let response = reqwest::Client::new() + .get(format!("{origin}/v1/workflows/{DELAYED}")) + .bearer_auth(token) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let contract: Value = response.json().await.unwrap(); + assert!(contract["workflowRevision"].is_string()); + server.abort(); +} diff --git a/crates/registry-documentsctl/Cargo.toml b/crates/registry-documentsctl/Cargo.toml index edec888d13..2132c99b7e 100644 --- a/crates/registry-documentsctl/Cargo.toml +++ b/crates/registry-documentsctl/Cargo.toml @@ -17,6 +17,11 @@ name = "postgres_cli" path = "tests/postgres_cli.rs" required-features = ["postgres-test"] +[[test]] +name = "provision_postgres" +path = "tests/provision_postgres.rs" +required-features = ["postgres-test"] + [features] default = [] postgres-test = ["registry-documents/postgres-test"] @@ -30,13 +35,16 @@ registry-documents.workspace = true registry-documents-core.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true serde.workspace = true serde_json.workspace = true tempfile.workspace = true tokio = { workspace = true, features = ["rt"] } uuid.workspace = true +zeroize.workspace = true [dev-dependencies] +registry-platform-provision = { workspace = true, features = ["test-support"] } tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } tokio-postgres.workspace = true diff --git a/crates/registry-documentsctl/src/lib.rs b/crates/registry-documentsctl/src/lib.rs index d105d01101..9bc2798d65 100644 --- a/crates/registry-documentsctl/src/lib.rs +++ b/crates/registry-documentsctl/src/lib.rs @@ -49,6 +49,7 @@ use serde_json::{json, Value}; use uuid::Uuid; mod operate; +mod provision; mod report; mod starter; @@ -90,6 +91,8 @@ enum Command { Package(PackageArgs), /// Report what apply would change in the database, writing nothing. Plan(ActivationArgs), + /// Create the roles and the database the runtime file names, or print the SQL. + Provision(registry_platform_provision::ProvisionArgs), /// Apply the schema and record the configured package as active. Apply(ApplyArgs), /// Report the active package and the activation history. @@ -512,6 +515,7 @@ where }; let command = command_path(&cli.command); let outcome = match &cli.command { + Command::Provision(args) => return provision(args, cli.format), Command::Init(args) => init(&args.directory), Command::Check(args) => check(args), Command::Package(args) => package(args), @@ -556,6 +560,7 @@ fn command_path(command: &Command) -> &'static str { Command::Check(_) => "check", Command::Package(_) => "package", Command::Plan(_) => "plan", + Command::Provision(_) => "provision", Command::Apply(_) => "apply", Command::Status(_) => "status", Command::Verification(VerificationCommand::List(_)) => "verification list", @@ -566,6 +571,23 @@ fn command_path(command: &Command) -> &'static str { } } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: ®istry_platform_provision::ProvisionArgs, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "documentsctl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + shared, + provision::load, + ) +} + fn init(directory: &Path) -> Outcome { match starter::write(directory) { Ok(created) => { diff --git a/crates/registry-documentsctl/src/provision.rs b/crates/registry-documentsctl/src/provision.rs new file mode 100644 index 0000000000..1ed7465b91 --- /dev/null +++ b/crates/registry-documentsctl/src/provision.rs @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `documentsctl provision`: the shared command over the Document Store's +//! runtime file. The file's two database URLs name the roles, the database +//! and both passwords, so nothing is written twice. + +use std::path::Path; + +use registry_documents::config::{startup_report, RuntimeConfig}; +use registry_documents_core::DOCUMENTS_RUNTIME_KIND; +use registry_platform_config::describe_secret_failure; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +/// The Document Store keeps its tables in `public`, handed to the migration +/// role, and needs no extension. +fn product() -> ProductDatabase { + ProductDatabase { + product: "documents", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } +} + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(DOCUMENTS_RUNTIME_KIND.to_owned()); + Box::new(diagnostic) +} + +/// Reads the runtime file exactly as `apply` does and resolves the two +/// database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be resolved against the working directory" + .to_owned(), + "Pass --runtime-config as a path that exists.", + ) + })?; + let config = RuntimeConfig::load(&absolute).map_err(|error| { + match startup_report(&absolute, &error) + .and_then(|report| report.diagnostics().first().cloned()) + { + Some(diagnostic) => Box::new(diagnostic), + None => refused( + "config.refused", + "", + error.to_string(), + "Correct the runtime file, then run provision again.", + ), + } + })?; + let secrets = config.secret_resolver().map_err(|error| { + refused( + "config.refused", + "/secretProviders", + error.to_string(), + "Correct secretProviders in the runtime file, then run provision again.", + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refused( + "config.refused", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; + let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let ca_pem = config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + Ok(ProvisionInput { + product: product(), + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-documentsctl/tests/provision_cli.rs b/crates/registry-documentsctl/tests/provision_cli.rs new file mode 100644 index 0000000000..204f0cec6e --- /dev/null +++ b/crates/registry-documentsctl/tests/provision_cli.rs @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `documentsctl provision` without a database: print mode reads the runtime +//! file and writes the script without connecting or printing a password, and +//! the administrator flags refuse the combinations the shared command +//! refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file whose secret files name a migration and a runtime login on +/// one server that does not exist, so a connection attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!( + "postgresql://documents_migration:{MIGRATION_PASSWORD}@db.invalid:5432/documents" + ), + ), + ( + "runtime-database-url", + format!("postgresql://documents_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/documents"), + ), + ( + "documents-audit-key", + "documentsctl-test-audit-key-not-a-secret".to_owned(), + ), + ( + "hook-key", + "documentsctl-test-hook-key-not-a-secret-0123456789".to_owned(), + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/documents/runtime/v1alpha1 +kind: DocumentsRuntimeConfig +identity: + databaseId: registry-documents-ctl-test +package: + root: {package} +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback + networkExposure: private-address +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url +authentication: + oidc: + issuer: https://identity.example.test/realms/registry + audience: urn:example:documents + scopeClaim: scope + allowedClients: [civil-registry-app] +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/documents-audit-key +storage: + type: database +contentVerification: + type: disabled +cleanup: + erasure: active +destinations: + hooks: + owning-system-events: + url: http://127.0.0.1:9/document-events + hmacSha256KeyRef: secret:file/hook-key +", + package = directory.join("package").display(), + secrets = secrets.display(), + audit = directory.join("audit.ndjson").display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_documentsctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in ["documents_migration", "documents_runtime", "documents"] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "documents"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "documents"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } + + // The command's own flag, after the verb, selects the same report. + let after = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--format", + "json", + ]); + assert_eq!(after.status.code(), Some(0)); + assert_eq!(String::from_utf8(after.stdout).unwrap(), stdout); +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for arguments in [ + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "DOCUMENTS_ADMIN_URL", + ], + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "DOCUMENTS_ADMIN_URL", + ], + vec!["provision", "--runtime-config", &runtime], + ] { + let output = ctl(&arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty(), "{arguments:?}"); + } +} diff --git a/crates/registry-documentsctl/tests/provision_postgres.rs b/crates/registry-documentsctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..1cd7c60b54 --- /dev/null +++ b/crates/registry-documentsctl/tests/provision_postgres.rs @@ -0,0 +1,300 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `documentsctl provision` against a real server, then `apply` and the +//! runtime on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. The administrator sessions of this suite +//! use verified TLS, so the server must offer it. Without the variables the +//! test fails on the spot: a skipped database test is not database +//! verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use serde_json::Value; +use uuid::Uuid; + +/// One deployment directory and the superuser session that creates the +/// roles `provision` is run from. +struct Deployment { + directory: tempfile::TempDir, + admin: tokio_postgres::Client, +} + +impl Deployment { + async fn new() -> Self { + let (url, ca_pem) = provision_test_env(); + let admin = connect_verified(&url, &ca_pem, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "documents-audit-key", + "documentsctl-test-audit-key-not-a-secret", + ), + ( + "hook-key", + "documentsctl-test-hook-key-not-a-secret-0123456789", + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + Self { directory, admin } + } + + fn path(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + + fn runtime(&self) -> String { + self.path("runtime.yaml").display().to_string() + } + + /// Write the runtime document over `package`, pinned to `digest`. + fn write_runtime(&self, package: &Path, digest: &str) { + let document = format!( + "\ +apiVersion: id.registrystack.org/formats/documents/runtime/v1alpha1 +kind: DocumentsRuntimeConfig +identity: + databaseId: registry-documents-ctl-test +package: + root: {package} + expectedDigest: {digest} +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback + networkExposure: private-address +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + testOnlyPlaintext: true +authentication: + oidc: + issuer: https://identity.example.test/realms/registry + audience: urn:example:documents + scopeClaim: scope + allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal] +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/documents-audit-key +storage: + type: database +contentVerification: + type: disabled +cleanup: + erasure: active +destinations: + hooks: + owning-system-events: + url: http://127.0.0.1:9/document-events + hmacSha256KeyRef: secret:file/hook-key +", + package = package.display(), + secrets = self.path("secrets").display(), + audit = self.path("audit.ndjson").display(), + ); + std::fs::write(self.path("runtime.yaml"), document).unwrap(); + } + + /// `init`, then `package`, then a runtime document pinned to the + /// package digest the report names. + fn deploy(&self) -> String { + let project = self.path("project").display().to_string(); + let (code, report) = ctl(&["init", &project]); + assert_eq!(code, 0, "{report:#}"); + let package = self.path("package"); + let (code, report) = ctl(&["package", &project, "--output", package.to_str().unwrap()]); + assert_eq!(code, 0, "{report:#}"); + let digest = report["packageDigest"].as_str().unwrap().to_owned(); + self.write_runtime(&package, &digest); + digest + } + + /// Replace the secret file `name` with `value`. + fn secret(&self, name: &str, value: &str) { + let path = self.path("secrets").join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&str]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_documentsctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stdout))); + (output.status.code().unwrap(), report) +} + +/// The public half of a P-256 key, as a key set the runtime trusts. +const PUBLIC_KEY_SET: &str = r#"{"keys":[{"kty":"EC","crv":"P-256","alg":"ES256","use":"sig","kid":"documentsctl-test-1","x":"gEHpg5PeV9TxLeisE9SSOQLb8FibjLxUHbQANAxmS4A","y":"wPnAyYS42uEWe2vyT4ys7yOAPoQwYU5FkogAZYroLbk"}]}"#; + +/// `provision` as the operate page runs it: from the administrator URL of a +/// non-superuser that holds only `CREATEROLE` and `CREATEDB`, over a runtime +/// file whose two URLs name the roles and the database. `apply` then +/// activates the package over the migration credential, and the runtime +/// starts over the runtime credential and answers its health route. +#[tokio::test] +async fn provision_then_apply_then_serve_with_split_roles() { + let deployment = Deployment::new().await; + deployment.deploy(); + let runtime = deployment.runtime(); + let (base_url, ca) = provision_test_env(); + let ca_path = deployment.path("secrets").join("postgres-ca.pem"); + std::fs::write(&ca_path, &ca).unwrap(); + std::fs::set_permissions(&ca_path, std::fs::Permissions::from_mode(0o600)).unwrap(); + let document = std::fs::read_to_string(&runtime).unwrap(); + // The runtime verifies tokens against a static key set, so it starts + // without reaching the issuer. + const ALLOWED_CLIENTS: &str = + " allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal]\n"; + assert!(document.contains(" testOnlyPlaintext: true\n")); + assert!(document.contains(ALLOWED_CLIENTS)); + std::fs::write( + &runtime, + document + .replace( + " testOnlyPlaintext: true\n", + " caBundleRef: secret:file/postgres-ca.pem\n", + ) + .replace( + ALLOWED_CLIENTS, + &format!( + "{ALLOWED_CLIENTS} jwksSource:\n type: static\n documentRef: secret:file/jwks.json\n" + ), + ), + ) + .unwrap(); + deployment.secret("jwks.json", PUBLIC_KEY_SET); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let (owner, migration, runtime_role, database) = ( + format!("documents_owner_{suffix}"), + format!("documents_mig_{suffix}"), + format!("documents_rt_{suffix}"), + format!("documents_db_{suffix}"), + ); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let (owner_password, migration_password, runtime_password) = ( + password("owner"), + password("migration"), + password("runtime"), + ); + deployment + .admin + .batch_execute(&format!( + "CREATE ROLE {owner} LOGIN PASSWORD '{owner_password}' NOSUPERUSER CREATEROLE CREATEDB" + )) + .await + .unwrap(); + + let base = registry_platform_provision::admin_config(&base_url, Some(&ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, port) = (base.host(), base.port()); + let url = |role: &str, password: &str, database: &str| { + format!("postgresql://{role}:{password}@{host}:{port}/{database}") + }; + deployment.secret( + "migration-database-url", + &url(&migration, &migration_password, &database), + ); + deployment.secret( + "runtime-database-url", + &url(&runtime_role, &runtime_password, &database), + ); + let admin_file = deployment.path("admin-url"); + std::fs::write(&admin_file, url(&owner, &owner_password, "postgres")).unwrap(); + std::fs::set_permissions(&admin_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let (code, provisioned) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], database.as_str()); + for secret in [&owner_password, &migration_password, &runtime_password] { + assert!( + !provisioned.to_string().contains(secret.as_str()), + "the report holds no password" + ); + } + + let (code, again) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "a second run converges: {again:#}"); + + let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); + assert_eq!(code, 0, "{applied:#}"); + assert_eq!(applied["activation"]["roleMode"], "split"); + + let prepared = registry_documents::runtime::prepare(&runtime) + .await + .expect("the runtime prepares over the runtime role"); + let address = prepared.local_addr().unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(prepared.serve_until(async { + stopped.await.ok(); + })); + let response = tokio::task::spawn_blocking(move || { + use std::io::{Read as _, Write as _}; + let mut stream = std::net::TcpStream::connect(address).unwrap(); + stream + .write_all(b"GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") + .unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).unwrap(); + response + }) + .await + .unwrap(); + assert!( + response.starts_with("HTTP/1.1 200"), + "the health route answers: {response}" + ); + stop.send(()).unwrap(); + server.await.unwrap().expect("the server stops cleanly"); + + for statement in [ + format!("DROP DATABASE {database} WITH (FORCE)"), + format!("DROP ROLE {runtime_role}"), + format!("DROP ROLE {migration}"), + format!("DROP ROLE {owner}"), + ] { + deployment.admin.batch_execute(&statement).await.unwrap(); + } +} diff --git a/crates/registry-platform-provision/Cargo.toml b/crates/registry-platform-provision/Cargo.toml index 8f63e1de03..8473cf6360 100644 --- a/crates/registry-platform-provision/Cargo.toml +++ b/crates/registry-platform-provision/Cargo.toml @@ -19,6 +19,10 @@ default = [] # With the feature on, a missing variable fails the suite. With `cli` on too, # src/cli.rs also runs the `provision` command against the first server. postgres-test = [] +# Test helpers for the provision tests of the products that use this crate: +# a verified-TLS superuser session and the two PROVISION_TEST_DATABASE_* +# variables. Dev-dependencies only, never a runtime build. +test-support = [] # The shared `provision` command: clap arguments, the runner and the report. cli = [ diff --git a/crates/registry-platform-provision/README.md b/crates/registry-platform-provision/README.md index bbacf1703c..56873f9640 100644 --- a/crates/registry-platform-provision/README.md +++ b/crates/registry-platform-provision/README.md @@ -28,3 +28,8 @@ computed in the client, never the password. No API in this crate prints, formats or logs a secret. This crate builds plans only. It opens no connection. + +The `test-support` feature adds `test_support`, a verified-TLS superuser +session and the two `PROVISION_TEST_DATABASE_*` variables, for the provision +tests of `registry-caseworkctl`, `registry-coordinator` and +`registry-documentsctl`. Only their dev-dependencies enable it. diff --git a/crates/registry-platform-provision/src/admin.rs b/crates/registry-platform-provision/src/admin.rs index 3f953368db..9b922a171c 100644 --- a/crates/registry-platform-provision/src/admin.rs +++ b/crates/registry-platform-provision/src/admin.rs @@ -204,6 +204,25 @@ impl AdminConfig { } } +#[cfg(feature = "test-support")] +impl AdminConfig { + /// Opens a session to `database` whose connection task runs on the current + /// runtime for as long as the client lives. The failure is the driver's, + /// which carries neither the URL nor the password. + pub(crate) async fn connect_detached( + &self, + database: Option<&str>, + ) -> Result { + let mut config = self.config.clone(); + if let Some(database) = database { + config.dbname(database); + } + let (client, connection) = config.connect(self.tls.clone()).await?; + tokio::spawn(connection); + Ok(client) + } +} + impl std::fmt::Debug for AdminConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("AdminConfig") diff --git a/crates/registry-platform-provision/src/lib.rs b/crates/registry-platform-provision/src/lib.rs index 55b035b9aa..9eca80b469 100644 --- a/crates/registry-platform-provision/src/lib.rs +++ b/crates/registry-platform-provision/src/lib.rs @@ -20,6 +20,9 @@ pub mod cli; mod execute; mod plan; pub mod sql; +#[cfg(feature = "test-support")] +#[doc(hidden)] +pub mod test_support; pub use admin::{admin_config, AdminConfig, AdminConfigError}; pub use execute::{execute, verify_logins, Mode, Outcome, ProvisionError, StatementOutcome}; diff --git a/crates/registry-platform-provision/src/test_support.rs b/crates/registry-platform-provision/src/test_support.rs new file mode 100644 index 0000000000..f52994d383 --- /dev/null +++ b/crates/registry-platform-provision/src/test_support.rs @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Helpers for the PostgreSQL tests of the products that provision with this +//! crate. They panic with a message that names the variable or the failure, +//! never the URL or the password. + +use tokio_postgres::Client; + +use crate::admin_config; + +/// Reads `PROVISION_TEST_DATABASE_URL` and the CA PEM file named by +/// `PROVISION_TEST_DATABASE_CA`. A missing variable or unreadable file fails +/// the test: a skipped database test is not database verification. +pub fn provision_test_env() -> (String, Vec) { + let url = std::env::var("PROVISION_TEST_DATABASE_URL") + .expect("PROVISION_TEST_DATABASE_URL names a disposable PostgreSQL superuser URL"); + let ca_path = std::env::var("PROVISION_TEST_DATABASE_CA") + .expect("PROVISION_TEST_DATABASE_CA names the PEM CA of the test server"); + let ca = std::fs::read(&ca_path).unwrap_or_else(|error| { + panic!("cannot read the file PROVISION_TEST_DATABASE_CA names: {error}") + }); + (url, ca) +} + +/// Opens a session over TLS verified against `ca_pem`, with the endpoint and +/// credentials of `url` (the same rules `provision` applies to an +/// administrator URL). `database` replaces the one the URL names. The +/// connection task runs on the current runtime. +pub async fn connect_verified(url: &str, ca_pem: &[u8], database: Option<&str>) -> Client { + let config = admin_config(url, Some(ca_pem)) + .unwrap_or_else(|error| panic!("the test PostgreSQL URL or CA is refused: {error}")); + config + .connect_detached(database) + .await + .unwrap_or_else(|error| panic!("cannot open a verified-TLS test session: {error}")) +} diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index cccd584127..0656fe869f 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -82,25 +82,40 @@ root read-only, and give the audit directory durable writable storage. ## Provision PostgreSQL -Use a new database. As your PostgreSQL administrator, create a schema-owning migration role, a -separate runtime role, and the database: - -```sql -CREATE ROLE casework_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS PASSWORD ''; -CREATE ROLE casework_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS PASSWORD ''; -CREATE DATABASE casework; +Use a new database. Your runtime file names the roles, their passwords, and the database: they are +the URLs in `database.migrationUrlRef` and `database.runtimeUrlRef`, which +[the next section](#write-the-runtime-file) writes. Put both URLs in their secret files, then run +`caseworkctl provision` once as a PostgreSQL role that can create roles and databases: + +```sh +caseworkctl provision --runtime-config runtime.yaml --admin-url-file admin-url ``` -In that database, grant connection access and give the migration role the schema: +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and +`CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, +use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set +`database.caBundleRef` in the runtime file to trust a private CA. The command never prints the +administrator URL or a password. -```sql -REVOKE ALL ON DATABASE casework FROM PUBLIC; -GRANT CONNECT ON DATABASE casework TO casework_migration, casework_runtime; -ALTER SCHEMA public OWNER TO casework_migration; -REVOKE ALL ON SCHEMA public FROM PUBLIC; -``` +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it + from `PUBLIC`. + +Run it again at any time. It creates only what is missing and refuses a role that exists with +different attributes. When both URLs name one role, it creates that one role and the deployment +records single-role mode. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a +`\password` line that prompts for the password in `psql`, so the script holds no password. + +{/* Evidence: crates/registry-caseworkctl/src/provision.rs; crates/registry-platform-provision/src/plan.rs, + SchemaLayout::PublicForMigration; crates/registry-caseworkctl/tests/provision.rs. */} Each runtime holds up to 32 connections and waits up to 5 seconds for one; neither is configurable, so allow 32 connections per replica. diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index 88ec886957..66a413df92 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -259,20 +259,41 @@ Secret values never appear in a diagnostic or a log. ### Create the database and roles Use PostgreSQL 17 or newer; `apply` and startup refuse an older server. -As a PostgreSQL administrator, create the migration role, the runtime role, and the database, and let only those two roles connect: +`provision` creates what the two database URLs in your runtime file name: the migration role, the runtime role, and the database, and it lets only those two roles connect. +It takes the role names, the database name, and the passwords from `database.migrationUrlRef` and `database.runtimeUrlRef`, so you write each of them once. + +Run it as a PostgreSQL administrator that can create roles and databases (`CREATEROLE` and `CREATEDB`). +It needs no superuser. +Put the administrator URL in a file or an environment variable, never on the command line. +The connection always uses verified TLS: it trusts the certificate authority behind `database.caBundleRef` when the runtime file names one, and the system roots otherwise. +The URL's `sslmode` must be `require`, `verify-ca`, or `verify-full`. + +```sh +coordinatorctl provision --runtime-config /etc/registry-coordinator/runtime.yaml \ + --admin-url-file /run/registry-coordinator/secrets/admin-database-url +``` + +Use `--admin-url-env NAME` for a variable instead of a file. +Run again at any time: it creates only what is missing, refuses a role or database that exists in another shape, and never changes a password or drops anything. +Add `--format json` for a machine-readable report. +The report and the errors never contain a password, a password verifier, or a URL. + +To review the statements first, or to run them yourself with `psql`, add `--print-sql`. +It connects to nothing and prints a script with a `\password` line after each role instead of a password: ```sql CREATE ROLE coordinator_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS PASSWORD ''; + NOINHERIT NOBYPASSRLS; CREATE ROLE coordinator_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS PASSWORD ''; -CREATE DATABASE coordinator; + NOINHERIT NOBYPASSRLS; +CREATE DATABASE coordinator WITH ALLOW_CONNECTIONS false; REVOKE ALL ON DATABASE coordinator FROM PUBLIC; GRANT CONNECT ON DATABASE coordinator TO coordinator_migration, coordinator_runtime; GRANT CREATE ON DATABASE coordinator TO coordinator_migration; +ALTER DATABASE coordinator WITH ALLOW_CONNECTIONS true; ``` -These are the only grants you make. +These are the only grants `provision` makes. The migration role needs `CREATE` on the database because `apply` creates the schema the runtime file's `namespace` names, and the migration role owns that schema and its tables. A namespace starts with `coordinator_` and is at most 60 characters. The runtime role needs only `CONNECT`. diff --git a/docs/site/src/content/docs/operate/documents.mdx b/docs/site/src/content/docs/operate/documents.mdx index e75334b771..0b9edc31f8 100644 --- a/docs/site/src/content/docs/operate/documents.mdx +++ b/docs/site/src/content/docs/operate/documents.mdx @@ -42,18 +42,51 @@ checkout, as the [overview](../../start/documents/#status) explains. ## Provision PostgreSQL -Create the roles and the database: +Your runtime file already names the roles, their passwords, and the database. They are the URLs in +`database.migrationUrlRef` and `database.runtimeUrlRef`. Put both URLs in their secret files, then +run `documentsctl provision` once as a PostgreSQL role that can create roles and databases: + +```sh +documentsctl provision --runtime-config runtime.yaml --admin-url-file admin-url +``` + +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and +`CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, +use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set +`database.caBundleRef` in the runtime file to trust a private CA. The command never prints the +administrator URL or a password. + +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it + from `PUBLIC`. + +Run it again at any time. It creates only what is missing. It refuses a role that exists with a +different password than its URL holds, and tells you which role. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a +`\password` line that prompts for the password in `psql`, so the script holds no password: ```sql -CREATE ROLE documents_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS; -CREATE ROLE documents_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS; -CREATE DATABASE documents; +SET createrole_self_grant = 'set,inherit'; +CREATE ROLE "documents_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "documents_migration" +CREATE ROLE "documents_runtime" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "documents_runtime" +CREATE DATABASE "documents" WITH ALLOW_CONNECTIONS false; +REVOKE ALL ON DATABASE "documents" FROM PUBLIC; +GRANT CONNECT ON DATABASE "documents" TO "documents_migration", "documents_runtime"; +ALTER DATABASE "documents" ALLOW_CONNECTIONS true; +\connect "documents" +REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "documents_migration"; ``` -Set each role's password with `\password documents_migration` and `\password documents_runtime` in -`psql`, which prompts for it instead of taking it in a statement. +The names come from your URLs. Add `--format json` for a report of each statement and its outcome. Document content is stored as `bytea`, so the database is slightly larger than the stored payload. A custom-format `pg_dump` is larger than the payload because `pg_dump` writes `bytea` as hex, so plan @@ -61,17 +94,8 @@ backup space above the database size. {/* Evidence: crates/registry-documents/migrations/0100_documents.sql, content bytea. */} -In the `documents` database, hand the schema to the migration role: - -```sql -REVOKE ALL ON DATABASE documents FROM PUBLIC; -GRANT CONNECT ON DATABASE documents TO documents_migration, documents_runtime; -ALTER SCHEMA public OWNER TO documents_migration; -REVOKE ALL ON SCHEMA public FROM PUBLIC; -``` - -Grant the runtime role nothing more. `apply` grants it what serving needs, and `serve` refuses a -runtime role that holds authority over the schema. If the runtime role later loses `USAGE` on the +`provision` grants the runtime role nothing beyond `CONNECT`. `apply` grants it what serving needs, +and `serve` refuses a runtime role that holds authority over the schema. If the runtime role later loses `USAGE` on the schema or read access to the activation ledger, `serve` refuses to start and the operator commands answer `documentsctl.activation.ledger-unreadable` at `database.runtimeUrlRef`. Run `apply` again with the migration credential to restore its grants. diff --git a/products/casework/AGENTS.md b/products/casework/AGENTS.md index 5c0598e97c..ef4a61bbae 100644 --- a/products/casework/AGENTS.md +++ b/products/casework/AGENTS.md @@ -20,7 +20,10 @@ canonical examples, and product-local verification scripts. Read the workspace `CASEWORK_ASSIGNMENT_TEST_DATABASE_URL`; fixtures isolate themselves in unique schemas. The native BReg journey also uses `BREG_TEST_DATABASE_URL`. The separate `caseworkctl` split-role session test uses - `CASEWORK_TEST_DATABASE_URL`. + `CASEWORK_TEST_DATABASE_URL`. The `caseworkctl provision` test reads the + shared `PROVISION_TEST_DATABASE_URL`, a disposable superuser URL on a server + that offers verified TLS, and `PROVISION_TEST_DATABASE_CA`, the + path of the CA bundle that verifies it. Never point test URLs at retained operator data. - Keep the submitted and current-source examples small and executable. Preserve exact policy and provider bindings, reviewer disclosure, independent producer diff --git a/products/coordinator/AGENTS.md b/products/coordinator/AGENTS.md index 2daa65a41c..a9cc99f630 100644 --- a/products/coordinator/AGENTS.md +++ b/products/coordinator/AGENTS.md @@ -83,5 +83,10 @@ COORDINATOR_SCHEDULING_TEST_DATABASE_URL= \ products/coordinator/scripts/test-postgres.sh ``` +The `provision_postgres` target needs `PROVISION_TEST_DATABASE_URL`, a +disposable superuser URL over verified TLS (`sslmode=verify-full`), and +`PROVISION_TEST_DATABASE_CA`, the path of the CA PEM. It fails without them, +and `scripts/test-postgres.sh` does not run it. + `README.md` names the focused runtime test targets and the native-service journeys. The client binding checks are in `crates/CLIENTS.md`. diff --git a/products/coordinator/scripts/check_dependency_direction.py b/products/coordinator/scripts/check_dependency_direction.py index 1284891fef..86eda8b5d6 100644 --- a/products/coordinator/scripts/check_dependency_direction.py +++ b/products/coordinator/scripts/check_dependency_direction.py @@ -49,9 +49,10 @@ "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"}) +# The combined Coordinator crate also publishes coordinatorctl. These helpers +# supply its product-neutral request/connection CLI and its report +# serialization, and reach no product. +CLI_SUPPORT = frozenset({"registry-cli-api", "registry-cli-report"}) # Product cores the runtime reaches only through their product client. The # core is in the runtime's forward closure through that client, so only the diff --git a/products/coordinator/scripts/test_dependency_direction.py b/products/coordinator/scripts/test_dependency_direction.py index f65538c8df..c58862b352 100644 --- a/products/coordinator/scripts/test_dependency_direction.py +++ b/products/coordinator/scripts/test_dependency_direction.py @@ -22,6 +22,7 @@ "stack-client": "registry-stack-client", "cli-docs": "registry-cli-docs", "cli-api": "registry-cli-api", + "cli-report": "registry-cli-report", "breg": "registry-breg", "breg-client": "registry-breg-client", "bregctl": "registry-bregctl", @@ -68,6 +69,7 @@ "stack-client": ["breg-client", "messaging-client", "scheduling-client", "client"], "cli-docs": ["runtime", "breg", "bregctl", "messaging", "scheduling", "schedulingctl"], "cli-api": ["platform"], + "cli-report": ["serde"], "breg": ["record", "platform"], "breg-client": ["record", "platform"], "bregctl": ["breg"], @@ -131,6 +133,14 @@ def test_shared_cli_support_is_accepted_without_product_authority(self): ) self.assertIn("registry-bregctl", found) + def test_the_shared_cli_report_is_accepted_without_product_authority(self): + self.assertEqual(failures(runtime=[*INTENDED["runtime"], "cli-report"]), "") + found = failures( + runtime=[*INTENDED["runtime"], "cli-report"], + cli_report=["bregctl"], + ) + self.assertIn("registry-bregctl", found) + def test_intended_direction_is_accepted(self): self.assertEqual(MODULE.violations(metadata()), []) diff --git a/products/documents/AGENTS.md b/products/documents/AGENTS.md index 253f490428..2c463fdb3e 100644 --- a/products/documents/AGENTS.md +++ b/products/documents/AGENTS.md @@ -33,6 +33,10 @@ rules that govern it and the invariant rows in `contracts/` that prove them. `scripts/check_database_test_isolation.py` refuses a suite that would run under default Cargo resolution. A suite skipped for a missing database URL is not database verification; the suites fail instead of skipping. + The `provision_postgres` target of `registry-documentsctl` needs + `PROVISION_TEST_DATABASE_URL`, a disposable superuser URL (`sslmode=verify-full` + on a server that offers verified TLS), and + `PROVISION_TEST_DATABASE_CA`, the path of the CA PEM. It fails without them. - Treat everything under `generated/` as generated output. The schemas and the OpenAPI document come from the generators `README.md` names, and the `schema` feature's drift test, run by `scripts/check-checkpoint.sh`, fails diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 0ff7e11546..0b47a39595 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- A `test-support` feature in `registry-platform-provision` gives the product + provision tests one verified-TLS superuser session, so they run against a + TLS-only PostgreSQL server. It is enabled only by dev-dependencies. + - One rule for a static key set, in `registry-platform-oidc` (`public_jwks_document`, behind `parse_static_jwks`). A key set that holds a private or symmetric member (`d`, `k`, `p`, `q`, `dp`, `dq`, `qi`, From d88f05c9a17780e7bbfc7546271c378dd9f557ae Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 03:17:55 +0100 Subject: [PATCH 016/136] test(platform): add observed ThunderID 1.1.0 and Supabase shapes to the token corpus The corpus held documented shapes for Supabase and only ThunderID 1.0.1 captures. It now carries shapes observed from a ThunderID 1.1.0 issuer (a token-exchange result, a person who proves identity only, attribute-carried claims, a JWT refresh token, a second ThunderID standing in for eSignet) and corrected Supabase shapes, under a new `issuer` source basis. A token's required scope is read with one helper that skips OpenID Connect scopes, so no characterisation profile requires `openid`, and every product test reads authority from `scope` only. Each cell's main result is observed on main's admission code. Signed-off-by: Jeremi Joslin --- .../tests/token_characterisation.rs | 16 +- .../tests/token_characterisation.rs | 15 +- .../src/access/token_characterisation.rs | 5 +- .../tests/token_characterisation.rs | 16 +- .../tests/token_characterisation.rs | 15 +- .../tests/token_characterisation.rs | 15 +- .../src/token_characterisation.rs | 44 ++-- .../tests/token_characterisation.rs | 16 +- .../src/token_fixtures.rs | 42 +++ .../tests/token_fixtures.rs | 34 ++- .../tests/token_characterisation.rs | 16 +- .../platform/conformance/tokens/README.md | 3 +- .../platform/conformance/tokens/expected.yaml | 241 ++++++++++++++++-- .../tokens/fixtures/esignet-access-token.json | 2 +- .../tokens/fixtures/esignet-id-token.json | 2 +- .../esignet-standin-access-token.json | 48 ++++ .../fixtures/esignet-standin-id-token.json | 54 ++++ .../fixtures/supabase-api-key-anon.json | 20 +- .../fixtures/supabase-api-key-opaque.json | 11 +- .../supabase-api-key-service-role.json | 20 +- .../tokens/fixtures/supabase-user-access.json | 37 +-- ...d-client-credentials-attribute-claims.json | 52 ++++ .../thunderid-exchanged-holder-no-scope.json | 56 ++++ .../fixtures/thunderid-exchanged-holder.json | 53 ++++ .../tokens/fixtures/thunderid-id-token.json | 19 +- .../fixtures/thunderid-refresh-token.json | 56 ++++ ...hunderid-user-access-attribute-claims.json | 56 ++++ .../thunderid-user-access-identity-only.json | 54 ++++ .../tokens/token-fixture.schema.json | 11 + 29 files changed, 848 insertions(+), 181 deletions(-) create mode 100644 products/platform/conformance/tokens/fixtures/esignet-standin-access-token.json create mode 100644 products/platform/conformance/tokens/fixtures/esignet-standin-id-token.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-client-credentials-attribute-claims.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-exchanged-holder-no-scope.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-exchanged-holder.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-refresh-token.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-user-access-attribute-claims.json create mode 100644 products/platform/conformance/tokens/fixtures/thunderid-user-access-identity-only.json diff --git a/crates/registry-breg/tests/token_characterisation.rs b/crates/registry-breg/tests/token_characterisation.rs index debaa70512..b8bf3a809b 100644 --- a/crates/registry-breg/tests/token_characterisation.rs +++ b/crates/registry-breg/tests/token_characterisation.rs @@ -100,7 +100,9 @@ impl Shape { (None, true) => Vec::new(), (None, false) => vec![LISTED_CLIENT.to_owned()], }; - let scope = first_scope(fixture, scope_claim).unwrap_or_else(|| FALLBACK_SCOPE.to_owned()); + let scope = fixture + .read_scope(scope_claim) + .unwrap_or_else(|| FALLBACK_SCOPE.to_owned()); Self { algorithm, access_token_type, @@ -228,18 +230,6 @@ fn literal_text(fixture: &TokenFixture, claim: &str) -> Option { } } -/// The first scope the fixture carries in `claim`, a space-separated string or -/// a list. -fn first_scope(fixture: &TokenFixture, claim: &str) -> Option { - match fixture.claims.get(claim) { - Some(ClaimValue::Literal(Value::String(text))) => text.split(' ').next().map(str::to_owned), - Some(ClaimValue::Literal(Value::Array(items))) => { - items.first().and_then(Value::as_str).map(str::to_owned) - } - _ => None, - } -} - async fn observe(case: FixtureCase) -> Outcome { let shape = Shape::of(&case); let config = parse_runtime_config(&shape.runtime_yaml(&case)) diff --git a/crates/registry-casework/tests/token_characterisation.rs b/crates/registry-casework/tests/token_characterisation.rs index c50213ad15..e39d93f719 100644 --- a/crates/registry-casework/tests/token_characterisation.rs +++ b/crates/registry-casework/tests/token_characterisation.rs @@ -110,7 +110,8 @@ impl Shape { (None, true) => Vec::new(), (None, false) => vec![LISTED_CLIENT.to_owned()], }; - let scope = first_scope(fixture, scope_claim.unwrap_or("registry_scopes")) + let scope = fixture + .read_scope(scope_claim.unwrap_or("registry_scopes")) .unwrap_or_else(|| FALLBACK_SCOPE.to_owned()); Self { scope_claim, @@ -202,18 +203,6 @@ fn literal_text(fixture: &TokenFixture, claim: &str) -> Option { } } -/// The first scope the fixture carries in `claim`, a space-separated string or -/// a list. -fn first_scope(fixture: &TokenFixture, claim: &str) -> Option { - match fixture.claims.get(claim) { - Some(ClaimValue::Literal(Value::String(text))) => text.split(' ').next().map(str::to_owned), - Some(ClaimValue::Literal(Value::Array(items))) => { - items.first().and_then(Value::as_str).map(str::to_owned) - } - _ => None, - } -} - async fn observe(case: FixtureCase, secrets: &Secrets) -> Outcome { let shape = Shape::of(&case); let config = RuntimeConfig::loader() diff --git a/crates/registry-coordinator/src/access/token_characterisation.rs b/crates/registry-coordinator/src/access/token_characterisation.rs index 24d799d920..fbfe89735e 100644 --- a/crates/registry-coordinator/src/access/token_characterisation.rs +++ b/crates/registry-coordinator/src/access/token_characterisation.rs @@ -37,10 +37,7 @@ fn client_of(fixture: &TokenFixture) -> Option { } fn first_scope(fixture: &TokenFixture) -> Option { - literal(fixture, "scope")? - .split_whitespace() - .next() - .map(str::to_owned) + fixture.read_scope("scope") } fn stage_of(error: &OidcError) -> Outcome { diff --git a/crates/registry-documents/tests/token_characterisation.rs b/crates/registry-documents/tests/token_characterisation.rs index be42b0b8c7..7dc1a1e006 100644 --- a/crates/registry-documents/tests/token_characterisation.rs +++ b/crates/registry-documents/tests/token_characterisation.rs @@ -82,17 +82,6 @@ fn scope_claim(case: &FixtureCase) -> &'static str { } } -/// The first scope the fixture carries in the claim the configuration names. -fn read_scope(case: &FixtureCase, claim: &str) -> String { - match case.fixture.claims.get(claim) { - Some(ClaimValue::Literal(Value::String(text))) => text.split_whitespace().next(), - Some(ClaimValue::Literal(Value::Array(items))) => items.first().and_then(Value::as_str), - _ => None, - } - .unwrap_or(PLACEHOLDER_SCOPE) - .to_owned() -} - /// The actor kind the profile admits: the one the fixture declares when it is /// a kind the Document Store has, and `human` otherwise or when the row /// selects the human-only profile. @@ -169,7 +158,10 @@ async fn observe(case: FixtureCase) -> Outcome { ); let claim = scope_claim(&case); - let scope = read_scope(&case, claim); + let scope = case + .fixture + .read_scope(claim) + .unwrap_or_else(|| PLACEHOLDER_SCOPE.to_owned()); let client = fixture_client(&case); let project = project_text(&client, &scope, profile_actor_kind(&case)); let package = root.path().join("package"); diff --git a/crates/registry-evidence-oid4vci/tests/token_characterisation.rs b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs index be1e1d691d..cef6d01bd8 100644 --- a/crates/registry-evidence-oid4vci/tests/token_characterisation.rs +++ b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs @@ -47,18 +47,9 @@ fn fixture_client(case: &FixtureCase) -> Option { /// The first scope the fixture carries, read from `scope` or `scp`. fn first_scope(case: &FixtureCase) -> Option { - if let Some(scope) = literal_string(case, "scope") { - return scope.split_whitespace().next().map(str::to_owned); - } - match case.fixture.claims.get("scp") { - Some(ClaimValue::Literal(Value::String(scope))) => { - scope.split_whitespace().next().map(str::to_owned) - } - Some(ClaimValue::Literal(Value::Array(scopes))) => { - scopes.first().and_then(Value::as_str).map(str::to_owned) - } - _ => None, - } + case.fixture + .read_scope("scope") + .or_else(|| case.fixture.read_scope("scp")) } /// The algorithm the offer boundary is configured with for the row: the diff --git a/crates/registry-evidence/tests/token_characterisation.rs b/crates/registry-evidence/tests/token_characterisation.rs index e5f2269933..43bb3748ed 100644 --- a/crates/registry-evidence/tests/token_characterisation.rs +++ b/crates/registry-evidence/tests/token_characterisation.rs @@ -56,18 +56,9 @@ fn fixture_client(case: &FixtureCase) -> Option { /// The first scope the fixture carries, read from `scope` or `scp`. fn first_scope(case: &FixtureCase) -> Option { - if let Some(scope) = literal_string(case, "scope") { - return scope.split_whitespace().next().map(str::to_owned); - } - match case.fixture.claims.get("scp") { - Some(ClaimValue::Literal(Value::String(scope))) => { - scope.split_whitespace().next().map(str::to_owned) - } - Some(ClaimValue::Literal(Value::Array(scopes))) => { - scopes.first().and_then(Value::as_str).map(str::to_owned) - } - _ => None, - } + case.fixture + .read_scope("scope") + .or_else(|| case.fixture.read_scope("scp")) } fn unique(values: Vec) -> UniqueList { diff --git a/crates/registry-mcp-edge/src/token_characterisation.rs b/crates/registry-mcp-edge/src/token_characterisation.rs index d9f1346988..0d8bbcc327 100644 --- a/crates/registry-mcp-edge/src/token_characterisation.rs +++ b/crates/registry-mcp-edge/src/token_characterisation.rs @@ -32,7 +32,7 @@ use zeroize::Zeroizing; use crate::{ inbound::require_caller, token_verifier, AccessTokenAlgorithm, RateLimitOptions, - ResourceServer, ResourceServerOptions, TokenBucketOptions, + ResourceServer, ResourceServerError, ResourceServerOptions, TokenBucketOptions, }; const ISSUER: &str = "https://issuer.example.test"; @@ -53,10 +53,7 @@ fn client_of(fixture: &TokenFixture) -> Option { } fn first_scope(fixture: &TokenFixture) -> Option { - literal(fixture, "scope")? - .split_whitespace() - .next() - .map(str::to_owned) + fixture.read_scope("scope") } /// The algorithm the fixture declares, when the edge can be configured with @@ -113,24 +110,27 @@ async fn observe(case: &FixtureCase) -> Outcome { let hasher = AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![5; 32])) .expect("audit profile") .key_hasher(); - let server = Arc::new( - ResourceServer::new( - &options, - token_verifier(&options, fetcher_for(case)), - hasher, - RateLimitOptions { - per_principal: TokenBucketOptions { - requests_per_minute: 60, - burst: 1000, - }, - per_client: TokenBucketOptions { - requests_per_minute: 60, - burst: 1000, - }, + let server = match ResourceServer::new( + &options, + token_verifier(&options, fetcher_for(case)), + hasher, + RateLimitOptions { + per_principal: TokenBucketOptions { + requests_per_minute: 60, + burst: 1000, }, - ) - .expect("the resource server builds"), - ); + per_client: TokenBucketOptions { + requests_per_minute: 60, + burst: 1000, + }, + }, + ) { + Ok(server) => Arc::new(server), + // The edge serves one MCP path, so an audience that is not an `/mcp` + // URL cannot be configured. + Err(ResourceServerError::Resource) => return Outcome::None, + Err(error) => panic!("the resource server builds: {error:?}"), + }; let router = Router::new() .route("/mcp", post(|| async { "ok" })) .layer(axum::middleware::from_fn_with_state(server, require_caller)); diff --git a/crates/registry-messaging/tests/token_characterisation.rs b/crates/registry-messaging/tests/token_characterisation.rs index b1808a6c6c..275997689c 100644 --- a/crates/registry-messaging/tests/token_characterisation.rs +++ b/crates/registry-messaging/tests/token_characterisation.rs @@ -68,17 +68,6 @@ fn scope_claim(case: &FixtureCase) -> &'static str { } } -/// The first scope the fixture carries in the claim the configuration names. -fn read_scope(case: &FixtureCase, claim: &str) -> String { - match case.fixture.claims.get(claim) { - Some(ClaimValue::Literal(Value::String(text))) => text.split_whitespace().next(), - Some(ClaimValue::Literal(Value::Array(items))) => items.first().and_then(Value::as_str), - _ => None, - } - .unwrap_or(PLACEHOLDER_SCOPE) - .to_owned() -} - fn write_private(path: &Path, bytes: &[u8]) { fs::write(path, bytes).expect("write a private file"); fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("restrict the file"); @@ -135,7 +124,10 @@ async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { &serde_json::to_vec(&static_key_set(&case.jwks)).expect("a key set"), ); let claim = scope_claim(&case); - let scope = read_scope(&case, claim); + let scope = case + .fixture + .read_scope(claim) + .unwrap_or_else(|| PLACEHOLDER_SCOPE.to_owned()); let runtime_path = root.path().join("runtime.json"); fs::write( &runtime_path, diff --git a/crates/registry-platform-testing/src/token_fixtures.rs b/crates/registry-platform-testing/src/token_fixtures.rs index f0e47e53b2..a452e8b64a 100644 --- a/crates/registry-platform-testing/src/token_fixtures.rs +++ b/crates/registry-platform-testing/src/token_fixtures.rs @@ -282,7 +282,37 @@ struct RawHeader { kid: Value, } +/// OpenID Connect scopes. They select a claim set for the person. No product +/// profile requires one of them as a permission. +const OPENID_CONNECT_SCOPES: [&str; 6] = [ + "openid", + "profile", + "email", + "address", + "phone", + "offline_access", +]; + impl TokenFixture { + /// The first value of the claim `claim` that is not an OpenID Connect + /// scope: a space-separated string, or the first string of an array. `None` + /// when the claim is absent or holds only OpenID Connect scopes. + #[must_use] + pub fn read_scope(&self, claim: &str) -> Option { + match self.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => text + .split_whitespace() + .find(|scope| !OPENID_CONNECT_SCOPES.contains(scope)) + .map(str::to_owned), + Some(ClaimValue::Literal(Value::Array(items))) => items + .iter() + .filter_map(Value::as_str) + .find(|scope| !OPENID_CONNECT_SCOPES.contains(scope)) + .map(str::to_owned), + _ => None, + } + } + /// Parse and validate one fixture file. `file_stem` is the file name without /// its extension and must equal the fixture's `id`. pub fn parse(file_stem: &str, text: &str) -> Result { @@ -890,6 +920,18 @@ impl ProductReport { /// Panics, listing each differing row, if any row mismatched. pub fn assert_matches(&self) { let mismatches = self.mismatches(); + for row in self + .rows + .iter() + .filter(|row| row.comparison == Comparison::Unresolved) + { + if let Some(observed) = &row.observed { + eprintln!( + "unresolved {} / {} / {:?} / {:?}: observed {observed}", + self.product, row.fixture, row.against, row.configuration + ); + } + } assert!( mismatches.is_empty(), "{} rows of `{}` differ from expected.yaml:\n{}", diff --git a/crates/registry-platform-testing/tests/token_fixtures.rs b/crates/registry-platform-testing/tests/token_fixtures.rs index a406db43fa..4e03790d8c 100644 --- a/crates/registry-platform-testing/tests/token_fixtures.rs +++ b/crates/registry-platform-testing/tests/token_fixtures.rs @@ -66,6 +66,34 @@ fn parse_error(extra: Value) -> String { .to_string() } +fn fixture_with_claims(claims: Value) -> TokenFixture { + let mut full = json!({ + "iss": { "bind": "issuer" }, + "aud": { "bind": "audience" }, + "sub": "subject-1", + "iat": { "offsetSeconds": 0 }, + "exp": { "offsetSeconds": 300 } + }); + for (key, value) in claims.as_object().expect("claims is an object") { + full[key] = value.clone(); + } + TokenFixture::parse("unit-fixture", &minimal_fixture(json!({ "claims": full }))) + .expect("the fixture parses") +} + +#[test] +fn read_scope_skips_openid_connect_scopes() { + let mixed = fixture_with_claims(json!({ "scope": "openid records:get" })); + assert_eq!(mixed.read_scope("scope").as_deref(), Some("records:get")); + let only_openid = fixture_with_claims(json!({ "scope": "openid email profile" })); + assert_eq!(only_openid.read_scope("scope"), None); + let none = fixture_with_claims(json!({})); + assert_eq!(none.read_scope("scope"), None); + let list = fixture_with_claims(json!({ "scp": ["openid", "records:get", "records:write"] })); + assert_eq!(list.read_scope("scp").as_deref(), Some("records:get")); + assert_eq!(list.read_scope("scope"), None); +} + // --------------------------------------------------------------------------- // The corpus as written // --------------------------------------------------------------------------- @@ -73,13 +101,13 @@ fn parse_error(extra: Value) -> String { #[test] fn every_fixture_loads_and_validates() { let corpus = corpus(); - assert_eq!(corpus.fixtures().len(), 21, "11 positive and 10 negative"); + assert_eq!(corpus.fixtures().len(), 29, "16 positive and 13 negative"); let positive = corpus .fixtures() .iter() .filter(|fixture| fixture.class == FixtureClass::Positive) .count(); - assert_eq!(positive, 11); + assert_eq!(positive, 16); let ids: BTreeSet<&str> = corpus.fixtures().iter().map(|f| f.id.as_str()).collect(); assert_eq!(ids.len(), corpus.fixtures().len(), "ids are unique"); } @@ -336,7 +364,7 @@ fn no_fixture_file_holds_a_private_jwk_member_or_a_live_looking_token() { }); checked += 1; } - assert_eq!(checked, 21); + assert_eq!(checked, 29); } fn walk(value: &Value, visit: &mut impl FnMut(&Value)) { diff --git a/crates/registry-scheduling/tests/token_characterisation.rs b/crates/registry-scheduling/tests/token_characterisation.rs index edcc9c3f08..75491bcd74 100644 --- a/crates/registry-scheduling/tests/token_characterisation.rs +++ b/crates/registry-scheduling/tests/token_characterisation.rs @@ -68,17 +68,6 @@ fn scope_claim(case: &FixtureCase) -> &'static str { } } -/// The first scope the fixture carries in the claim the configuration names. -fn read_scope(case: &FixtureCase, claim: &str) -> String { - match case.fixture.claims.get(claim) { - Some(ClaimValue::Literal(Value::String(text))) => text.split_whitespace().next(), - Some(ClaimValue::Literal(Value::Array(items))) => items.first().and_then(Value::as_str), - _ => None, - } - .unwrap_or(PLACEHOLDER_SCOPE) - .to_owned() -} - fn write_private(path: &Path, bytes: &[u8]) { fs::write(path, bytes).expect("write a private file"); fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("restrict the file"); @@ -115,7 +104,10 @@ async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { &serde_json::to_vec(&static_key_set(&case.jwks)).expect("a key set"), ); let claim = scope_claim(&case); - let scope = read_scope(&case, claim); + let scope = case + .fixture + .read_scope(claim) + .unwrap_or_else(|| PLACEHOLDER_SCOPE.to_owned()); let runtime_path = root.path().join("runtime.json"); fs::write( &runtime_path, diff --git a/products/platform/conformance/tokens/README.md b/products/platform/conformance/tokens/README.md index 7d9e118158..93f25febf0 100644 --- a/products/platform/conformance/tokens/README.md +++ b/products/platform/conformance/tokens/README.md @@ -22,7 +22,7 @@ A **negative** fixture is a token that every product must refuse, in every confi ## Providers covered -Keycloak, ThunderID, Microsoft Entra ID, Supabase Auth and eSignet. One fixture, `rstack-dev-run-user`, holds the shape the development runner signs. One fixture, `identity-only`, is a token built to carry identity and nothing else. +Keycloak, ThunderID, Microsoft Entra ID, Supabase Auth and eSignet. One fixture, `rstack-dev-run-user`, holds the shape the development runner signs. One fixture, `identity-only`, is a token built to carry identity and nothing else. Two fixtures, `esignet-standin-id-token` and `esignet-standin-access-token`, are tokens of a stand-in for eSignet that is a second ThunderID. They are not eSignet's own shape, which `esignet-id-token` and `esignet-access-token` take from eSignet's documentation. ## What a fixture file holds @@ -81,6 +81,7 @@ A corpus test fails on any string shaped like a compact JWT, and on any private Every fixture states its source in `source.basis`. - `observed` with `observedFrom: capture`. The token was issued by a running provider. The fixture names the provider version, the container image digest, and the capture file. Only claim names, header members and value types were kept. +- `observed` with `observedFrom: issuer`. The token was issued by a running provider, and no image digest or capture file was kept. The fixture names the provider version, the date and a note on what was kept. Header members, claim names and value types are the observed ones. Claim values are synthetic. - `observed` with `observedFrom: code`. The shape was read from the code that signs it. - `documentation`. The shape comes from the provider's public documentation. The fixture names the page. Replace a documentation fixture with an observed one as soon as you can capture a token. - `constructed`. The token was built on purpose and the fixture says why. diff --git a/products/platform/conformance/tokens/expected.yaml b/products/platform/conformance/tokens/expected.yaml index 8e079989fd..35c558275b 100644 --- a/products/platform/conformance/tokens/expected.yaml +++ b/products/platform/conformance/tokens/expected.yaml @@ -107,6 +107,21 @@ rows: render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } + - fixture: thunderid-client-credentials + against: human-only-profile + configuration: recipe + products: + breg: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } + casework: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } + messaging: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } + scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } + documents: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } + coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence: { main: refused/claims, basis: observed, target: refused/profile, changedBy: M7, landed: false } + render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - fixture: keycloak-user-access against: plain-read configuration: default @@ -347,21 +362,6 @@ rows: render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } - - fixture: thunderid-client-credentials - against: human-only-profile - configuration: recipe - products: - breg: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } - casework: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } - messaging: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } - scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } - documents: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } - coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - evidence: { main: refused/claims, basis: observed, target: refused/profile, changedBy: M7, landed: false } - render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - fixture: keycloak-client-credentials against: human-only-profile configuration: recipe @@ -602,3 +602,214 @@ rows: render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: thunderid-exchanged-holder + against: plain-read + configuration: default + products: + breg: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "a token with no actor kind passes authentication as unspecified. The audience, scope claim and client rule are issuer-block lines. The holder profile limits rows by holder_ref, and no national claim is passed through" } + casework: { main: refused/audience, basis: observed, target: admitted, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } + messaging: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: none, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product"} + scheduling: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } + documents: { main: refused/audience, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided in M7" } + coordinator: { main: refused/audience, basis: observed, target: admitted, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } + adapter: { main: refused/audience, basis: observed, target: admitted, changedBy: none, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product"} + evidence: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } + render: { main: refused/audience, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: refused/audience, basis: observed, target: admitted, changedBy: none, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product"} + evidence-oid4vci: { main: refused/audience, basis: observed, target: admitted, changedBy: none, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product"} + - fixture: thunderid-exchanged-holder + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "a token with no actor kind passes authentication as unspecified. The audience, scope claim and client rule are issuer-block lines. The holder profile limits rows by holder_ref, and no national claim is passed through" } + casework: { main: admitted, basis: observed, target: admitted, changedBy: none } + messaging: { main: admitted/unspecified, basis: observed, target: admitted/unspecified, changedBy: none } + scheduling: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + documents: { main: refused/profile, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided in M7" } + coordinator: { main: admitted, basis: observed, target: admitted, changedBy: none } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: none, basis: observed, target: admitted, changedBy: none, reason: "observed: the edge serves one MCP path, so the token's literal audience, which is not an /mcp URL, cannot be configured"} + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } + - fixture: thunderid-exchanged-holder-no-scope + against: plain-read + configuration: default + products: + breg: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + casework: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + documents: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries no scope claim", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence-oid4vci: { main: admitted, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "no result is defined yet for a token that carries no scope claim" } + - fixture: thunderid-exchanged-holder-no-scope + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + casework: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + documents: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } + evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries no scope claim", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + mcp-edge: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + - fixture: esignet-standin-id-token + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: esignet-standin-access-token + against: plain-read + configuration: default + products: + breg: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + casework: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + messaging: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + scheduling: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + documents: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + coordinator: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + adapter: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + evidence: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + render: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + mcp-edge: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + evidence-oid4vci: { main: refused/issuer, basis: observed, target: refused/issuer, changedBy: none } + - fixture: thunderid-refresh-token + against: plain-read + configuration: default + products: + breg: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + casework: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + messaging: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + scheduling: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + documents: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + coordinator: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + adapter: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + render: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + mcp-edge: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + evidence-oid4vci: { main: refused/token-type, basis: observed, target: refused/token-type, changedBy: none } + - fixture: thunderid-user-access-attribute-claims + against: plain-read + configuration: default + products: + breg: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none, reason: "observed in the characterisation run: the cause was not traced", targetReason: "authority carried outside scope is not read" } + casework: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + messaging: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + scheduling: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + documents: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + coordinator: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none, targetReason: "this check requires no scope, and authority carried outside scope is not read" } + evidence: { main: refused/claims, basis: observed, target: refused/claims, changedBy: none, targetReason: "authority carried outside scope is not read" } + render: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + mcp-edge: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none, targetReason: "this check requires no scope, and authority carried outside scope is not read" } + - fixture: thunderid-user-access-attribute-claims + against: plain-read + configuration: recipe + products: + breg: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none, reason: "observed in the characterisation run: the cause was not traced", targetReason: "authority carried outside scope is not read" } + casework: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + messaging: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + scheduling: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + documents: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + coordinator: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none, targetReason: "this check requires no scope, and authority carried outside scope is not read" } + evidence: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + render: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + mcp-edge: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + evidence-oid4vci: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "authority carried outside scope is not read" } + + - fixture: thunderid-client-credentials-attribute-claims + against: plain-read + configuration: default + products: + breg: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none, targetReason: "authority carried outside scope is not read" } + casework: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + messaging: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + scheduling: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + documents: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + coordinator: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none, targetReason: "this check requires no scope, and authority carried outside scope is not read" } + evidence: { main: refused/claims, basis: observed, target: refused/claims, changedBy: none, targetReason: "authority carried outside scope is not read" } + render: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + mcp-edge: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none, targetReason: "this check requires no scope, and authority carried outside scope is not read" } + - fixture: thunderid-client-credentials-attribute-claims + against: plain-read + configuration: recipe + products: + breg: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none, targetReason: "authority carried outside scope is not read" } + casework: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + messaging: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + scheduling: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + documents: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + coordinator: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none, targetReason: "this check requires no scope, and authority carried outside scope is not read" } + evidence: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + render: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + mcp-edge: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + evidence-oid4vci: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "authority carried outside scope is not read" } + - fixture: thunderid-user-access-identity-only + against: plain-read + configuration: default + products: + breg: { main: refused/claims, basis: observed, target: refused/claims, changedBy: none, targetReason: "the token proves identity only" } + casework: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "the token proves identity only" } + messaging: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } + scheduling: { main: refused/claims, basis: observed, target: refused/claims, changedBy: none, targetReason: "the token proves identity only" } + documents: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } + coordinator: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "the token proves identity only" } + adapter: { main: admitted, basis: observed, target: admitted, changedBy: none, targetReason: "this check requires no scope and no actor kind" } + evidence: { main: refused/claims, basis: observed, target: refused/claims, changedBy: none, targetReason: "the token proves identity only" } + render: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, targetReason: "the token proves identity only" } + mcp-edge: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } + evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none, targetReason: "this check requires no scope and no actor kind" } + - fixture: thunderid-user-access-identity-only + against: plain-read + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } + casework: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } + messaging: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } + scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } + documents: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } + coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } + adapter: { main: admitted, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } + evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } + mcp-edge: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } + evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } + - fixture: thunderid-user-access-identity-only + against: human-only-profile + configuration: recipe + products: + breg: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "decided with the actor kind an operator declares for the client (M7)" } + casework: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client (M7)" } + messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client (M7)" } + scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } + documents: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client (M7)" } + coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client (M7)" } + render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } + evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } diff --git a/products/platform/conformance/tokens/fixtures/esignet-access-token.json b/products/platform/conformance/tokens/fixtures/esignet-access-token.json index 160500222d..97a2696b72 100644 --- a/products/platform/conformance/tokens/fixtures/esignet-access-token.json +++ b/products/platform/conformance/tokens/fixtures/esignet-access-token.json @@ -10,7 +10,7 @@ "basis": "documentation", "consultedOn": "2026-11-27", "url": "https://docs.esignet.io/home/esignet-2.x/readme/standards.md", - "note": "eSignet 2.x documentation, no lab run. The access token follows RFC 9068 with sub, iss, aud, exp, iat, client_id and scope. The header typ is not stated. at+jwt is inferred from the RFC and is not documented." + "note": "eSignet 2.x documentation. The shape is from documentation and was not observed. The access token follows RFC 9068 with sub, iss, aud, exp, iat, client_id and scope. The header typ is not stated. at+jwt is inferred from the RFC and is not documented." }, "header": { "alg": "RS256", diff --git a/products/platform/conformance/tokens/fixtures/esignet-id-token.json b/products/platform/conformance/tokens/fixtures/esignet-id-token.json index 46f1c2ac3b..3e250c0ebc 100644 --- a/products/platform/conformance/tokens/fixtures/esignet-id-token.json +++ b/products/platform/conformance/tokens/fixtures/esignet-id-token.json @@ -10,7 +10,7 @@ "basis": "documentation", "consultedOn": "2026-11-27", "url": "https://docs.esignet.io/home/esignet-2.x/readme/standards.md", - "note": "eSignet 2.x documentation, no lab run. The ID token has iss, sub, aud (the relying party's client ID), exp, iat, auth_time, nonce, acr and at_hash. The header typ is not stated, so it is omitted." + "note": "eSignet 2.x documentation. The shape is from documentation and was not observed. The ID token has iss, sub, aud (the relying party's client ID), exp, iat, auth_time, nonce, acr and at_hash. The header typ is not stated, so it is omitted." }, "header": { "alg": "RS256", diff --git a/products/platform/conformance/tokens/fixtures/esignet-standin-access-token.json b/products/platform/conformance/tokens/fixtures/esignet-standin-access-token.json new file mode 100644 index 0000000000..7fbba94456 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/esignet-standin-access-token.json @@ -0,0 +1,48 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "esignet-standin-access-token", + "class": "negative", + "provider": "thunderid", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key. Token of the stand-in for eSignet, client portal." + }, + "header": { + "alg": "ES256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "aci": "synthetic-aci", + "aud": "portal", + "client_id": "portal", + "exp": { + "offsetSeconds": 900 + }, + "grant_type": "authorization_code", + "iat": { + "offsetSeconds": 0 + }, + "iss": "https://standin.example.test", + "jti": "synthetic-jti-0042", + "nbf": { + "offsetSeconds": 0 + }, + "scope": "openid email profile", + "sub": "00000000-0000-4000-8000-000000000001", + "tfid": "synthetic-tfid" + }, + "omits": [ + "azp", + "registry_actor_kind" + ], + "notes": "This token is from a second ThunderID that stands in for eSignet. Its tokens are the subject of the exchange and never reach a product. The documented eSignet fixtures (esignet-id-token, esignet-access-token) keep eSignet's own shape from its documentation. The issuer is a literal. A product trusts one configured issuer." +} diff --git a/products/platform/conformance/tokens/fixtures/esignet-standin-id-token.json b/products/platform/conformance/tokens/fixtures/esignet-standin-id-token.json new file mode 100644 index 0000000000..a4148c7d33 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/esignet-standin-id-token.json @@ -0,0 +1,54 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "esignet-standin-id-token", + "class": "negative", + "provider": "thunderid", + "kind": "user-id", + "tokenUse": "id", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key. Token of the stand-in for eSignet, client portal." + }, + "header": { + "alg": "ES256", + "typ": "JWT", + "kid": { + "generated": true + } + }, + "claims": { + "aud": "portal", + "auth_time": { + "offsetSeconds": 0 + }, + "exp": { + "offsetSeconds": 900 + }, + "holder_ref": "holder-0002", + "iat": { + "offsetSeconds": 0 + }, + "individual_id": "holder-0001", + "iss": "https://standin.example.test", + "jti": "synthetic-jti-0041", + "jurisdiction": "north-synthetic", + "name": "Journey User", + "nbf": { + "offsetSeconds": 0 + }, + "registry_actor_kind": "service", + "registry_scope": "records:get", + "role": "service_role", + "sub": "00000000-0000-4000-8000-000000000001" + }, + "omits": [ + "scope", + "client_id", + "azp" + ], + "notes": "This token is from a second ThunderID that stands in for eSignet. Its tokens are the subject of the exchange and never reach a product. The documented eSignet fixtures (esignet-id-token, esignet-access-token) keep eSignet's own shape from its documentation. The ID token carries registry-shaped claims. The lifetime is a test choice." +} diff --git a/products/platform/conformance/tokens/fixtures/supabase-api-key-anon.json b/products/platform/conformance/tokens/fixtures/supabase-api-key-anon.json index 2bdf6fb3d9..72fabae497 100644 --- a/products/platform/conformance/tokens/fixtures/supabase-api-key-anon.json +++ b/products/platform/conformance/tokens/fixtures/supabase-api-key-anon.json @@ -7,10 +7,11 @@ "tokenUse": "api-key", "subjectKind": "unspecified", "source": { - "basis": "documentation", - "consultedOn": "2026-11-27", - "url": "https://supabase.com/docs/guides/api/api-keys", - "note": "The page lists the legacy anon and service_role keys as long-lived JWTs and does not document their claims. The role claim is named on the JWT fields page. The claim set here is the minimum. Replace with an observed shape when one exists." + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "self-hosted Supabase stack", + "note": "Observed from a self-hosted Supabase Auth issuer on 27 November 2026, the legacy key. Claim values are synthetic. Signed by the corpus test key." }, "header": { "alg": "HS256", @@ -20,13 +21,14 @@ } }, "claims": { - "role": "anon", + "exp": { + "offsetSeconds": 157680000 + }, "iat": { "offsetSeconds": 0 }, - "exp": { - "offsetSeconds": 315360000 - } + "iss": "supabase", + "role": "anon" }, - "notes": "The expiry models a long-lived key, a test choice." + "notes": "The observed header has no kid. The corpus schema requires one, so the fixture carries a generated kid. The lifetime, five years, is the observed one. The asymmetric variant of the key (ES256, with a kid, same claims) was also observed and is not a separate fixture." } diff --git a/products/platform/conformance/tokens/fixtures/supabase-api-key-opaque.json b/products/platform/conformance/tokens/fixtures/supabase-api-key-opaque.json index 3c86ab043b..6d8580881b 100644 --- a/products/platform/conformance/tokens/fixtures/supabase-api-key-opaque.json +++ b/products/platform/conformance/tokens/fixtures/supabase-api-key-opaque.json @@ -7,10 +7,11 @@ "tokenUse": "api-key", "subjectKind": "unspecified", "source": { - "basis": "documentation", - "consultedOn": "2026-11-27", - "url": "https://supabase.com/docs/guides/api/api-keys", - "note": "Publishable and secret keys are short strings, not JWTs. The value is synthetic and not a key." + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "self-hosted Supabase stack", + "note": "Observed from a self-hosted Supabase Auth issuer on 27 November 2026: the publishable key is an opaque string of 46 characters and the secret key one of 41. The value here is synthetic, not a key, and has the publishable key's length." }, - "opaque": "sb_publishable_synthetic-test-value-not-a-key" + "opaque": "sb_publishable_synthetic-test-value-not-a-key0" } diff --git a/products/platform/conformance/tokens/fixtures/supabase-api-key-service-role.json b/products/platform/conformance/tokens/fixtures/supabase-api-key-service-role.json index 7c5a14d31f..6419288591 100644 --- a/products/platform/conformance/tokens/fixtures/supabase-api-key-service-role.json +++ b/products/platform/conformance/tokens/fixtures/supabase-api-key-service-role.json @@ -7,10 +7,11 @@ "tokenUse": "api-key", "subjectKind": "unspecified", "source": { - "basis": "documentation", - "consultedOn": "2026-11-27", - "url": "https://supabase.com/docs/guides/api/api-keys", - "note": "See supabase-api-key-anon." + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "self-hosted Supabase stack", + "note": "Observed from a self-hosted Supabase Auth issuer on 27 November 2026, the legacy key. Claim values are synthetic. Signed by the corpus test key." }, "header": { "alg": "HS256", @@ -20,13 +21,14 @@ } }, "claims": { - "role": "service_role", + "exp": { + "offsetSeconds": 157680000 + }, "iat": { "offsetSeconds": 0 }, - "exp": { - "offsetSeconds": 315360000 - } + "iss": "supabase", + "role": "service_role" }, - "notes": "The expiry models a long-lived key, a test choice." + "notes": "The observed header has no kid. The corpus schema requires one, so the fixture carries a generated kid. The lifetime, five years, is the observed one. The asymmetric variant of the key (ES256, with a kid, same claims) was also observed and is not a separate fixture." } diff --git a/products/platform/conformance/tokens/fixtures/supabase-user-access.json b/products/platform/conformance/tokens/fixtures/supabase-user-access.json index d0f9d216e1..098c60439b 100644 --- a/products/platform/conformance/tokens/fixtures/supabase-user-access.json +++ b/products/platform/conformance/tokens/fixtures/supabase-user-access.json @@ -7,10 +7,11 @@ "tokenUse": "access", "subjectKind": "user", "source": { - "basis": "documentation", - "consultedOn": "2026-11-27", - "url": "https://supabase.com/docs/guides/auth/jwt-fields", - "note": "Header and claim names from the JWT fields page. The signing keys page lists ES256 as an asymmetric option, which is the one a verifier can check from a key set. Replace with an observed shape when one exists." + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "self-hosted Supabase stack", + "note": "Observed from a self-hosted Supabase Auth issuer on 27 November 2026, password grant. Claim values are synthetic. Signed by the corpus test key. This fixture holds the stock shape." }, "header": { "alg": "ES256", @@ -20,13 +21,6 @@ } }, "claims": { - "iss": { - "bind": "issuer" - }, - "aud": "authenticated", - "sub": "00000000-0000-4000-8000-000000000001", - "role": "authenticated", - "session_id": "synthetic-session", "aal": "aal1", "amr": [ { @@ -34,15 +28,24 @@ "timestamp": 1700000000 } ], - "is_anonymous": false, + "app_metadata": {}, + "aud": "authenticated", "email": "journey-user@example.test", - "phone": "", + "exp": { + "offsetSeconds": 3600 + }, "iat": { "offsetSeconds": 0 }, - "exp": { - "offsetSeconds": 3600 - } + "is_anonymous": false, + "iss": { + "bind": "issuer" + }, + "phone": "", + "role": "authenticated", + "session_id": "synthetic-session", + "sub": "00000000-0000-4000-8000-000000000001", + "user_metadata": {} }, "omits": [ "scope", @@ -51,5 +54,5 @@ "azp", "registry_actor_kind" ], - "notes": "The documentation defines no scope claim and no client claim for a user access token." + "notes": "The token carries no scope claim and no client claim. The lifetime, 3600 seconds, is the observed one." } diff --git a/products/platform/conformance/tokens/fixtures/thunderid-client-credentials-attribute-claims.json b/products/platform/conformance/tokens/fixtures/thunderid-client-credentials-attribute-claims.json new file mode 100644 index 0000000000..fdee06d2be --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-client-credentials-attribute-claims.json @@ -0,0 +1,52 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-client-credentials-attribute-claims", + "class": "positive", + "provider": "thunderid", + "kind": "client-access", + "tokenUse": "access", + "subjectKind": "service", + "source": { + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key. The client-credentials token carries no scope claim, and the registry attributes are copied into it." + }, + "header": { + "alg": "ES256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "aud": { + "bind": "audience" + }, + "client_id": "journey-service", + "exp": { + "offsetSeconds": 300 + }, + "grant_type": "client_credentials", + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0002", + "nbf": { + "offsetSeconds": 0 + }, + "registry_actor_kind": "service", + "registry_scope": "records:get", + "sub": "00000000-0000-4000-8000-000000000002" + }, + "omits": [ + "azp", + "scope", + "role" + ], + "notes": "The authority is in registry_scope and registry_actor_kind. There is no scope claim. The lifetime, 300 seconds, is the observed one." +} diff --git a/products/platform/conformance/tokens/fixtures/thunderid-exchanged-holder-no-scope.json b/products/platform/conformance/tokens/fixtures/thunderid-exchanged-holder-no-scope.json new file mode 100644 index 0000000000..69d8b47324 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-exchanged-holder-no-scope.json @@ -0,0 +1,56 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-exchanged-holder-no-scope", + "class": "positive", + "provider": "thunderid", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key. Form requested with neither resource nor scope." + }, + "header": { + "alg": "ES256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "aud": { + "bind": "audience" + }, + "client_id": "portal-exchange", + "exp": { + "offsetSeconds": 900 + }, + "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", + "holder_ref": "holder-0001", + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0032", + "nbf": { + "offsetSeconds": 0 + }, + "sub": "00000000-0000-4000-8000-000000000001" + }, + "omits": [ + "azp", + "scope", + "scp", + "registry_scope", + "registry_actor_kind", + "jurisdiction", + "role", + "individual_id" + ], + "notes": "RFC 8693 exchange, subject token the stand-in's ID token. ThunderID keeps the national subject as sub and replaces the mapped holder_ref. Every authority claim of the national token is dropped, and registry_actor_kind cannot be supplied on an exchange. The grant_type value is the RFC 8693 grant type, inferred: only the claim name was observed, not its value. The lifetime is 900 seconds, observed. aud falls back to the client's default audience, so it binds to the product's audience. The token grants no permission and carries no scope claim. It is positive, as the other scope-less fixtures are, because no result is defined yet for a token without a scope claim." +} diff --git a/products/platform/conformance/tokens/fixtures/thunderid-exchanged-holder.json b/products/platform/conformance/tokens/fixtures/thunderid-exchanged-holder.json new file mode 100644 index 0000000000..17b652e0bf --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-exchanged-holder.json @@ -0,0 +1,53 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-exchanged-holder", + "class": "positive", + "provider": "thunderid", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key. Form requested with a resource and scope." + }, + "header": { + "alg": "ES256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "aud": "https://resource.example.test", + "client_id": "portal-exchange", + "exp": { + "offsetSeconds": 900 + }, + "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", + "holder_ref": "holder-0001", + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0031", + "nbf": { + "offsetSeconds": 0 + }, + "scope": "records:get", + "sub": "00000000-0000-4000-8000-000000000001" + }, + "omits": [ + "azp", + "registry_actor_kind", + "registry_scope", + "jurisdiction", + "role", + "individual_id" + ], + "notes": "RFC 8693 exchange, subject token the stand-in's ID token. ThunderID keeps the national subject as sub and replaces the mapped holder_ref. Every authority claim of the national token is dropped, and registry_actor_kind cannot be supplied on an exchange. The grant_type value is the RFC 8693 grant type, inferred: only the claim name was observed, not its value. The lifetime is 900 seconds, observed. aud is the exchange resource server, an absolute URI that a resource-bearing request needs. The scope claim holds the granted permission, from the connection's authorization mapping. A product whose audience is not that URI needs a configured audience line." +} diff --git a/products/platform/conformance/tokens/fixtures/thunderid-id-token.json b/products/platform/conformance/tokens/fixtures/thunderid-id-token.json index de7f635201..66e958fe42 100644 --- a/products/platform/conformance/tokens/fixtures/thunderid-id-token.json +++ b/products/platform/conformance/tokens/fixtures/thunderid-id-token.json @@ -8,14 +8,13 @@ "subjectKind": "user", "source": { "basis": "observed", - "observedFrom": "capture", + "observedFrom": "issuer", "observedOn": "2026-11-27", - "version": "1.0.1", - "image": "ghcr.io/thunder-id/thunderid:1.0.1@sha256:d3c0613ff447a551fd440768a15bdfb6668948e80809cbb50f82d6752f22ab3e", - "captureFile": "thunderid-user-id.json" + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key." }, "header": { - "alg": "RS256", + "alg": "ES256", "typ": "JWT", "kid": { "generated": true @@ -26,6 +25,8 @@ "auth_time": { "offsetSeconds": 0 }, + "email": "journey-user@example.test", + "email_verified": true, "exp": { "offsetSeconds": 3600 }, @@ -36,16 +37,18 @@ "bind": "issuer" }, "jti": "synthetic-jti-0021", + "name": "Journey User", "nbf": { "offsetSeconds": 0 }, - "nonce": "synthetic-nonce", "sub": "00000000-0000-4000-8000-000000000001" }, "omits": [ "scope", "client_id", - "azp" + "azp", + "nonce", + "registry_actor_kind" ], - "notes": "aud is the client, as in the capture. The lifetime is a test choice." + "notes": "aud is the client, as observed. The lifetime is a test choice, since none was observed for an ID token." } diff --git a/products/platform/conformance/tokens/fixtures/thunderid-refresh-token.json b/products/platform/conformance/tokens/fixtures/thunderid-refresh-token.json new file mode 100644 index 0000000000..e0d5fb6c8a --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-refresh-token.json @@ -0,0 +1,56 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-refresh-token", + "class": "negative", + "provider": "thunderid", + "kind": "user-refresh", + "tokenUse": "refresh", + "subjectKind": "unspecified", + "source": { + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key. ThunderID's refresh token is a JWT, not an opaque string." + }, + "header": { + "alg": "ES256", + "typ": "rt+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "access_token_aud": [ + "licence-registry" + ], + "access_token_sub": "00000000-0000-4000-8000-000000000001", + "aci": "synthetic-aci", + "aud": { + "bind": "issuer" + }, + "exp": { + "offsetSeconds": 86400 + }, + "grant_type": "authorization_code", + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0051", + "nbf": { + "offsetSeconds": 0 + }, + "scope": "openid email profile", + "sub": "journey-app", + "tfid": "synthetic-tfid" + }, + "omits": [ + "client_id", + "azp", + "registry_actor_kind" + ], + "notes": "sub is the client, and the user is in access_token_sub. aud is the issuer. The lifetime, 86400 seconds, is the observed one. The grant_type value is inferred, only the claim name was observed." +} diff --git a/products/platform/conformance/tokens/fixtures/thunderid-user-access-attribute-claims.json b/products/platform/conformance/tokens/fixtures/thunderid-user-access-attribute-claims.json new file mode 100644 index 0000000000..d151c41e35 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-user-access-attribute-claims.json @@ -0,0 +1,56 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-user-access-attribute-claims", + "class": "positive", + "provider": "thunderid", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key. Shape with every authority-bearing claim present." + }, + "header": { + "alg": "ES256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "aci": "synthetic-aci", + "aud": { + "bind": "audience" + }, + "client_id": "journey-app", + "exp": { + "offsetSeconds": 900 + }, + "grant_type": "authorization_code", + "holder_ref": "holder-0001", + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0061", + "jurisdiction": "north-synthetic", + "nbf": { + "offsetSeconds": 0 + }, + "registry_actor_kind": "human", + "registry_scope": "records:get records:write", + "role": "authenticated", + "scope": "openid email profile", + "sub": "00000000-0000-4000-8000-000000000001", + "tfid": "synthetic-tfid" + }, + "omits": [ + "azp" + ], + "notes": "A ThunderID person access token whose authority-bearing claims (registry_scope, registry_actor_kind, jurisdiction, holder_ref, role) are carried as user-attribute claims rather than in scope. scope holds the OpenID Connect scopes only." +} diff --git a/products/platform/conformance/tokens/fixtures/thunderid-user-access-identity-only.json b/products/platform/conformance/tokens/fixtures/thunderid-user-access-identity-only.json new file mode 100644 index 0000000000..fbe2cc8075 --- /dev/null +++ b/products/platform/conformance/tokens/fixtures/thunderid-user-access-identity-only.json @@ -0,0 +1,54 @@ +{ + "schema": "registry.token-fixture/v1", + "id": "thunderid-user-access-identity-only", + "class": "positive", + "provider": "thunderid", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { + "basis": "observed", + "observedFrom": "issuer", + "observedOn": "2026-11-27", + "version": "ThunderID 1.1.0", + "note": "Observed from a ThunderID 1.1.0 issuer on 27 November 2026. Authorization code with PKCE, public client, a person with no grants. Header members and claim names are the observed ones. Claim values are synthetic. Signed by the corpus test key." + }, + "header": { + "alg": "ES256", + "typ": "at+jwt", + "kid": { + "generated": true + } + }, + "claims": { + "aci": "synthetic-aci", + "aud": { + "bind": "audience" + }, + "client_id": "journey-app", + "exp": { + "offsetSeconds": 900 + }, + "grant_type": "authorization_code", + "iat": { + "offsetSeconds": 0 + }, + "iss": { + "bind": "issuer" + }, + "jti": "synthetic-jti-0071", + "nbf": { + "offsetSeconds": 0 + }, + "role": "authenticated", + "scope": "openid email profile", + "sub": "00000000-0000-4000-8000-000000000001", + "tfid": "synthetic-tfid" + }, + "omits": [ + "azp", + "registry_actor_kind", + "registry_scope" + ], + "notes": "scope holds the OpenID Connect scopes only. The token carries no registry authority claim. The lifetime, 900 seconds, is the observed one." +} diff --git a/products/platform/conformance/tokens/token-fixture.schema.json b/products/platform/conformance/tokens/token-fixture.schema.json index 20e7d65e01..5f0f80ca88 100644 --- a/products/platform/conformance/tokens/token-fixture.schema.json +++ b/products/platform/conformance/tokens/token-fixture.schema.json @@ -57,6 +57,17 @@ "required": ["basis", "observedFrom", "observedOn", "version", "image", "captureFile"], "additionalProperties": false }, + { + "properties": { + "basis": { "const": "observed" }, + "observedFrom": { "const": "issuer" }, + "observedOn": { "type": "string", "format": "date" }, + "version": { "type": "string", "minLength": 1 }, + "note": { "type": "string", "minLength": 1 } + }, + "required": ["basis", "observedFrom", "observedOn", "version", "note"], + "additionalProperties": false + }, { "properties": { "basis": { "const": "observed" }, From b237ba6ec83d15374d0263ee820ae873635e9f0b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 03:23:16 +0100 Subject: [PATCH 017/136] feat(scheduling): add schedulingctl provision for roles and the database An operator created the Scheduling roles and database by hand from the operations page. schedulingctl provision now creates them from the runtime file's two URLs through the shared provisioning plan, as a non-superuser administrator, idempotently, or prints the SQL with --print-sql. It reads the runtime file the way apply does, so it runs after the policy is packaged. Signed-off-by: Jeremi Joslin --- Cargo.lock | 2 + crates/registry-schedulingctl/Cargo.toml | 7 + crates/registry-schedulingctl/src/lib.rs | 28 +- .../registry-schedulingctl/src/provision.rs | 104 +++++++ .../tests/provision_cli.rs | 212 ++++++++++++++ .../tests/provision_postgres.rs | 271 ++++++++++++++++++ .../src/content/docs/operate/scheduling.mdx | 97 ++++--- products/scheduling/AGENTS.md | 4 + 8 files changed, 689 insertions(+), 36 deletions(-) create mode 100644 crates/registry-schedulingctl/src/provision.rs create mode 100644 crates/registry-schedulingctl/tests/provision_cli.rs create mode 100644 crates/registry-schedulingctl/tests/provision_postgres.rs diff --git a/Cargo.lock b/Cargo.lock index 34113156ee..271af8ed2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8528,6 +8528,7 @@ dependencies = [ "registry-platform-audit", "registry-platform-buildinfo", "registry-platform-config", + "registry-platform-provision", "registry-platform-yaml", "registry-scheduling", "registry-scheduling-core", @@ -8537,6 +8538,7 @@ dependencies = [ "tokio", "tokio-postgres", "uuid", + "zeroize", ] [[package]] diff --git a/crates/registry-schedulingctl/Cargo.toml b/crates/registry-schedulingctl/Cargo.toml index 1a3502b187..f27ef4de92 100644 --- a/crates/registry-schedulingctl/Cargo.toml +++ b/crates/registry-schedulingctl/Cargo.toml @@ -26,6 +26,7 @@ registry-cli-api.workspace = true registry-platform-audit.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true registry-scheduling.workspace = true registry-scheduling-core.workspace = true @@ -34,6 +35,7 @@ serde_json.workspace = true tempfile.workspace = true tokio = { workspace = true, features = ["rt"] } uuid.workspace = true +zeroize.workspace = true [dev-dependencies] # The database suites reach the runtime's plaintext test connection through @@ -42,6 +44,7 @@ uuid.workspace = true # holding both crates, and the runtime's own database suite would then be # compiled and run by shards that have no server to offer it. chrono.workspace = true +registry-platform-provision = { workspace = true, features = ["test-support"] } tokio-postgres.workspace = true [[test]] @@ -55,3 +58,7 @@ required-features = ["postgres-test"] [[test]] name = "activation_postgres" required-features = ["postgres-test"] + +[[test]] +name = "provision_postgres" +required-features = ["postgres-test"] diff --git a/crates/registry-schedulingctl/src/lib.rs b/crates/registry-schedulingctl/src/lib.rs index e6c3251665..a668e0c9f4 100644 --- a/crates/registry-schedulingctl/src/lib.rs +++ b/crates/registry-schedulingctl/src/lib.rs @@ -5,7 +5,8 @@ //! checks every project file offline, and with `--runtime-config` the //! runtime file too, `test` replays every fixture offline, `explain` //! publishes what the runtime would serve, `package` writes the deployment -//! identity the runtime verifies, `plan`, `apply`, and `status` activate a +//! identity the runtime verifies, `provision` creates the roles and the +//! database the runtime file names, `plan`, `apply`, and `status` activate a //! verified package on a deployment's database and report its activation //! ledger, `records apply` performs the one attributable operator write of a //! deployment's live environment records, and `intents` reads the delivery @@ -14,6 +15,7 @@ pub mod activation; pub mod intents; mod project; +mod provision; pub mod records; mod report; mod selected_binary; @@ -73,6 +75,8 @@ enum Command { Package(PackageArgs), /// Report what `apply` would do to a deployment's database, writing nothing. Plan(ActivationArgs), + /// Create the roles and the database the runtime file names, or print the SQL. + Provision(registry_platform_provision::ProvisionArgs), /// Activate the verified package on a deployment's database. Apply(ApplyArgs), /// Report the active package and the activation ledger of a deployment's database. @@ -326,6 +330,7 @@ where Command::Serve(args) => { return serve(args, format, format_requested, stdout, stderr); } + Command::Provision(args) => return provision(&args, format), command => command, }; let command_name = command_path(&command); @@ -416,6 +421,7 @@ fn command_path(command: &Command) -> &'static str { Command::Explain(_) => "explain", Command::Package(_) => "package", Command::Plan(_) => "plan", + Command::Provision(_) => "provision", Command::Apply(_) => "apply", Command::Status(_) => "status", Command::Records(RecordsArgs { @@ -425,12 +431,32 @@ fn command_path(command: &Command) -> &'static str { } } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: ®istry_platform_provision::ProvisionArgs, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "schedulingctl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + shared, + provision::load, + ) +} + fn run(cli: Cli) -> Result { match cli.command { Command::Api(_) | Command::Connection { .. } => { unreachable!("API commands handle their output before report dispatch") } Command::Serve(_) => unreachable!("serve replaces the ctl process before report dispatch"), + Command::Provision(_) => { + unreachable!("provision writes its own report before report dispatch") + } Command::Init(args) => project::init(&args.project, &args.template), Command::Check(args) => { let checked = if args.runtime_config.is_some() { diff --git a/crates/registry-schedulingctl/src/provision.rs b/crates/registry-schedulingctl/src/provision.rs new file mode 100644 index 0000000000..ce31dd05fe --- /dev/null +++ b/crates/registry-schedulingctl/src/provision.rs @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `schedulingctl provision`: the shared command over Scheduling's +//! runtime file. The file's two database URLs name the roles, the database +//! and both passwords, so nothing is written twice. + +use std::path::Path; + +use registry_platform_config::describe_secret_failure; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use registry_scheduling::config::{startup_report, RuntimeConfig}; +use registry_scheduling_core::SCHEDULING_RUNTIME_KIND; +use zeroize::Zeroizing; + +/// Scheduling keeps its tables in `public`, handed to the migration +/// role, and needs no extension. +fn product() -> ProductDatabase { + ProductDatabase { + product: "scheduling", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } +} + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(SCHEDULING_RUNTIME_KIND.to_owned()); + Box::new(diagnostic) +} + +/// Reads the runtime file exactly as `apply` does and resolves the two +/// database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be resolved against the working directory" + .to_owned(), + "Pass --runtime-config as a path that exists.", + ) + })?; + let config = RuntimeConfig::load(&absolute).map_err(|error| { + match startup_report(&absolute, &error) + .and_then(|report| report.diagnostics().first().cloned()) + { + Some(diagnostic) => Box::new(diagnostic), + None => refused( + "config.refused", + "", + error.to_string(), + "Correct the runtime file, then run provision again.", + ), + } + })?; + let secrets = config.secret_providers.resolver().map_err(|error| { + refused( + "config.refused", + "/secretProviders", + error.to_string(), + "Correct secretProviders in the runtime file, then run provision again.", + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refused( + "config.refused", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; + let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let ca_pem = config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + Ok(ProvisionInput { + product: product(), + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-schedulingctl/tests/provision_cli.rs b/crates/registry-schedulingctl/tests/provision_cli.rs new file mode 100644 index 0000000000..2dd371aa18 --- /dev/null +++ b/crates/registry-schedulingctl/tests/provision_cli.rs @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `schedulingctl provision` without a database: print mode reads the runtime +//! file and writes the script without connecting or printing a password, and +//! the administrator flags refuse the combinations the shared command +//! refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file over a built package, whose secret files name a migration +/// and a runtime login on one server that does not exist, so a connection +/// attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!( + "postgresql://scheduling_migration:{MIGRATION_PASSWORD}@db.invalid:5432/scheduling" + ), + ), + ( + "runtime-database-url", + format!( + "postgresql://scheduling_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/scheduling" + ), + ), + ("audit-key", "0123456789abcdef0123456789abcdef".to_owned()), + ( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + // The loader verifies the package the file names, as `apply` does. + let project = directory.join("project"); + let package = directory.join("package"); + for arguments in [ + vec![ + "init", + project.to_str().unwrap(), + "--template", + "standalone-exact-time", + ], + vec![ + "package", + project.to_str().unwrap(), + "--output", + package.to_str().unwrap(), + ], + ] { + let output = ctl(&arguments); + assert_eq!(output.status.code(), Some(0), "{arguments:?}"); + } + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/scheduling/runtime/v1alpha1 +kind: SchedulingRuntimeConfig +package: + root: {package} +identity: + databaseId: registry-scheduling-ctl-test +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback +secretProviders: + file: + root: {secrets} +authentication: + oidc: + issuer: https://identity.example.test + audience: urn:example:scheduling + allowedClients: [scheduling-test-client] + jwksSource: + type: static + documentRef: secret:file/jwks.json +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url +taskGrantStatus: unchecked-final-fifteen-minutes +audit: + path: {audit} + hashKeyRef: secret:file/audit-key +retention: + receiptRetentionDays: 2 +", + package = package.display(), + secrets = secrets.display(), + audit = directory.join("audit.ndjson").display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_schedulingctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in ["scheduling_migration", "scheduling_runtime", "scheduling"] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "scheduling"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "scheduling"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } + + // The command's own flag, after the verb, selects the same report. + let after = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--format", + "json", + ]); + assert_eq!(after.status.code(), Some(0)); + assert_eq!(String::from_utf8(after.stdout).unwrap(), stdout); +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for arguments in [ + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "SCHEDULING_ADMIN_URL", + ], + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "SCHEDULING_ADMIN_URL", + ], + vec!["provision", "--runtime-config", &runtime], + ] { + let output = ctl(&arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty(), "{arguments:?}"); + } +} diff --git a/crates/registry-schedulingctl/tests/provision_postgres.rs b/crates/registry-schedulingctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..1cc5608403 --- /dev/null +++ b/crates/registry-schedulingctl/tests/provision_postgres.rs @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `schedulingctl provision` against a real server, then `apply` and the +//! runtime on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. The administrator sessions of this suite +//! use verified TLS, so the server must offer it. Without the variables the +//! test fails on the spot: a skipped database test is not database +//! verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::PathBuf; +use std::process::Command; +use std::time::Duration; + +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use serde_json::Value; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use uuid::Uuid; + +/// One deployment directory and the superuser session that creates the +/// roles `provision` is run from. +struct Deployment { + directory: tempfile::TempDir, + admin: tokio_postgres::Client, +} + +impl Deployment { + async fn new() -> Self { + let (url, ca_pem) = provision_test_env(); + let admin = connect_verified(&url, &ca_pem, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let deployment = Self { directory, admin }; + deployment.secret("audit-key", "0123456789abcdef0123456789abcdef"); + // The runtime verifies tokens against a static key set, so it starts + // without reaching the issuer. + deployment.secret( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + ); + deployment + } + + fn path(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + + fn runtime(&self) -> String { + self.path("runtime.yaml").display().to_string() + } + + /// Write or replace the secret file `name` with `value`. + fn secret(&self, name: &str, value: &str) { + let path = self.path("secrets").join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + + /// Write the runtime document over `package`, listening on `bind`, with + /// the database connections verified against the CA secret. + fn write_runtime(&self, package: &std::path::Path, bind: &str) { + let document = format!( + "\ +apiVersion: id.registrystack.org/formats/scheduling/runtime/v1alpha1 +kind: SchedulingRuntimeConfig +package: + root: {package} +identity: + databaseId: registry-scheduling-ctl-test +listener: + bind: {bind} + tlsTermination: development-loopback +secretProviders: + file: + root: {secrets} +authentication: + oidc: + issuer: https://identity.example.test + audience: urn:example:scheduling + allowedClients: [scheduling-test-client] + jwksSource: + type: static + documentRef: secret:file/jwks.json +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/postgres-ca.pem +taskGrantStatus: unchecked-final-fifteen-minutes +audit: + path: {audit} + hashKeyRef: secret:file/audit-key +retention: + receiptRetentionDays: 2 +", + package = package.display(), + secrets = self.path("secrets").display(), + audit = self.path("audit.ndjson").display(), + ); + std::fs::write(self.path("runtime.yaml"), document).unwrap(); + } +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&str]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_schedulingctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stdout))); + (output.status.code().unwrap(), report) +} + +/// Read one HTTP status code from `GET path`, or none when nothing answers. +async fn http_status(address: &str, path: &str) -> Option { + let mut stream = tokio::net::TcpStream::connect(address).await.ok()?; + stream + .write_all( + format!("GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await + .ok()?; + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.ok()?; + let text = String::from_utf8_lossy(&response); + text.split_whitespace().nth(1)?.parse().ok() +} + +/// `provision` as the operate page runs it: from the administrator URL of a +/// non-superuser that holds only `CREATEROLE` and `CREATEDB`, over a runtime +/// file whose two URLs name the roles and the database. `apply` then +/// activates the package over the migration credential, and the runtime +/// starts over the runtime credential and answers its readiness route. +#[tokio::test] +async fn provision_then_apply_then_serve_with_split_roles() { + let deployment = Deployment::new().await; + let project = deployment.path("project").display().to_string(); + let (code, report) = ctl(&["init", &project, "--template", "standalone-exact-time"]); + assert_eq!(code, 0, "{report:#}"); + let package = deployment.path("package"); + let (code, report) = ctl(&["package", &project, "--output", package.to_str().unwrap()]); + assert_eq!(code, 0, "{report:#}"); + + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let bind = format!("127.0.0.1:{port}"); + deployment.write_runtime(&package, &bind); + let runtime = deployment.runtime(); + + let (base_url, ca) = provision_test_env(); + deployment.secret("postgres-ca.pem", &String::from_utf8_lossy(&ca)); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let (owner, migration, runtime_role, database) = ( + format!("scheduling_owner_{suffix}"), + format!("scheduling_mig_{suffix}"), + format!("scheduling_rt_{suffix}"), + format!("scheduling_db_{suffix}"), + ); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let (owner_password, migration_password, runtime_password) = ( + password("owner"), + password("migration"), + password("runtime"), + ); + deployment + .admin + .batch_execute(&format!( + "CREATE ROLE {owner} LOGIN PASSWORD '{owner_password}' NOSUPERUSER CREATEROLE CREATEDB" + )) + .await + .unwrap(); + + let base = registry_platform_provision::admin_config(&base_url, Some(&ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, port) = (base.host(), base.port()); + let url = |role: &str, password: &str, database: &str| { + format!("postgresql://{role}:{password}@{host}:{port}/{database}") + }; + deployment.secret( + "migration-database-url", + &url(&migration, &migration_password, &database), + ); + deployment.secret( + "runtime-database-url", + &url(&runtime_role, &runtime_password, &database), + ); + let admin_file = deployment.path("admin-url"); + std::fs::write(&admin_file, url(&owner, &owner_password, "postgres")).unwrap(); + std::fs::set_permissions(&admin_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let (code, provisioned) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], database.as_str()); + for secret in [&owner_password, &migration_password, &runtime_password] { + assert!( + !provisioned.to_string().contains(secret.as_str()), + "the report holds no password" + ); + } + + let (code, again) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "a second run converges: {again:#}"); + + let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); + assert_eq!(code, 0, "{applied:#}"); + assert_eq!(applied["roleMode"], "split"); + + let server = tokio::spawn({ + let runtime = runtime.clone(); + async move { registry_scheduling::runtime::serve_from_path(&runtime).await } + }); + let mut ready = None; + for _ in 0..300 { + if server.is_finished() { + break; + } + ready = http_status(&bind, "/readyz").await; + if ready == Some(200) { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + if server.is_finished() { + let outcome = server.await.expect("the server task does not panic"); + panic!("the service stopped instead of serving: {outcome:?}"); + } + assert_eq!(ready, Some(200), "the service never reported ready"); + server.abort(); + + for statement in [ + format!("DROP DATABASE {database} WITH (FORCE)"), + format!("DROP ROLE {runtime_role}"), + format!("DROP ROLE {migration}"), + format!("DROP ROLE {owner}"), + ] { + deployment.admin.batch_execute(&statement).await.unwrap(); + } +} diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index 2238807718..1b460af3eb 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -72,41 +72,6 @@ two commands, and keep it out of the serving container. module comment and apply_audited(); crates/registry-schedulingctl/src/records.rs, connect_migration(). */} -## Provision PostgreSQL - -Create the roles and the database, then hand the schema to the migration role: - -```sql -CREATE ROLE scheduling_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS; -CREATE ROLE scheduling_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS; -CREATE DATABASE scheduling; -``` - -Set each role's password with `\password scheduling_migration` and `\password scheduling_runtime` -in `psql`, which prompts for it instead of taking it in a statement. - -In the `scheduling` database: - -```sql -REVOKE ALL ON DATABASE scheduling FROM PUBLIC; -GRANT CONNECT ON DATABASE scheduling TO scheduling_migration, scheduling_runtime; -ALTER SCHEMA public OWNER TO scheduling_migration; -REVOKE ALL ON SCHEMA public FROM PUBLIC; -``` - -Grant the runtime role nothing yourself. `apply` grants it exactly what serving needs: usage on -the schema, read and write on the Scheduling tables, usage and select on the outbox identity -sequence, and read on the activation ledgers. It reissues the grants on every run, so a table a -later migration adds is covered. The runtime requires TLS on its database connection and refuses -one it cannot verify; `database.caBundleRef` names the CA bundle when a private CA -fronts PostgreSQL. - -{/* Evidence: crates/registry-scheduling/migrations/0200_scheduling.sql; - crates/registry-schedulingctl/src/activation.rs, RoleMode; - products/scheduling/examples/standalone-exact-time/runtime.example.yaml, database. */} - ## Write the runtime file `schedulingctl init` wrote `runtime.example.yaml` beside your policy. Copy it to the host as @@ -166,6 +131,68 @@ secretsIncluded: false `SHA256SUMS` file. Set `package.expectedDigest` to the digest if the runtime must refuse any other package. +## Provision PostgreSQL + +Your runtime file already names the roles, their passwords, and the database. They are the URLs in +`database.migrationUrlRef` and `database.runtimeUrlRef`. `provision` reads the runtime file and the +package it names, so write the file and build the package first. Put both database URLs in their +secret files, then run `schedulingctl provision` once as a PostgreSQL role that can create roles and +databases: + +```sh +schedulingctl provision --runtime-config /etc/registry-scheduling/runtime.yaml --admin-url-file admin-url +``` + +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and +`CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, +use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set +`database.caBundleRef` in the runtime file to trust a private CA. The command never prints the +administrator URL or a password. + +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it + from `PUBLIC`. + +Run it again at any time. It creates only what is missing. It refuses a role that exists with a +different password than its URL holds, and tells you which role. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a +`\password` line that prompts for the password in `psql`, so the script holds no password: + +```sql +SET createrole_self_grant = 'set,inherit'; +CREATE ROLE "scheduling_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "scheduling_migration" +CREATE ROLE "scheduling_runtime" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "scheduling_runtime" +CREATE DATABASE "scheduling" WITH ALLOW_CONNECTIONS false; +REVOKE ALL ON DATABASE "scheduling" FROM PUBLIC; +GRANT CONNECT ON DATABASE "scheduling" TO "scheduling_migration", "scheduling_runtime"; +ALTER DATABASE "scheduling" ALLOW_CONNECTIONS true; +\connect "scheduling" +REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "scheduling_migration"; +``` + +The names come from your URLs. Add `--format json` for a report of each statement and its outcome. + +`provision` grants the runtime role nothing beyond `CONNECT`. `apply` grants it exactly what serving +needs: usage on the schema, read and write on the Scheduling tables, usage and select on the outbox +identity sequence, and read on the activation ledgers. It reissues the grants on every run, so a +table a later migration adds is covered. The runtime requires TLS on its database connection and +refuses one it cannot verify; `database.caBundleRef` names the CA bundle when a private CA fronts +PostgreSQL. + +{/* Evidence: crates/registry-schedulingctl/src/provision.rs; + crates/registry-scheduling/migrations/0200_scheduling.sql; + crates/registry-schedulingctl/src/activation.rs, RoleMode; + products/scheduling/examples/standalone-exact-time/runtime.example.yaml, database. */} + ## Plan and apply `plan` connects with the runtime credential and writes nothing: diff --git a/products/scheduling/AGENTS.md b/products/scheduling/AGENTS.md index ea805a90ef..3d3e965425 100644 --- a/products/scheduling/AGENTS.md +++ b/products/scheduling/AGENTS.md @@ -46,3 +46,7 @@ product. - PostgreSQL verification requires a separate disposable database and the `postgres-test` feature. A test binary that skips because its database URL is absent is not database verification. + The `provision_postgres` target of `registry-schedulingctl` needs + `PROVISION_TEST_DATABASE_URL`, a disposable superuser URL (`sslmode=verify-full` + on a server that offers verified TLS), and + `PROVISION_TEST_DATABASE_CA`, the path of the CA PEM. It fails without them. From b7385b677f272c61bfd1957d7c83c7e8604dbfa2 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 03:30:33 +0100 Subject: [PATCH 018/136] test(platform): add the own-provider acceptance journey and its observed stops The own-provider journey starts each product from its starter against a stock Keycloak and a stock PostgreSQL the reader already runs, and stops at the first step a reader cannot pass without hand-written SQL, a claim mapper or another forbidden assist. Its sixteen rows in the ratchet table are now observed on main: the database products stop at provisioning, Evidence at its issuer check, Render at the call. Signed-off-by: Jeremi Joslin --- products/platform/journeys/README.md | 4 + .../platform/journeys/expected-failures.yaml | 93 +- .../platform/journeys/keycloak/realm.json | 95 ++ products/platform/journeys/own-provider.sh | 1177 +++++++++++++++++ .../projects/coordinator/deployment.yaml | 36 + .../journeys/projects/render/runtime.yaml | 19 + 6 files changed, 1386 insertions(+), 38 deletions(-) create mode 100644 products/platform/journeys/keycloak/realm.json create mode 100755 products/platform/journeys/own-provider.sh create mode 100644 products/platform/journeys/projects/coordinator/deployment.yaml create mode 100644 products/platform/journeys/projects/render/runtime.yaml diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index c8ee203b57..61e060e407 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -30,6 +30,10 @@ issuer the run starts and does not start an identity provider. | `test_journey_tables.py` | The static check. | | `lib.sh` | The shared library every journey script sources: options, binaries, generated secrets and redaction, containers and their cleanup, steps, outcomes and the ratchet comparison. | | `test_lib.sh` | The library's self-test. It runs against fake `docker`, `curl` and `cargo` commands, so it starts no container and builds nothing: `bash products/platform/journeys/test_lib.sh`. | +| `rstack-dev.sh` | The `rstack dev` journey, with a recipe per product for the steps from `start` on. | +| `own-provider.sh` | The own-provider journey: a stock Keycloak and a stock PostgreSQL started on loopback, then each product from its starter to a first authenticated call. | +| `keycloak/realm.json` | The realm the own-provider journey imports: per product, one caller client with a service account and one API client for the product's audience. It holds no protocol mappers. | +| `projects/` | The runtime files the own-provider journey gives the products whose starter has none (Render, Coordinator). | ## Reading the ratchet table diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index 4f995e31d4..c0ecb52be6 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -57,72 +57,82 @@ expectedFailures: code: journey.needs.hand-written-sql finding: X13 removedBy: M4 - basis: predicted - reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "prepare and issuer pass (bregctl check accepts the Keycloak issuer with RS256). bregctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." - journey: own-provider product: casework step: database.provision code: journey.needs.hand-written-sql finding: X13 removedBy: M4 - basis: predicted - reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "prepare and issuer pass (caseworkctl check). caseworkctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." - journey: own-provider product: messaging step: database.provision code: journey.needs.hand-written-sql finding: X13 removedBy: M4 - basis: predicted - reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "prepare and issuer pass (messagingctl check). messagingctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." - journey: own-provider product: scheduling step: database.provision code: journey.needs.hand-written-sql finding: X13 removedBy: M4 - basis: predicted - reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "prepare and issuer pass (schedulingctl check). schedulingctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." - journey: own-provider product: documents step: database.provision code: journey.needs.hand-written-sql finding: X13 removedBy: M4 - basis: predicted - reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "prepare and issuer pass (documentsctl check). documentsctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." - journey: own-provider product: coordinator step: database.provision code: journey.needs.hand-written-sql finding: X13 removedBy: M4 - basis: predicted - reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "prepare and issuer pass (coordinatorctl check, with the deployment block written by hand). coordinatorctl provision is refused with coordinator.cli.usage (unrecognized command), so roles, the database and grants are made by hand." - journey: own-provider product: adapter step: database.provision code: journey.needs.hand-written-sql finding: X13 removedBy: M4 - basis: predicted - reason: Roles, databases and grants are made by hand. The only provisioning code is private to rstack dev. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "prepare and issuer pass (adapterctl check of the facade-recovery example with the breg-records profile). adapterctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." - journey: own-provider product: evidence - step: call - code: http.401.token-type - finding: G3 - removedBy: M7 - basis: predicted - reason: No database. Evidence accepts at+jwt or application/at+jwt only and Keycloak sends typ JWT. + step: issuer + code: product.evidence.bundle.invalid-authentication + finding: X1 + removedBy: M1 + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "evidencectl check refuses the local target (outer code evidence.target.publication-invalid): the local profile takes only a canonical 127.0.0.1 HTTP origin with a port, and a Keycloak issuer carries the /realms/ path, so any such issuer needs allowInsecureHttp: true. The loopback transport class of M1 (A2) removes the URL-shape rule. Behind it the call is predicted to stop at token-type, because Keycloak sends typ JWT." - journey: own-provider product: render step: call - code: http.401.token-type + code: product.render.unauthorized finding: G3 removedBy: M7 - basis: predicted - reason: Render fixes the token type at at+jwt and Keycloak sends typ JWT. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "No database. Start, ready and the client-credentials token pass (RS256, audience urn:example:render, scope render:render, client portal). POST /v1/render/letter answers 401 with problem render.unauthorized. Render logs no authentication stage, so the code is the problem code. Inferred cause: the token type fixed at at+jwt (registry-render/src/auth.rs:71 on main) against Keycloak's typ JWT." + - journey: rstack-dev product: breg step: plan @@ -280,39 +290,46 @@ expectedFailures: unreached: - journey: own-provider product: discovery - step: call - basis: predicted - reason: Discovery verifies no token. Its last step is one served public call, and whether the steps before it pass is not known until the first run. + step: prepare + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "Discovery verifies no token and keeps no database, so the reader's own provider and PostgreSQL have nothing to serve it. Its tutorial packages from a publication origin served by products/discovery/tutorial/publication_server.py, which a journey does not run." - journey: own-provider product: breg-mcp step: prepare - basis: predicted - reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes." - journey: own-provider product: breg-review step: prepare - basis: predicted - reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes." - journey: own-provider product: registry-mcp step: prepare - basis: predicted - reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes." - journey: own-provider product: evidence-oid4vci step: prepare - basis: predicted - reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes." - journey: own-provider product: evidence-oid4vp step: prepare - basis: predicted - reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes." - journey: own-provider product: adapter-job step: prepare - basis: predicted - reason: Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" + reason: "Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes." - journey: rstack-dev product: breg-mcp step: init diff --git a/products/platform/journeys/keycloak/realm.json b/products/platform/journeys/keycloak/realm.json new file mode 100644 index 0000000000..8532f8ad9f --- /dev/null +++ b/products/platform/journeys/keycloak/realm.json @@ -0,0 +1,95 @@ +{ + "realm": "registry-journey", + "displayName": "Registry Stack own-provider journey", + "enabled": true, + "sslRequired": "none", + "accessTokenLifespan": 300, + "roles": { + "client": { + "urn:breg:local-directory": [{"name": "access"}], + "urn:example:casework": [{"name": "access"}], + "urn:example:messaging": [{"name": "access"}], + "urn:example:scheduling": [{"name": "access"}], + "urn:example:documents": [{"name": "access"}], + "urn:example:coordinator": [{"name": "access"}], + "registry-adapter-example": [{"name": "access"}], + "urn:example:audience:local-evidence": [{"name": "access"}], + "urn:example:render": [{"name": "access"}] + } + }, + "clients": [ + {"clientId": "urn:breg:local-directory", "name": "BReg API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "directory-client", "name": "BReg caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_BREG}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + + {"clientId": "urn:example:casework", "name": "Casework API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "casework-client", "name": "Casework caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_CASEWORK}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + + {"clientId": "urn:example:messaging", "name": "Messaging API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "case-system", "name": "Messaging caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_MESSAGING}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + + {"clientId": "urn:example:scheduling", "name": "Scheduling API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "scheduling-booking-agent", "name": "Scheduling caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_SCHEDULING}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + + {"clientId": "urn:example:documents", "name": "Documents API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "case-portal", "name": "Documents caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_DOCUMENTS}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + + {"clientId": "urn:example:coordinator", "name": "Coordinator API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "coordinator-producer", "name": "Coordinator caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_COORDINATOR}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + + {"clientId": "registry-adapter-example", "name": "Adapter API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "registry-adapter-example-client", "name": "Adapter caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_ADAPTER}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + + {"clientId": "urn:example:audience:local-evidence", "name": "Evidence API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "evidence-client", "name": "Evidence caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_EVIDENCE}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + + {"clientId": "urn:example:render", "name": "Render API", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, + {"clientId": "portal", "name": "Render caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_RENDER}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true} + ], + "users": [ + {"username": "service-account-directory-client", "enabled": true, "serviceAccountClientId": "directory-client", + "clientRoles": {"urn:breg:local-directory": ["access"]}}, + {"username": "service-account-casework-client", "enabled": true, "serviceAccountClientId": "casework-client", + "clientRoles": {"urn:example:casework": ["access"]}}, + {"username": "service-account-case-system", "enabled": true, "serviceAccountClientId": "case-system", + "clientRoles": {"urn:example:messaging": ["access"]}}, + {"username": "service-account-scheduling-booking-agent", "enabled": true, "serviceAccountClientId": "scheduling-booking-agent", + "clientRoles": {"urn:example:scheduling": ["access"]}}, + {"username": "service-account-case-portal", "enabled": true, "serviceAccountClientId": "case-portal", + "clientRoles": {"urn:example:documents": ["access"]}}, + {"username": "service-account-coordinator-producer", "enabled": true, "serviceAccountClientId": "coordinator-producer", + "clientRoles": {"urn:example:coordinator": ["access"]}}, + {"username": "service-account-registry-adapter-example-client", "enabled": true, "serviceAccountClientId": "registry-adapter-example-client", + "clientRoles": {"registry-adapter-example": ["access"]}}, + {"username": "service-account-evidence-client", "enabled": true, "serviceAccountClientId": "evidence-client", + "clientRoles": {"urn:example:audience:local-evidence": ["access"]}}, + {"username": "service-account-portal", "enabled": true, "serviceAccountClientId": "portal", + "clientRoles": {"urn:example:render": ["access"]}} + ] +} diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh new file mode 100755 index 0000000000..5741f0198e --- /dev/null +++ b/products/platform/journeys/own-provider.sh @@ -0,0 +1,1177 @@ +#!/usr/bin/env bash +# The own-provider acceptance journey: each product from its starter to a first +# authenticated call against an identity provider and a PostgreSQL server the +# reader already runs. Here those are a stock Keycloak with the realm in +# keycloak/realm.json and a stock PostgreSQL with no TLS and no init SQL. +# +# Steps, as the pass rule counts them: prepare, issuer, database.provision, +# database.connect, start, ready, token, call, hook, stop. A cell is one +# product and stops at its first failing step. See README.md for the options, +# the two modes and the exit codes. +# +# What this script starts: two containers on the default bridge, named by +# lib.sh, with ports published on 127.0.0.1 only. +# kc Keycloak, the image products.yaml names (ownProviderIssuer), started +# with `start-dev --import-realm` on keycloak/realm.json +# pg postgres:18.7 by digest, started only when a selected product keeps a +# database +# Products run as host processes from --bin-dir. With JOURNEY_PORT_BASE the +# containers take the first ports and each product listens on base+4 (API) and +# base+5 (metrics), one product at a time. +# +# The reader's identity provider. realm.json holds, for every product that +# verifies a token, one confidential caller client with a service account, one +# API client whose client id is the product's audience, and the client role +# that makes Keycloak's stock audience resolution put that audience in `aud`. +# It holds no protocol mappers and no client scopes: an import that lists +# client scopes drops Keycloak's default ones. Each product's scope is created +# through the admin API at setup and made a default scope of its caller. A +# claim Keycloak gives only through a mapper is a journey.needs.claim-mapper +# stop, never a mapper here. Each product counts three identity-provider +# changes: its caller client, its audience and its scope. +# +# What the harness does that the reader does not type, and so is not counted: +# - the secret folder of every product is the run's secrets/ folder, so each +# secret:file reference is renamed with the product id as a prefix, and a +# secret root that init already placed beside the project is moved there +# - the secret files the runtime file names: random keys, the two PostgreSQL +# URLs with their role passwords and the administrator URL. lib.sh counts +# only files under work/, so these files are not counted; the step that +# introduces them declares the secret-file concept +# - free ports, when JOURNEY_PORT_BASE is not set +# +# Assists (lib-assists.sh, --assist) are called with these arguments: +# sql PRODUCT ADMIN_URL_FILE MIGRATION_URL_FILE RUNTIME_URL_FILE +# at database.provision: make the database, the two roles and the grants +# the two URLs name. The journey then goes on to database.connect. +# certificate PRODUCT RUNTIME_FILE +# at database.provision, database.connect or start, where the product +# refuses PostgreSQL without TLS: give the pg container a certificate +# and the runtime file its CA. The journey then runs the step again. +# mapper PRODUCT CLIENT TOKEN_VARIABLE CLAIM... +# at call: add the mappers for the claims the token lacks and set a +# fresh token, registered as a secret, in TOKEN_VARIABLE. The journey +# then makes the call again. +# keycloak_admin_login and keycloak_admin below are there for the assists. +# +# Run directory: everything lib.sh writes (run.json, cells.tsv, summary.json, +# /cell.json and step output, containers.txt, processes.txt, +# containers/, work/, secrets/ and, with --keep, the kept marker). On top of +# it: work/// is the project, work//package/ its +# package and own-provider.json the issuer, realm, ports and container roles of +# the run. With --keep the containers, secrets/ and the files this script +# wrote there stay for `promote --from`, and so do the development keys +# evidencectl init writes into work/evidence/evidence/.generated/secrets/. +# Without --keep cleanup deletes those keys with the rest of the secrets. +# +# Run it from anywhere: +# products/platform/journeys/own-provider.sh --bin-dir DIR [--product ID]... +# [--issuer keycloak] [--out DIR] [--expected FILE [--strict]] [--keep] +# [--assist LIST] + +set -euo pipefail + +# shellcheck disable=SC1091 # lib.sh is checked on its own +source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" + +journey_init own-provider --value-option issuer -- "$@" + +REALM=registry-journey +POSTGRES_IMAGE=postgres:18.7@sha256:2ea8630df176ad090ec92136dee850397c5af8781e4bcf2e4162593691c61bbc +PROJECTS_DIR=$JOURNEY_LIB_DIR/projects +SECRETS=$JOURNEY_OUT/secrets +# The stages the shared verifier logs (AuthenticationStage in +# registry-platform-oidc), the same list as authenticationStages in the table. +STAGES=' header algorithm token-type key signature issuer audience time client scope profile unavailable ' +# Every product a token reaches. The realm names a caller client for each, so +# every one of their client secrets is generated even when fewer are selected. +TOKEN_PRODUCTS='breg casework messaging scheduling documents coordinator adapter evidence render' + +# --------------------------------------------------------------------------- +# The issuer the run uses + +journey_option_value issuer ISSUER_KIND +ISSUER_KIND=${ISSUER_KIND:-keycloak} +[[ "$ISSUER_KIND" == keycloak ]] || + journey_usage_error "--issuer $ISSUER_KIND: this journey starts only keycloak, the provider products.yaml names" + +# products.yaml names the provider and its image at the top level, which +# journey_product_field does not read, so it is read here with the same core +# Perl YAML reader lib.sh uses. +ISSUER_LINE=$(perl -MCPAN::Meta::YAML -e ' + my $docs = CPAN::Meta::YAML->read($ARGV[0]) or die CPAN::Meta::YAML->errstr . "\n"; + my $issuer = $docs->[0]{ownProviderIssuer} or die "$ARGV[0] has no ownProviderIssuer\n"; + print "$issuer->{name}\t$issuer->{image}\n";' "$JOURNEY_TABLES_DIR/products.yaml") || + journey_usage_error "cannot read ownProviderIssuer from $JOURNEY_TABLES_DIR/products.yaml" +[[ "${ISSUER_LINE%%$'\t'*}" == "$ISSUER_KIND" ]] || + journey_usage_error "products.yaml names the provider ${ISSUER_LINE%%$'\t'*}, not $ISSUER_KIND" +KEYCLOAK_IMAGE=${ISSUER_LINE#*$'\t'} + +journey_require_docker +journey_set_address_class loopback + +# --------------------------------------------------------------------------- +# Small helpers + +# field PRODUCT FIELD: a products.yaml field on stdout. +field() { + local value + journey_product_field "$1" "$2" value + printf '%s' "$value" +} + +upper() { + printf '%s' "$1" | tr '[:lower:]-' '[:upper:]_' +} + +# free_port VAR: a loopback port nothing listens on now. +free_port() { + local _kc_port + _kc_port=$(perl -MIO::Socket::INET -e ' + my $socket = IO::Socket::INET->new(LocalAddr => "127.0.0.1", LocalPort => 0, Proto => "tcp", Listen => 1) + or die "cannot bind a loopback port: $!\n"; + print $socket->sockport, "\n";') || journey_harness_failure "cannot find a free loopback port" + printf -v "$1" '%s' "$_kc_port" +} + +# port_is_free PORT +port_is_free() { + perl -MIO::Socket::INET -e ' + IO::Socket::INET->new(LocalAddr => "127.0.0.1", LocalPort => $ARGV[0], Proto => "tcp", Listen => 1, ReuseAddr => 1) + or exit 1;' "$1" +} + +# tcp_open PORT: something accepts a connection on 127.0.0.1:PORT. +tcp_open() { + perl -MIO::Socket::INET -e ' + IO::Socket::INET->new(PeerAddr => "127.0.0.1", PeerPort => $ARGV[0], Proto => "tcp", Timeout => 2) + or exit 1;' "$1" +} + +# copy_file SOURCE TARGET: what `cp` does for one text file, in bash. +copy_file() { + local text + text=$(<"$1") + printf '%s\n' "$text" >"$2" +} + +# copy_files DIRECTORY SOURCE...: `cp SOURCE... DIRECTORY` for text files. +copy_files() { + local directory=$1 source + shift + mkdir -p -- "$directory" + for source in "$@"; do + copy_file "$source" "$directory/${source##*/}" + done +} + +# fill_template FILE NAME=VALUE...: FILE without its comment lines, with each +# @NAME@ replaced. A placeholder left unfilled is a journey script error. +fill_template() { + perl -e ' + my ($path, @pairs) = @ARGV; + my %value = map { my ($k, $v) = split /=/, $_, 2; ($k, $v) } @pairs; + open my $in, "<", $path or die "cannot read $path: $!\n"; + while (my $line = <$in>) { + next if $line =~ /^\s*#/; + $line =~ s/\@([A-Z]+)\@/exists $value{$1} ? $value{$1} : die "$path: no value for \@$1\@\n"/ge; + print $line; + }' "$@" || journey_harness_failure "journey script error: cannot fill the template $1" +} + +# edit FILE SEARCH REPLACE [CONCEPTS]: an edit the reader makes by hand. +edit() { + if [[ -n "${4:-}" ]]; then + journey_edit_file "$1" "$2" "$3" --concepts "$4" + else + journey_edit_file "$1" "$2" "$3" + fi +} + +# harness_edit FILE SEARCH REPLACE: an edit the harness makes for its own +# layout and does not count. SEARCH must occur exactly once. +harness_edit() { + perl -e ' + my ($path, $search, $replace) = @ARGV; + open my $in, "<:raw", $path or die "cannot read $path: $!\n"; + local $/; my $text = <$in>; close $in; + my $count = () = $text =~ /\Q$search\E/g; + die "the text to replace occurs $count times in $path; it must occur once\n" if $count != 1; + substr($text, index($text, $search), length $search) = $replace; + open my $out, ">:raw", $path or die "cannot write $path: $!\n"; + print {$out} $text; close $out or die "cannot write $path: $!\n";' "$@" || + journey_harness_failure "journey script error: cannot edit $1" +} + +# prefix_secret_references PRODUCT FILE: rename every secret:file reference +# outside a comment to PRODUCT-NAME, so ten products share one secret folder. +prefix_secret_references() { + perl -i -pe ' + BEGIN { $product = shift @ARGV } + next if /^\s*#/; + s{secret:file/(?!\Q$product\E-)}{secret:file/$product-}g;' "$1" "$2" || + journey_harness_failure "cannot rename the secret references in $2" +} + +# secret_references FILE: the secret:file names FILE uses outside comments. +secret_references() { + perl -ne 'next if /^\s*#/; print "$1\n" while m{secret:file/([A-Za-z0-9._-]+)}g' "$1" | sort -u +} + +# --------------------------------------------------------------------------- +# Secret files this script writes itself + +# lib.sh generates random secrets and deletes what it generated. A PostgreSQL +# URL is not random text, so this script writes those files into secrets/ and +# deletes them in its own cleanup hook, before lib.sh removes the folder. With +# --keep they stay, and the run that takes this one over adopts them. +OWN_SECRET_FILES=() + +# write_own_secret NAME VALUE_VARIABLE: write the value of a shell variable +# into secrets/NAME with mode 0600. The value is read by name. +write_own_secret() { + local name=$1 variable=$2 path + path=$SECRETS/$name + [[ ! -e "$path" ]] || journey_harness_failure "journey script error: secret file $name already exists" + ( + umask 077 + printf '%s' "${!variable}" >"$path" + ) || journey_harness_failure "cannot write secret file $name" + OWN_SECRET_FILES+=("$path") +} + +remove_own_secret_files() { + local path status=0 + [[ $JOURNEY_KEEP -eq 0 ]] || return 0 + for path in ${OWN_SECRET_FILES[@]+"${OWN_SECRET_FILES[@]}"}; do + if [[ -e "$path" ]] && ! rm -- "$path"; then + printf 'cannot delete %s\n' "$path" >&2 + status=1 + fi + done + return "$status" +} +journey_at_cleanup remove_own_secret_files + +# Key folders a product's own init writes inside the reader's project +# (evidencectl init --profile local generates its development keys into +# .generated/secrets/). lib.sh's secret scan skips work/, so cleanup deletes +# the files of each folder named here and the folder itself, as it does the +# run's secrets/. With --keep they stay. +PRODUCT_KEY_DIRS=() + +remove_product_key_dirs() { + local directory path status=0 + [[ $JOURNEY_KEEP -eq 0 ]] || return 0 + for directory in ${PRODUCT_KEY_DIRS[@]+"${PRODUCT_KEY_DIRS[@]}"}; do + [[ -d "$directory" ]] || continue + for path in "$directory"/* "$directory"/.[!.]*; do + [[ -e "$path" || -L "$path" ]] || continue + if [[ -d "$path" && ! -L "$path" ]]; then + printf 'cannot delete %s: a folder inside a product key folder\n' "$path" >&2 + status=1 + elif ! rm -- "$path"; then + printf 'cannot delete %s\n' "$path" >&2 + status=1 + fi + done + if ! rmdir -- "$directory"; then + printf 'cannot delete %s\n' "$directory" >&2 + status=1 + fi + done + return "$status" +} +journey_at_cleanup remove_product_key_dirs + +# read_secret NAME VAR: the value of a generated secret into VAR. +read_secret() { + local _kc_path + journey_secret_path "$1" _kc_path + IFS= read -r "$2" <"$_kc_path" || [[ -n "${!2}" ]] || journey_harness_failure "cannot read secret $1" +} + +# --------------------------------------------------------------------------- +# The reader's identity provider and PostgreSQL server + +KC_PORT='' +KC_URL='' +KC_ISSUER='' +PG_PORT='' +ADMIN_URL_FILE='' +KC_ADMIN_TOKEN='' +KC_STATUS='' +KC_BODY='' +COORDINATOR_SUBJECT='' + +# keycloak_admin_login: an administrator token of the master realm into +# KC_ADMIN_TOKEN, registered as a secret. The password reaches curl as a file. +keycloak_admin_login() { + local password_file response token + journey_secret_path keycloak-admin password_file + response=$(curl --silent --show-error --max-time 30 \ + --data grant_type=password --data client_id=admin-cli --data username=admin \ + --data-urlencode "password@$password_file" \ + "$KC_URL/realms/master/protocol/openid-connect/token") || + journey_harness_failure "the Keycloak administrator login did not answer" + token=$(printf '%s' "$response" | jq -r '.access_token // empty') || + journey_harness_failure "the Keycloak administrator login answered something that is not JSON" + if [[ -z "$token" ]]; then + journey_harness_failure "the Keycloak administrator login was refused: $(printf '%s' "$response" | jq -c '{error, error_description}')" + fi + KC_ADMIN_TOKEN=$token + journey_secret_register keycloak-admin-token KC_ADMIN_TOKEN +} + +# keycloak_admin METHOD PATH [JSON]: one admin API request on the journey's +# realm. Sets KC_STATUS and KC_BODY. The token reaches curl through a file +# descriptor. +keycloak_admin() { + local method=$1 path=$2 body=${3:-} response + local -a data=() + if [[ -n "$body" ]]; then + data=(--header 'Content-Type: application/json' --data-binary "$body") + fi + response=$(curl --silent --show-error --max-time 30 -X "$method" \ + -H "@"<(printf 'Authorization: Bearer %s\n' "$KC_ADMIN_TOKEN") \ + ${data[@]+"${data[@]}"} --write-out '\n%{http_code}' \ + "$KC_URL/admin/realms/$REALM$path") || + journey_harness_failure "the Keycloak admin API did not answer $method $path" + KC_STATUS=${response##*$'\n'} + KC_BODY=${response%$'\n'*} +} + +# keycloak_client_uuid CLIENT_ID VAR. Its locals start with _kc_ so that a +# caller's VAR is never one of them. +keycloak_client_uuid() { + local _kc_encoded _kc_uuid + _kc_encoded=$(jq -rn --arg value "$1" '$value | @uri') + keycloak_admin GET "/clients?clientId=$_kc_encoded" + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak cannot list client $1 (HTTP $KC_STATUS)" + _kc_uuid=$(printf '%s' "$KC_BODY" | jq -r --arg id "$1" 'first(.[] | select(.clientId == $id) | .id) // empty') + [[ -n "$_kc_uuid" ]] || journey_harness_failure "the realm has no client $1; see keycloak/realm.json" + printf -v "$2" '%s' "$_kc_uuid" +} + +# keycloak_default_scope CLIENT_ID SCOPE: create SCOPE, included in the +# token's scope claim, and make it a default scope of CLIENT_ID. +keycloak_default_scope() { + local client=$1 scope=$2 uuid scope_id body + body=$(jq -cn --arg name "$scope" \ + '{name: $name, protocol: "openid-connect", attributes: {"include.in.token.scope": "true", "display.on.consent.screen": "false"}}') + keycloak_admin POST /client-scopes "$body" + [[ "$KC_STATUS" == 201 || "$KC_STATUS" == 409 ]] || + journey_harness_failure "Keycloak refused to create client scope $scope (HTTP $KC_STATUS)" + keycloak_admin GET /client-scopes + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak cannot list client scopes (HTTP $KC_STATUS)" + scope_id=$(printf '%s' "$KC_BODY" | jq -r --arg name "$scope" 'first(.[] | select(.name == $name) | .id) // empty') + [[ -n "$scope_id" ]] || journey_harness_failure "Keycloak lists no client scope $scope after creating it" + keycloak_client_uuid "$client" uuid + keycloak_admin PUT "/clients/$uuid/default-client-scopes/$scope_id" + [[ "$KC_STATUS" == 204 ]] || + journey_harness_failure "Keycloak refused to add scope $scope to client $client (HTTP $KC_STATUS)" +} + +# keycloak_service_account_subject CLIENT_ID VAR: the `sub` of the client's +# service account, which a Coordinator policy names. +keycloak_service_account_subject() { + local _kc_client _kc_subject + keycloak_client_uuid "$1" _kc_client + keycloak_admin GET "/clients/$_kc_client/service-account-user" + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak has no service account for $1 (HTTP $KC_STATUS)" + _kc_subject=$(printf '%s' "$KC_BODY" | jq -r '.id // empty') + [[ -n "$_kc_subject" ]] || journey_harness_failure "the service account of $1 has no id" + printf -v "$2" '%s' "$_kc_subject" +} + +start_keycloak() { + local product env_name + local -a secret_envs=() + journey_secret_new keycloak-admin 24 + for product in $TOKEN_PRODUCTS; do + journey_secret_new "client-$product" 24 + env_name="JOURNEY_CLIENT_SECRET_$(upper "$product")" + secret_envs+=(--secret-env "$env_name=client-$product") + done + journey_container_run kc --port 8080 \ + --env=KC_BOOTSTRAP_ADMIN_USERNAME=admin \ + --secret-env KC_BOOTSTRAP_ADMIN_PASSWORD=keycloak-admin "${secret_envs[@]}" \ + -v "$JOURNEY_LIB_DIR/keycloak:/opt/keycloak/data/import:ro" -- \ + "$KEYCLOAK_IMAGE" start-dev --import-realm + journey_container_port kc 8080 KC_PORT + KC_URL=http://127.0.0.1:$KC_PORT + KC_ISSUER=$KC_URL/realms/$REALM + journey_container_wait kc 240 -- curl --silent --fail --output /dev/null \ + "$KC_ISSUER/.well-known/openid-configuration" +} + +start_postgres() { + # shellcheck disable=SC2034 # url is read by name in write_own_secret + local password url + journey_secret_new postgres-password 24 + journey_container_run pg --port 5432 --secret-env POSTGRES_PASSWORD=postgres-password -- "$POSTGRES_IMAGE" + journey_container_port pg 5432 PG_PORT + journey_container_wait pg 90 -- tcp_open "$PG_PORT" + read_secret postgres-password password + url="postgresql://postgres:$password@127.0.0.1:$PG_PORT/postgres" + write_own_secret postgres-admin-url url + ADMIN_URL_FILE=$SECRETS/postgres-admin-url +} + +# --------------------------------------------------------------------------- +# Recipes: what each product's reader uses + +# recipe PRODUCT: sets TOOL (the product's tool), SERVER (its runtime binary), +# CLIENT, AUDIENCE and SCOPE (the reader's provider), READY_PATH, CALL_METHOD +# and CALL_PATH (the first authenticated request) and CLAIMS (claims beyond the +# OIDC core the product reads from a service token). +recipe() { + local product=$1 + SERVER=$(field "$product" binary) + CLAIMS='' + READY_PATH=/ready + CALL_METHOD=GET + case "$product" in + breg) + TOOL=bregctl CLIENT=directory-client AUDIENCE=urn:breg:local-directory SCOPE=registry:directory:write + CALL_PATH=/v1/records/contacts CLAIMS='registry_principal registry_purpose' + ;; + casework) + TOOL=caseworkctl CLIENT=casework-client AUDIENCE=urn:example:casework SCOPE=casework:staff + CALL_PATH=/v1/review-policies + ;; + messaging) + TOOL=messagingctl CLIENT=case-system AUDIENCE=urn:example:messaging SCOPE=messaging:send + CALL_METHOD=POST CALL_PATH=/v1/messages + ;; + scheduling) + TOOL=schedulingctl CLIENT=scheduling-booking-agent AUDIENCE=urn:example:scheduling SCOPE=scheduling:read + READY_PATH=/readyz CALL_PATH=/v1/locations CLAIMS=registry_actor_kind + ;; + documents) + TOOL=documentsctl CLIENT=case-portal AUDIENCE=urn:example:documents SCOPE=documents:read + CALL_PATH=/v1/document-policies + ;; + coordinator) + TOOL=coordinatorctl CLIENT=coordinator-producer AUDIENCE=urn:example:coordinator SCOPE=coordinator:start + CALL_PATH=/v1/workflows/coordinator + ;; + adapter) + TOOL=adapterctl CLIENT=registry-adapter-example-client AUDIENCE=registry-adapter-example SCOPE=records.write + CALL_PATH=/v1/records/person + ;; + evidence) + TOOL=evidencectl CLIENT=evidence-client AUDIENCE=urn:example:audience:local-evidence SCOPE=evidence:request + CALL_PATH=/v1/evidence-definitions CLAIMS='evidence_audience evidence_tags' + ;; + render) + TOOL=registry-render CLIENT=portal AUDIENCE=urn:example:render SCOPE=render:render + CALL_METHOD=POST CALL_PATH=/v1/render/letter + ;; + *) journey_harness_failure "no recipe is written for product $product; add one to recipe in own-provider.sh" ;; + esac + journey_bin "$TOOL" TOOL_BIN + journey_bin "$SERVER" SERVER_BIN +} + +# --------------------------------------------------------------------------- +# Outcomes + +# The open cell's product, its folders and its runtime file, and whether the +# cell has stopped. +CELL='' +CELL_OVER=0 +WORK='' +PROJECT='' +RUNTIME_FILE='' +PORT='' +METRICS_PORT='' +ACCESS_TOKEN='' +MIGRATION_URL_FILE='' +RUNTIME_URL_FILE='' +SERVER_LOG_OUT='' +SERVER_LOG_ERR='' + +# harness_places_secrets PRODUCT: the harness puts the product's secret files in +# secrets/. Evidence's init generates its own local keys beside the project and +# its target names them there, so they are left where init put them. +harness_places_secrets() { + [[ "$1" != evidence ]] +} + +# diagnostic_code FILE...: the code a product printed in any FILE: the code +# nested in the first diagnostic's message as error[code], else that +# diagnostic's code, else a JSON error code, else a human error[code] line. +diagnostic_code() { + local file code='' + for file in "$@"; do + [[ -s "$file" ]] || continue + code=$(jq -r '(first(.diagnostics[]?) + | ((.message // "") | [match("error\\[([a-z0-9._-]+)\\]").captures[0].string] | first) // .code) + // .error.code // empty' "$file" 2>/dev/null) || code='' + if [[ -z "$code" ]]; then + code=$(perl -ne 'if (/^error\[([a-z0-9._-]+)\]/) { print $1; last }' "$file") + fi + [[ -z "$code" ]] || break + done + printf '%s' "$code" +} + +# stop_with_product_code STEP FILE...: the cell stops at STEP with the code the +# product printed. A refusal that prints no code is a harness failure: the +# journey would otherwise invent one. +stop_with_product_code() { + local step=$1 code + shift + code=$(diagnostic_code "$@") + [[ -n "$code" ]] || journey_harness_failure "step $step of $CELL failed and printed no diagnostic code; see $*" + [[ "$code" =~ ^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)*$ ]] || + journey_harness_failure "step $step of $CELL printed the code '$code', which no table code form can hold; see $*" + journey_fail "$step" "product.$code" + CELL_OVER=1 +} + +# reader_command STEP [STEP OPTIONS] -- COMMAND...: one command of STEP. A +# refusal stops the cell with the product's code. +reader_command() { + local step=$1 status=0 + shift + journey_step "$step" "$@" || status=$? + if [[ $status -ne 0 ]]; then + stop_with_product_code "$step" "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" + fi +} + +# mentions_tls FILE...: the output names TLS, SSL or a certificate. +mentions_tls() { + perl -e ' + local $/; + for my $path (@ARGV) { + open my $fh, "<", $path or next; + my $text = <$fh>; + exit 0 if defined $text && $text =~ /\b(?:tls|ssl|sslmode)\b|certificate/i; + } + exit 1;' "$@" +} + +# unrecognized_subcommand FILE...: the tool has no such command, in clap's +# words or in a tool's own usage diagnostic. +unrecognized_subcommand() { + perl -e ' + local $/; + for my $path (@ARGV) { + open my $fh, "<", $path or next; + my $text = <$fh>; + exit 0 if defined $text && $text =~ /unrecognized (?:sub)?command/; + } + exit 1;' "$@" +} + +# --------------------------------------------------------------------------- +# The steps + +# prepare: the product's starter, its package and its runtime file, with the +# paths and ports of this machine. +step_prepare() { + local product=$1 package=$WORK/package digest workflow block + case "$product" in + breg) + reader_command prepare --concepts project -- "$TOOL_BIN" init "$PROJECT" + [[ $CELL_OVER -eq 0 ]] || return 0 + RUNTIME_FILE=$PROJECT/runtime.yaml + reader_command prepare --concepts runtime-file --typed "cp runtime.example.yaml runtime.yaml" -- \ + copy_file "$PROJECT/runtime.example.yaml" "$RUNTIME_FILE" + [[ $CELL_OVER -eq 0 ]] || return 0 + edit "$RUNTIME_FILE" " bind: 127.0.0.1:8080" " bind: 127.0.0.1:$PORT" listener-bind + edit "$RUNTIME_FILE" " root: /var/lib/breg/secrets" " root: $SECRETS" secret-file + edit "$RUNTIME_FILE" " root: /var/lib/breg/package" " root: $package" package + edit "$RUNTIME_FILE" " path: /var/log/breg/audit.jsonl" " path: $WORK/audit.jsonl" + ;; + casework) + reader_command prepare --concepts project -- "$TOOL_BIN" init "$PROJECT" + [[ $CELL_OVER -eq 0 ]] || return 0 + reader_command prepare --concepts package -- "$TOOL_BIN" package --output "$PROJECT/.casework/package" "$PROJECT" + [[ $CELL_OVER -eq 0 ]] || return 0 + RUNTIME_FILE=$PROJECT/runtime.yaml + reader_command prepare --concepts runtime-file --typed "cp runtime.example.yaml runtime.yaml" -- \ + copy_file "$PROJECT/runtime.example.yaml" "$RUNTIME_FILE" + [[ $CELL_OVER -eq 0 ]] || return 0 + edit "$RUNTIME_FILE" " bind: 127.0.0.1:8100" " bind: 127.0.0.1:$PORT" listener-bind + harness_edit "$RUNTIME_FILE" " root: $PROJECT/secrets" " root: $SECRETS" + ;; + messaging | scheduling | documents) + if [[ "$product" == scheduling ]]; then + reader_command prepare --concepts project -- "$TOOL_BIN" init --template standalone-exact-time "$PROJECT" + else + reader_command prepare --concepts project -- "$TOOL_BIN" init "$PROJECT" + fi + [[ $CELL_OVER -eq 0 ]] || return 0 + reader_command prepare --concepts package -- "$TOOL_BIN" package --output "$package" "$PROJECT" + [[ $CELL_OVER -eq 0 ]] || return 0 + RUNTIME_FILE=$PROJECT/runtime.yaml + reader_command prepare --concepts runtime-file --typed "cp runtime.example.yaml runtime.yaml" -- \ + copy_file "$PROJECT/runtime.example.yaml" "$RUNTIME_FILE" + [[ $CELL_OVER -eq 0 ]] || return 0 + local api metrics + case "$product" in + messaging) api=8107 metrics=9107 ;; + scheduling) api=8105 metrics=9105 ;; + documents) api=8116 metrics=9116 ;; + esac + edit "$RUNTIME_FILE" " root: /srv/registry-$product/package" " root: $package" package + edit "$RUNTIME_FILE" " bind: 127.0.0.1:$api" " bind: 127.0.0.1:$PORT" listener-bind + edit "$RUNTIME_FILE" " bind: 127.0.0.1:$metrics" " bind: 127.0.0.1:$METRICS_PORT" + edit "$RUNTIME_FILE" " root: /run/secrets/registry-$product" " root: $SECRETS" secret-file + edit "$RUNTIME_FILE" " path: /var/lib/registry-$product/audit.ndjson" " path: $WORK/audit.ndjson" + if [[ "$product" == documents ]]; then + # The starter's listener is the production one, which refuses a + # loopback HTTP issuer; local development is development-loopback. + edit "$RUNTIME_FILE" " tlsTermination: operator-controlled-upstream" " tlsTermination: development-loopback" \ + tls-termination,posture + fi + ;; + coordinator) + reader_command prepare --concepts project -- "$TOOL_BIN" init --directory "$PROJECT" + [[ $CELL_OVER -eq 0 ]] || return 0 + reader_command prepare --concepts package -- "$TOOL_BIN" --format json package --project "$PROJECT" --output "$package" + [[ $CELL_OVER -eq 0 ]] || return 0 + digest=$(jq -er '.packageDigest' "$JOURNEY_STEP_STDOUT") || + journey_harness_failure "the coordinatorctl package report names no packageDigest; see $JOURNEY_STEP_STDOUT" + workflow=$(perl -ne 'if (/^ id: (\S+)/) { print $1; last }' "$PROJECT/workflow.yaml") + [[ -n "$workflow" ]] || journey_harness_failure "cannot read the workflow id from $PROJECT/workflow.yaml" + RUNTIME_FILE=$PROJECT/runtime.yaml + harness_edit "$RUNTIME_FILE" " root: $PROJECT/.coordinator/secrets" " root: $SECRETS" + edit "$RUNTIME_FILE" " runtimeUrlRef: secret:env/COORDINATOR_TEST_DATABASE_URL" \ + " runtimeUrlRef: secret:file/runtime-database-url" database-url,secret-file + edit "$RUNTIME_FILE" " migrationUrlRef: secret:env/COORDINATOR_TEST_DATABASE_URL" \ + " migrationUrlRef: secret:file/migration-database-url" + block=$(fill_template "$PROJECTS_DIR/coordinator/deployment.yaml" \ + "PACKAGE=$package" "DIGEST=$digest" "PORT=$PORT" "SUBJECT=$COORDINATOR_SUBJECT" \ + "WORKFLOW=$workflow" "WORK=$WORK") + edit "$RUNTIME_FILE" $'\nconnections:\n' $'\n'"$block"$'\nconnections:\n' \ + package,listener-bind,tls-termination,audience,scope-claim,access-profile,required-scopes,database-role + ;; + adapter) + local example=$JOURNEY_ROOT/products/adapter/examples/facade-recovery + reader_command prepare --concepts project --typed "cp products/adapter/examples/facade-recovery/*.yaml $PROJECT" -- \ + copy_files "$PROJECT" "$example/project.yaml" "$example/pack.yaml" "$example/fixture.yaml" "$example/runtime.example.yaml" + [[ $CELL_OVER -eq 0 ]] || return 0 + RUNTIME_FILE=$PROJECT/runtime.yaml + reader_command prepare --concepts runtime-file --typed "cp runtime.example.yaml runtime.yaml" -- \ + copy_file "$PROJECT/runtime.example.yaml" "$RUNTIME_FILE" + [[ $CELL_OVER -eq 0 ]] || return 0 + edit "$RUNTIME_FILE" " bind: 127.0.0.1:8080" " bind: 127.0.0.1:$PORT" listener-bind + ;; + evidence) + PRODUCT_KEY_DIRS+=("$PROJECT/.generated/secrets") + reader_command prepare --concepts project -- "$TOOL_BIN" init --profile local --transport sqlite-extract "$PROJECT" + [[ $CELL_OVER -eq 0 ]] || return 0 + RUNTIME_FILE=$PROJECT/local-target.yaml + ;; + render) + reader_command prepare --concepts project -- "$TOOL_BIN" init "$PROJECT" + [[ $CELL_OVER -eq 0 ]] || return 0 + reader_command prepare --concepts package -- "$TOOL_BIN" package --bundle "$PROJECT" --output "$package" + [[ $CELL_OVER -eq 0 ]] || return 0 + RUNTIME_FILE=$WORK/runtime.yaml + journey_write_file "$RUNTIME_FILE" --concepts runtime-file,listener-bind,package,audience,allowed-clients < <( + fill_template "$PROJECTS_DIR/render/runtime.yaml" "PORT=$PORT" "WORK=$WORK" + ) + ;; + esac + if harness_places_secrets "$product"; then + prefix_secret_references "$product" "$RUNTIME_FILE" + fi + journey_pass prepare +} + +# issuer: point the runtime file at the reader's own provider, then the +# product's offline check. +step_issuer() { + local product=$1 + journey_count identity-provider-changes 3 + case "$product" in + breg) + edit "$RUNTIME_FILE" " issuer: https://issuer.example.com" " issuer: $KC_ISSUER" issuer-url + edit "$RUNTIME_FILE" " allowedAlgorithm: EdDSA" " allowedAlgorithm: RS256" + reader_command issuer -- "$TOOL_BIN" --format json check "$PROJECT" --runtime-config "$RUNTIME_FILE" + ;; + casework) + edit "$RUNTIME_FILE" " issuer: https://identity.example.test" " issuer: $KC_ISSUER" issuer-url + reader_command issuer -- "$TOOL_BIN" --format json check "$PROJECT" --runtime-config "$RUNTIME_FILE" + ;; + messaging | documents) + edit "$RUNTIME_FILE" " issuer: https://identity.example.test/realms/registry" " issuer: $KC_ISSUER" issuer-url + reader_command issuer -- "$TOOL_BIN" --format json check --runtime-config "$RUNTIME_FILE" + ;; + scheduling) + edit "$RUNTIME_FILE" " issuer: https://identity.example.test/realms/registry" " issuer: $KC_ISSUER" issuer-url + reader_command issuer -- "$TOOL_BIN" --format json check "$PROJECT" --runtime-config "$RUNTIME_FILE" + ;; + coordinator) + edit "$RUNTIME_FILE" " issuer: https://identity.example.test/realms/registry" " issuer: $KC_ISSUER" issuer-url + reader_command issuer -- "$TOOL_BIN" --format json --runtime-config "$RUNTIME_FILE" check --project "$PROJECT" + ;; + adapter) + edit "$RUNTIME_FILE" " issuer: https://issuer.example.invalid" " issuer: $KC_ISSUER" issuer-url + reader_command issuer -- "$TOOL_BIN" --format json check "$PROJECT/project.yaml" \ + --profile "$JOURNEY_ROOT/products/adapter/profiles/breg-records/profile.yaml" \ + --pack "$PROJECT/pack.yaml" --runtime "$RUNTIME_FILE" + ;; + evidence) + edit "$RUNTIME_FILE" " issuer: http://127.0.0.1:8081" " issuer: $KC_ISSUER" issuer-url + edit "$RUNTIME_FILE" " uri: http://127.0.0.1:8081/oauth2/jwks" \ + " uri: $KC_ISSUER/protocol/openid-connect/certs" jwks-uri + edit "$RUNTIME_FILE" " - ES256" " - RS256" + reader_command issuer -- "$TOOL_BIN" check "$PROJECT" --target "$RUNTIME_FILE" --format json + ;; + render) + edit "$RUNTIME_FILE" " issuer: https://identity.example.test/realms/registry" " issuer: $KC_ISSUER" issuer-url + reader_command issuer -- "$TOOL_BIN" check --runtime-config "$RUNTIME_FILE" --format json + ;; + esac + [[ $CELL_OVER -eq 0 ]] || return 0 + journey_pass issuer +} + +# write_product_secrets PRODUCT: the secret files the runtime file names. The +# two PostgreSQL URLs carry role names, passwords and the database the +# product's provisioning makes; every other reference gets random bytes. +write_product_secrets() { + # shellcheck disable=SC2034 # url is read by name in write_own_secret + local product=$1 name password url bytes + harness_places_secrets "$product" || return 0 + if [[ "$(field "$product" usesPostgres)" == true ]]; then + journey_secret_new "$product-migration-password" 24 + journey_secret_new "$product-runtime-password" 24 + read_secret "$product-migration-password" password + url="postgresql://${product}_migration:$password@127.0.0.1:$PG_PORT/$product" + write_own_secret "$product-migration-database-url" url + read_secret "$product-runtime-password" password + # shellcheck disable=SC2034 # read by name in write_own_secret + url="postgresql://${product}_runtime:$password@127.0.0.1:$PG_PORT/$product" + write_own_secret "$product-runtime-database-url" url + MIGRATION_URL_FILE=$SECRETS/$product-migration-database-url + RUNTIME_URL_FILE=$SECRETS/$product-runtime-database-url + fi + while IFS= read -r name; do + [[ -n "$name" && ! -e "$SECRETS/$name" ]] || continue + [[ "$name" == "$product-"* ]] || + journey_harness_failure "journey script error: the secret reference $name of $product was not renamed" + bytes=32 + # Coordinator keys are exactly 32 bytes in a file: 16 random bytes + # written as 32 hexadecimal characters. + if [[ "$product" == coordinator ]]; then + bytes=16 + fi + journey_secret_new "$name" "$bytes" + done < <(secret_references "$RUNTIME_FILE") +} + +# database_step STEP TYPED -- COMMAND...: a database step and its blockers. +database_step() { + local step=$1 typed=$2 status=0 + shift 3 + journey_step "$step" --concepts database-url,database-role,secret-file --typed "$typed" -- "$@" || status=$? + if [[ $status -eq 0 ]]; then + journey_pass "$step" + return 0 + fi + if [[ "$step" == database.provision ]] && unrecognized_subcommand "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR"; then + # No provisioning command: the reader's way on is the CREATE ROLE, + # CREATE DATABASE and GRANT statements of the operate page. + if ! journey_blocker "$step" journey.needs.hand-written-sql sql \ + "$CELL" "$ADMIN_URL_FILE" "$MIGRATION_URL_FILE" "$RUNTIME_URL_FILE"; then + CELL_OVER=1 + fi + return 0 + fi + if mentions_tls "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR"; then + if ! journey_blocker "$step" journey.needs.certificate certificate "$CELL" "$RUNTIME_FILE"; then + CELL_OVER=1 + return 0 + fi + reader_command "$step" --concepts database-tls --typed "$typed" -- "$@" + return 0 + fi + stop_with_product_code "$step" "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" +} + +# database.provision and database.connect: the product's roles and database on +# the reader's PostgreSQL, then its schema. A product with no database has no +# command for either step. +step_database() { + local product=$1 + write_product_secrets "$product" + if [[ "$(field "$product" usesPostgres)" != true ]]; then + journey_pass database.provision + journey_pass database.connect + return 0 + fi + database_step database.provision "$TOOL provision --runtime-config $RUNTIME_FILE --admin-url-file $ADMIN_URL_FILE" -- \ + "$TOOL_BIN" provision --runtime-config "$RUNTIME_FILE" --admin-url-file "$ADMIN_URL_FILE" + [[ $CELL_OVER -eq 0 ]] || return 0 + case "$product" in + casework | messaging | scheduling | documents | coordinator) + database_step database.connect "$TOOL apply --runtime-config $RUNTIME_FILE" -- \ + "$TOOL_BIN" apply --runtime-config "$RUNTIME_FILE" --format json + ;; + breg) + journey_harness_failure "no database.connect recipe is written for breg: bregctl apply needs the package bregctl package builds from a bregctl test receipt, and bregctl test needs a schema-test credential binding document; extend step_database in own-provider.sh" + ;; + adapter) + journey_harness_failure "no database.connect recipe is written for adapter: it has no apply command, and its runtime reads the database URLs from secret:env references; extend step_database in own-provider.sh" + ;; + esac +} + +# The command that starts the product's runtime, as the reader types it. +serve_command() { + local product=$1 + case "$product" in + breg | coordinator) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE") ;; + casework | messaging | scheduling | documents) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE" serve) ;; + render) SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE") ;; + *) journey_harness_failure "no start recipe is written for $product; add one to serve_command in own-provider.sh" ;; + esac +} + +# server_gone: the open cell's server is no longer running. +server_gone() { + ! journey_process_running server +} + +# refresh_server_log: bring the saved, redacted log of the open cell's server +# (SERVER_LOG_OUT and SERVER_LOG_ERR, set at start) up to date. A server that +# has exited was saved by lib.sh when it stopped. +refresh_server_log() { + # shellcheck disable=SC2034 # journey_process_log sets it; only the refresh matters here + local ignored + if journey_process_running server; then + journey_process_log server ignored + fi +} + +# stop_server_after_failure: a cell that stopped after its server started +# cannot take the stop step, and the next cell needs the port, so the server +# is sent SIGTERM here by the process id lib.sh recorded in processes.txt. +# lib.sh's cleanup then collects its exit status and saves its log. +stop_server_after_failure() { + local pid='' product name + journey_process_running server || return 0 + while IFS=$'\t' read -r pid product name; do + [[ "$product" == "$CELL" && "$name" == server ]] && break + pid='' + done <"$JOURNEY_OUT/processes.txt" + [[ -n "$pid" ]] || journey_harness_failure "processes.txt has no server of $CELL" + kill -TERM "$pid" || journey_harness_failure "cannot send SIGTERM to the server of $CELL (pid $pid)" + if ! journey_poll 30 -- server_gone; then + kill -KILL "$pid" || journey_harness_failure "cannot stop the server of $CELL (pid $pid)" + journey_poll 10 -- server_gone || journey_harness_failure "the server of $CELL (pid $pid) is still running after SIGKILL" + fi +} + +# start and ready: the product's runtime, until it answers its readiness +# route. +step_start() { + local product=$1 status=0 ready_url + serve_command "$product" + port_is_free "$PORT" || journey_harness_failure "port $PORT is in use; the journey cannot start $product on it" + journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? + SERVER_LOG_OUT=$JOURNEY_STEP_STDOUT + SERVER_LOG_ERR=$JOURNEY_STEP_STDERR + if [[ $status -ne 0 ]]; then + if mentions_tls "$SERVER_LOG_OUT" "$SERVER_LOG_ERR"; then + if ! journey_blocker start journey.needs.certificate certificate "$CELL" "$RUNTIME_FILE"; then + CELL_OVER=1 + return 0 + fi + status=0 + journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? + SERVER_LOG_OUT=$JOURNEY_STEP_STDOUT + SERVER_LOG_ERR=$JOURNEY_STEP_STDERR + fi + if [[ $status -ne 0 ]]; then + stop_with_product_code start "$SERVER_LOG_OUT" "$SERVER_LOG_ERR" + return 0 + fi + fi + journey_pass start + ready_url=http://127.0.0.1:$PORT$READY_PATH + status=0 + journey_ready ready server --timeout 90 -- curl --silent --show-error --fail --output /dev/null "$ready_url" || status=$? + if [[ $status -ne 0 ]]; then + refresh_server_log + if [[ -z "${JOURNEY_PROCESS_STATUS:-}" ]]; then + journey_harness_failure "$product kept running but $ready_url did not answer 2xx within 90 seconds; see $SERVER_LOG_ERR" + fi + stop_with_product_code ready "$SERVER_LOG_OUT" "$SERVER_LOG_ERR" + return 0 + fi + journey_pass ready +} + +# token: a client-credentials token from the reader's provider. +step_token() { + local token_url=$KC_ISSUER/protocol/openid-connect/token status=0 + journey_http token --concepts client,grant,scopes \ + --typed "curl -X POST $token_url -d grant_type=client_credentials -d client_id=$CLIENT -d client_secret=\$SECRET" \ + --form grant_type=client_credentials --form "client_id=$CLIENT" --form-secret "client_secret=client-$CELL" \ + --capture-secret .access_token ACCESS_TOKEN POST "$token_url" || status=$? + if [[ $status -ne 0 ]]; then + journey_harness_failure "Keycloak refused the client credentials of $CLIENT (HTTP $JOURNEY_HTTP_STATUS); the realm is the journey's own setup, see $JOURNEY_STEP_STDOUT" + fi + # The audience and the scope come from the realm, the journey's own setup: + # a token without them would turn a realm mistake into a product refusal. + token_has_audience_and_scope ACCESS_TOKEN "$AUDIENCE" "$SCOPE" || + journey_harness_failure "the token Keycloak issued to $CLIENT lacks audience $AUDIENCE or scope $SCOPE; check keycloak/realm.json and the scope setup" + journey_pass token +} + +# token_has_audience_and_scope TOKEN_VARIABLE AUDIENCE SCOPE +token_has_audience_and_scope() { + local variable=$1 + shift + printf '%s' "${!variable}" | perl -MMIME::Base64 -MJSON::PP -e ' + local $/; my $token = ; + my $payload = (split /\./, $token)[1] // ""; + $payload =~ tr{-_}{+/}; + $payload .= "=" x ((4 - length($payload) % 4) % 4); + my $claims = decode_json(decode_base64($payload)); + my ($audience, $scope) = @ARGV; + my @aud = ref $claims->{aud} eq "ARRAY" ? @{ $claims->{aud} } : ($claims->{aud} // ()); + exit 1 unless grep { $_ eq $audience } @aud; + exit 1 unless grep { $_ eq $scope } split / /, ($claims->{scope} // ""); + exit 0;' "$@" +} + +# missing_claims TOKEN_VARIABLE CLAIM...: the CLAIMs the token's payload lacks, +# one per line. The token reaches perl through a pipe. +missing_claims() { + local variable=$1 + shift + [[ $# -gt 0 ]] || return 0 + printf '%s' "${!variable}" | perl -MMIME::Base64 -MJSON::PP -e ' + local $/; my $token = ; + my $payload = (split /\./, $token)[1] // ""; + $payload =~ tr{-_}{+/}; + $payload .= "=" x ((4 - length($payload) % 4) % 4); + my $claims = decode_json(decode_base64($payload)); + for my $name (@ARGV) { print "$name\n" unless exists $claims->{$name} }' "$@" || + journey_harness_failure "cannot read the claims of the token of $CELL" +} + +# logged_stage FILE...: the last authentication stage the product logged. +logged_stage() { + perl -e ' + my $stage = ""; + local $/; + for my $path (@ARGV) { + open my $fh, "<", $path or next; + my $text = <$fh>; + next unless defined $text; + while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2/g) { + $stage = defined $1 ? $1 : $3; + } + } + print $stage;' "$@" +} + +# call_request: the first authenticated request, made once more after an +# assist. +call_request() { + local -a options=(--bearer ACCESS_TOKEN) + case "$CELL" in + messaging) + options+=(--header 'Content-Type: application/json' --header 'Idempotency-Key: journey-first-call' + --data-file "$WORK/call-body.json") + ;; + render) + options+=(--header 'Content-Type: application/json' --data-file "$WORK/request.json") + ;; + esac + journey_http call "${options[@]}" "$CALL_METHOD" "http://127.0.0.1:$PORT$CALL_PATH" +} + +# render_request DATA TARGET: the request body of the Render tutorial. +render_request() { + jq -c '{issuedAt: "2026-09-16T10:32:00Z", data: .}' "$1" >"$2" +} + +# call: the first authenticated request. A refusal is named by the HTTP status +# and the stage the product logged, by the problem code it answered when its +# log names no stage, or is a claim-mapper stop when the token lacks a claim +# the product reads. +step_call() { + local status=0 stage='' missing attempt + case "$CELL" in + messaging) + journey_write_file "$WORK/call-body.json" < <(printf '%s\n' \ + '{"senderProfile":"reminders-sms","to":{"phone":"+15555550100"},"template":{"id":"appointment-reminder-sms","version":"1"},"locale":"en","data":{"name":"Ada Lovelace","day":"2026-10-01","office":"Central Registry Office"}}') + ;; + render) + journey_step call --typed "jq -c '{issuedAt: \"2026-09-16T10:32:00Z\", data: .}' fixtures/data.json > request.json" -- \ + render_request "$PROJECT/fixtures/data.json" "$WORK/request.json" || + journey_harness_failure "cannot build the Render request body; see $JOURNEY_STEP_STDERR" + ;; + esac + call_request || status=$? + if [[ $status -eq 0 ]]; then + journey_pass call + journey_reached t1 + return 0 + fi + [[ "$JOURNEY_HTTP_STATUS" != 000 ]] || + journey_harness_failure "the call to $CELL got no answer; see $JOURNEY_STEP_STDERR" + [[ -z "${JOURNEY_HTTP_CAPTURE_FAILED:-}" ]] || + journey_harness_failure "the call to $CELL answered 2xx without what the journey reads; see $JOURNEY_STEP_STDOUT" + # The refusal is logged as the response is written; wait a moment for it. + for attempt in 1 2 3; do + refresh_server_log + stage=$(logged_stage "$SERVER_LOG_OUT" "$SERVER_LOG_ERR") + [[ -z "$stage" ]] || break + [[ $attempt -eq 3 ]] || sleep 1 + done + # shellcheck disable=SC2086 # CLAIMS is a list of words + missing=$(missing_claims ACCESS_TOKEN $CLAIMS) + if [[ -n "$missing" && (-z "$stage" || "$stage" == profile) ]]; then + # shellcheck disable=SC2086 # missing is a list of words + if ! journey_blocker call journey.needs.claim-mapper mapper "$CELL" "$CLIENT" ACCESS_TOKEN $missing; then + CELL_OVER=1 + return 0 + fi + status=0 + call_request || status=$? + if [[ $status -eq 0 ]]; then + journey_reached t1 + return 0 + fi + refresh_server_log + stage=$(logged_stage "$SERVER_LOG_OUT" "$SERVER_LOG_ERR") + fi + if [[ -z "$stage" ]]; then + # A product whose log names no stage still names its refusal in the + # problem body. That code is recorded rather than a stage the journey + # would have to guess. + if [[ "${JOURNEY_HTTP_PROBLEM_CODE:-}" =~ ^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)*$ ]]; then + journey_fail call "product.$JOURNEY_HTTP_PROBLEM_CODE" + CELL_OVER=1 + return 0 + fi + journey_harness_failure "the call to $CELL answered HTTP $JOURNEY_HTTP_STATUS with problem code '${JOURNEY_HTTP_PROBLEM_CODE:-none}', and its log names no authentication stage; see $SERVER_LOG_ERR and extend own-provider.sh" + fi + if [[ "$STAGES" != *" $stage "* ]]; then + journey_harness_failure "the call to $CELL answered HTTP $JOURNEY_HTTP_STATUS and its log names the stage '$stage', which the table does not list; see $SERVER_LOG_ERR" + fi + journey_fail call "http.$JOURNEY_HTTP_STATUS.$stage" + CELL_OVER=1 +} + +# hook: the products whose runtime format has hook destinations need the +# receiver container the hook milestone adds; the others deliver nothing, so +# the step has no command for them. +step_hook() { + case "$CELL" in + breg | scheduling | documents) + journey_unreached hook "The product delivers hooks, and the journey has no receiver for them until the hook milestone (M8) adds one." + CELL_OVER=1 + ;; + *) journey_pass hook ;; + esac +} + +step_stop() { + if journey_stop stop server; then + journey_pass stop + else + journey_fail stop product.stop.ignored-signal + CELL_OVER=1 + fi +} + +# walk_product PRODUCT: walk one product through the steps. +walk_product() { + local product=$1 step + CELL=$product + CELL_OVER=0 + RUNTIME_FILE='' + # shellcheck disable=SC2034 # read by name through journey_http --bearer + ACCESS_TOKEN='' + MIGRATION_URL_FILE='' + RUNTIME_URL_FILE='' + SERVER_LOG_OUT='' + SERVER_LOG_ERR='' + journey_cell_begin "$product" + if [[ "$(field "$product" tier)" == supporting ]]; then + journey_unreached prepare "Supporting runtime. It starts beside its parent and is added to the journey when the parent's cell passes." + journey_cell_end + return 0 + fi + if [[ "$(field "$product" verifiesTokens)" != true && "$(field "$product" usesPostgres)" != true ]]; then + journey_unreached prepare "The product verifies no token and keeps no database, so the reader's own provider and PostgreSQL have nothing to serve it, and its tutorial's publication server is Python, which a journey does not run." + journey_cell_end + return 0 + fi + journey_workdir "$product" WORK + PROJECT=$WORK/$product + recipe "$product" + for step in prepare issuer database start token call hook stop; do + "step_$step" "$product" + [[ $CELL_OVER -eq 0 ]] || break + done + stop_server_after_failure + journey_cell_end +} + +# --------------------------------------------------------------------------- +# Setup and the cells + +NEEDS_ISSUER=0 +NEEDS_POSTGRES=0 +PRIMARY=() +for product in "${JOURNEY_PRODUCTS[@]}"; do + [[ "$(field "$product" tier)" == primary ]] || continue + [[ "$(field "$product" verifiesTokens)" == true || "$(field "$product" usesPostgres)" == true ]] || continue + PRIMARY+=("$product") + [[ "$(field "$product" verifiesTokens)" != true ]] || NEEDS_ISSUER=1 + [[ "$(field "$product" usesPostgres)" != true ]] || NEEDS_POSTGRES=1 +done + +if [[ ${#PRIMARY[@]} -gt 0 ]]; then + journey_resolve_binaries "${PRIMARY[@]}" + [[ $NEEDS_ISSUER -eq 0 ]] || start_keycloak + [[ $NEEDS_POSTGRES -eq 0 ]] || start_postgres + if [[ $NEEDS_ISSUER -eq 1 ]]; then + keycloak_admin_login + for product in "${PRIMARY[@]}"; do + recipe "$product" + keycloak_default_scope "$CLIENT" "$SCOPE" + if [[ "$product" == coordinator ]]; then + keycloak_service_account_subject "$CLIENT" COORDINATOR_SUBJECT + fi + done + fi + if [[ -n "$JOURNEY_PORT_BASE" ]]; then + PORT=$((JOURNEY_PORT_BASE + 4)) + METRICS_PORT=$((JOURNEY_PORT_BASE + 5)) + else + free_port PORT + free_port METRICS_PORT + [[ "$PORT" != "$METRICS_PORT" ]] || free_port METRICS_PORT + fi + jq -n --arg issuer "$ISSUER_KIND" --arg image "$KEYCLOAK_IMAGE" --arg realm "$REALM" \ + --arg issuerUrl "$KC_ISSUER" --arg postgres "$POSTGRES_IMAGE" --arg pgPort "$PG_PORT" \ + --arg port "$PORT" --arg metricsPort "$METRICS_PORT" \ + 'def opt: if . == "" then null else . end; + {schema: "registry.journey-own-provider/v1", issuer: $issuer, issuerImage: $image, realm: $realm, + issuerUrl: ($issuerUrl | opt), postgresImage: $postgres, postgresPort: ($pgPort | opt | if . == null then null else tonumber end), + productPort: ($port | tonumber), productMetricsPort: ($metricsPort | tonumber), + containers: {issuer: "kc", postgres: "pg"}}' >"$JOURNEY_OUT/own-provider.json" || + journey_harness_failure "cannot write $JOURNEY_OUT/own-provider.json" +fi + +for product in "${JOURNEY_PRODUCTS[@]}"; do + walk_product "$product" +done + +journey_finish diff --git a/products/platform/journeys/projects/coordinator/deployment.yaml b/products/platform/journeys/projects/coordinator/deployment.yaml new file mode 100644 index 0000000000..0176d191e0 --- /dev/null +++ b/products/platform/journeys/projects/coordinator/deployment.yaml @@ -0,0 +1,36 @@ +# The deployment block the own-provider journey adds by hand to the runtime +# file `coordinatorctl init` writes, which has none: the package it serves, the +# listener, the reader's own issuer and one caller policy, the audit file and +# the three keys. The block follows the Coordinator operate page. +# own-provider.sh replaces each @NAME@ with a value of the run (the package +# digest `coordinatorctl package` printed, the caller's subject in the +# reader's provider) before the reader "types" it, and the issuer step then +# points `issuer` at that provider. +deployment: + databaseId: coordinator-journey + runtimeRole: coordinator_runtime + packages: + - root: @PACKAGE@ + expectedDigest: @DIGEST@ + listener: + bind: 127.0.0.1:@PORT@ + tlsTermination: development-loopback + authentication: + issuer: https://identity.example.test/realms/registry + audience: urn:example:coordinator + scopeClaim: scope + jwksSource: + type: discovery + policies: + coordinator-producer: + subjects: [@SUBJECT@] + requiredScopes: [coordinator:start] + workflows: [@WORKFLOW@] + actions: [start, status] + auditFile: @WORK@/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/platform/journeys/projects/render/runtime.yaml b/products/platform/journeys/projects/render/runtime.yaml new file mode 100644 index 0000000000..55c910e949 --- /dev/null +++ b/products/platform/journeys/projects/render/runtime.yaml @@ -0,0 +1,19 @@ +# The Render runtime file the own-provider journey writes by hand, because +# `registry-render init` writes a bundle and no runtime file. It follows the +# runtime of the first-render-document tutorial with the OIDC block of the +# Render operate page in place of the API key. own-provider.sh replaces each +# @NAME@ with a path or port of the run before the reader "types" the file, and +# the issuer step then points `issuer` at the reader's own provider. +apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1 +kind: RenderRuntimeConfig +listener: + bind: 127.0.0.1:@PORT@ +package: + root: @WORK@/package +authentication: + oidc: + issuer: https://identity.example.test/realms/registry + audience: urn:example:render + allowedClients: [portal] +audit: + path: @WORK@/audit.jsonl From 07f18d9edc7d4abb819e1d8e449f926cfd68c240 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 03:43:41 +0100 Subject: [PATCH 019/136] feat(messaging): add messagingctl provision for roles and the database The runtime file's two database URLs name the roles, the database and both passwords, so the operate page's hand-written role and database SQL becomes one command, with --print-sql for an administrator who must run the script. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-messagingctl/Cargo.toml | 7 + crates/registry-messagingctl/src/lib.rs | 24 ++ crates/registry-messagingctl/src/provision.rs | 104 +++++++ .../tests/provision_cli.rs | 202 +++++++++++++ .../tests/provision_postgres.rs | 274 ++++++++++++++++++ .../src/content/docs/operate/messaging.mdx | 95 +++--- products/messaging/AGENTS.md | 4 + 8 files changed, 677 insertions(+), 34 deletions(-) create mode 100644 crates/registry-messagingctl/src/provision.rs create mode 100644 crates/registry-messagingctl/tests/provision_cli.rs create mode 100644 crates/registry-messagingctl/tests/provision_postgres.rs diff --git a/Cargo.lock b/Cargo.lock index 271af8ed2b..9a0f195d2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7681,6 +7681,7 @@ dependencies = [ "registry-platform-dispatch", "registry-platform-httputil", "registry-platform-oidc", + "registry-platform-provision", "registry-platform-testing", "registry-platform-yaml", "registry-rstack-dev", diff --git a/crates/registry-messagingctl/Cargo.toml b/crates/registry-messagingctl/Cargo.toml index 5260045d8c..2a3f50ee0a 100644 --- a/crates/registry-messagingctl/Cargo.toml +++ b/crates/registry-messagingctl/Cargo.toml @@ -17,6 +17,11 @@ name = "postgres_messages_cli" path = "tests/postgres_messages_cli.rs" required-features = ["postgres-test"] +[[test]] +name = "provision_postgres" +path = "tests/provision_postgres.rs" +required-features = ["postgres-test"] + [features] default = [] postgres-test = ["registry-messaging/postgres-test"] @@ -42,6 +47,7 @@ registry-platform-config.workspace = true registry-platform-crypto.workspace = true registry-platform-httputil.workspace = true registry-platform-oidc.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-thunderid-tooling = { workspace = true, features = ["session"] } @@ -61,6 +67,7 @@ zeroize.workspace = true [dev-dependencies] registry-platform-audit.workspace = true registry-platform-dispatch = { workspace = true, features = ["postgres"] } +registry-platform-provision = { workspace = true, features = ["test-support"] } registry-platform-testing.workspace = true tokio-postgres.workspace = true tower.workspace = true diff --git a/crates/registry-messagingctl/src/lib.rs b/crates/registry-messagingctl/src/lib.rs index ae3a3402f0..22bd26eb93 100644 --- a/crates/registry-messagingctl/src/lib.rs +++ b/crates/registry-messagingctl/src/lib.rs @@ -12,6 +12,8 @@ //! reports the package digest and renders every template's sample. //! - `preview` renders one template version with given data, offline, and //! in JSON prints the exact bytes the runtime's preview route answers. +//! - `provision` creates the roles and the database the runtime file names, +//! or with `--print-sql` prints the SQL that does. //! - `plan` reads the configured package, activation ledger, schema, and //! runtime role without writing; `apply` performs that activation with //! migration authority; `status` reads the resulting history with the @@ -80,6 +82,7 @@ use uuid::Uuid; mod cli_contract_tests; mod dev; mod identity_facts; +mod provision; mod report; mod selected_binary; mod starter; @@ -117,6 +120,8 @@ enum Command { Check(CheckArgs), /// Render one template version with the given data, offline. Preview(PreviewArgs), + /// Create the roles and the database the runtime file names, or print the SQL. + Provision(registry_platform_provision::ProvisionArgs), /// Report what activating the configured package would change, without writing. Plan(ActivationArgs), /// Apply schema changes and record the configured package as active. @@ -742,6 +747,7 @@ where let command = command_path(&cli.command); let outcome = match cli.command { Command::Serve(args) => return serve(args, cli.format, format_requested, stdout, stderr), + Command::Provision(args) => return provision(&args, cli.format), Command::Dev(args) => return dev::run(args, cli.format, stdout, stderr), Command::RstackDev(args) => return registry_rstack_dev::run(args, stdout, stderr), Command::Api(args) => return api(*args, format_requested, stderr), @@ -773,6 +779,7 @@ fn command_path(command: &Command) -> &'static str { Command::Generate(GenerateCommand::IdentityFacts(_)) => "generate identity-facts", Command::Check(_) => "check", Command::Preview(_) => "preview", + Command::Provision(_) => "provision", Command::Plan(_) => "plan", Command::Apply(_) => "apply", Command::Status(_) => "status", @@ -789,6 +796,23 @@ fn command_path(command: &Command) -> &'static str { } } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: ®istry_platform_provision::ProvisionArgs, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "messagingctl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + shared, + provision::load, + ) +} + fn api( args: registry_cli_api::ApiArgs, format_requested: bool, diff --git a/crates/registry-messagingctl/src/provision.rs b/crates/registry-messagingctl/src/provision.rs new file mode 100644 index 0000000000..46df660003 --- /dev/null +++ b/crates/registry-messagingctl/src/provision.rs @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `messagingctl provision`: the shared command over Messaging's +//! runtime file. The file's two database URLs name the roles, the database +//! and both passwords, so nothing is written twice. + +use std::path::Path; + +use registry_messaging::config::{startup_report, RuntimeConfig}; +use registry_messaging_core::MESSAGING_RUNTIME_KIND; +use registry_platform_config::describe_secret_failure; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +/// Messaging keeps its tables in `public`, handed to the migration +/// role, and needs no extension. +fn product() -> ProductDatabase { + ProductDatabase { + product: "messaging", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } +} + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(MESSAGING_RUNTIME_KIND.to_owned()); + Box::new(diagnostic) +} + +/// Reads the runtime file exactly as `apply` does and resolves the two +/// database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be resolved against the working directory" + .to_owned(), + "Pass --runtime-config as a path that exists.", + ) + })?; + let config = RuntimeConfig::load(&absolute).map_err(|error| { + match startup_report(&absolute, &error) + .and_then(|report| report.diagnostics().first().cloned()) + { + Some(diagnostic) => Box::new(diagnostic), + None => refused( + "config.refused", + "", + error.to_string(), + "Correct the runtime file, then run provision again.", + ), + } + })?; + let secrets = config.secret_providers.resolver().map_err(|error| { + refused( + "config.refused", + "/secretProviders", + error.to_string(), + "Correct secretProviders in the runtime file, then run provision again.", + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refused( + "config.refused", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; + let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let ca_pem = config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + Ok(ProvisionInput { + product: product(), + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs new file mode 100644 index 0000000000..cacbe39cce --- /dev/null +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `messagingctl provision` without a database: print mode reads the runtime +//! file and writes the script without connecting or printing a password, and +//! the administrator flags refuse the combinations the shared command +//! refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file over a built package, whose secret files name a migration +/// and a runtime login on one server that does not exist, so a connection +/// attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!( + "postgresql://messaging_migration:{MIGRATION_PASSWORD}@db.invalid:5432/messaging" + ), + ), + ( + "runtime-database-url", + format!("postgresql://messaging_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/messaging"), + ), + ("audit-key", "0123456789abcdef0123456789abcdef".to_owned()), + ( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + // The loader verifies the package the file names, as `apply` does. + let project = directory.join("project"); + let package = directory.join("package"); + for arguments in [ + vec!["init", project.to_str().unwrap()], + vec![ + "package", + project.to_str().unwrap(), + "--output", + package.to_str().unwrap(), + ], + ] { + let output = ctl(&arguments); + assert_eq!(output.status.code(), Some(0), "{arguments:?}"); + } + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/messaging/runtime/v1alpha1 +kind: MessagingRuntimeConfig +identity: + databaseId: registry-messaging-ctl-test +package: + root: {package} +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url +authentication: + oidc: + issuer: https://identity.example.test + audience: urn:example:messaging + allowedClients: [case-system, operations-console] + jwksSource: + type: static + documentRef: secret:file/jwks.json +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/audit-key +", + package = package.display(), + secrets = secrets.display(), + audit = directory.join("audit.ndjson").display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_messagingctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in ["messaging_migration", "messaging_runtime", "messaging"] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "messaging"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "messaging"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } + + // The tool's global flag, after the verb, selects the same report. + let after = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--format", + "json", + ]); + assert_eq!(after.status.code(), Some(0)); + assert_eq!(String::from_utf8(after.stdout).unwrap(), stdout); +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for arguments in [ + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "MESSAGING_ADMIN_URL", + ], + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "MESSAGING_ADMIN_URL", + ], + vec!["provision", "--runtime-config", &runtime], + ] { + let output = ctl(&arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + } +} diff --git a/crates/registry-messagingctl/tests/provision_postgres.rs b/crates/registry-messagingctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..59d48bf16c --- /dev/null +++ b/crates/registry-messagingctl/tests/provision_postgres.rs @@ -0,0 +1,274 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `messagingctl provision` against a real server, then `apply` and the +//! runtime on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. The administrator sessions of this suite +//! use verified TLS, so the server must offer it. Without the variables the +//! test fails on the spot: a skipped database test is not database +//! verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::PathBuf; +use std::process::Command; +use std::time::Duration; + +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use serde_json::Value; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use uuid::Uuid; + +/// One deployment directory and the superuser session that creates the +/// roles `provision` is run from. +struct Deployment { + directory: tempfile::TempDir, + admin: tokio_postgres::Client, +} + +impl Deployment { + async fn new() -> Self { + let (url, ca_pem) = provision_test_env(); + let admin = connect_verified(&url, &ca_pem, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let deployment = Self { directory, admin }; + deployment.secret("audit-key", "0123456789abcdef0123456789abcdef"); + // The runtime verifies tokens against a static key set, so it starts + // without reaching the issuer. + deployment.secret( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + ); + deployment + } + + fn path(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + + fn runtime(&self) -> String { + self.path("runtime.yaml").display().to_string() + } + + /// Write or replace the secret file `name` with `value`. + fn secret(&self, name: &str, value: &str) { + let path = self.path("secrets").join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + + /// Write the runtime document over `package`, listening on `bind`, with + /// the database connections verified against the CA secret. + fn write_runtime(&self, package: &std::path::Path, bind: &str) { + let document = format!( + "\ +apiVersion: id.registrystack.org/formats/messaging/runtime/v1alpha1 +kind: MessagingRuntimeConfig +identity: + databaseId: registry-messaging-ctl-test +package: + root: {package} +listener: + bind: {bind} + tlsTermination: development-loopback +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/postgres-ca.pem +authentication: + oidc: + issuer: https://identity.example.test + audience: urn:example:messaging + allowedClients: [case-system, operations-console] + jwksSource: + type: static + documentRef: secret:file/jwks.json +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/audit-key +", + package = package.display(), + secrets = self.path("secrets").display(), + audit = self.path("audit.ndjson").display(), + ); + std::fs::write(self.path("runtime.yaml"), document).unwrap(); + } +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&str]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_messagingctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stdout))); + (output.status.code().unwrap(), report) +} + +/// Read one HTTP status code from `GET path`, or none when nothing answers. +async fn http_status(address: &str, path: &str) -> Option { + let mut stream = tokio::net::TcpStream::connect(address).await.ok()?; + stream + .write_all( + format!("GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await + .ok()?; + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.ok()?; + let text = String::from_utf8_lossy(&response); + text.split_whitespace().nth(1)?.parse().ok() +} + +/// `provision` as the operate page runs it: from the administrator URL of a +/// non-superuser that holds only `CREATEROLE` and `CREATEDB`, over a runtime +/// file whose two URLs name the roles and the database. `apply` then +/// activates the package over the migration credential, and the runtime +/// starts over the runtime credential and answers its readiness route. +#[tokio::test] +async fn provision_then_apply_then_serve_with_split_roles() { + let deployment = Deployment::new().await; + let project = deployment.path("project").display().to_string(); + let (code, report) = ctl(&["init", &project]); + assert_eq!(code, 0, "{report:#}"); + let package = deployment.path("package"); + let (code, report) = ctl(&["package", &project, "--output", package.to_str().unwrap()]); + assert_eq!(code, 0, "{report:#}"); + + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let bind = format!("127.0.0.1:{port}"); + deployment.write_runtime(&package, &bind); + let runtime = deployment.runtime(); + + let (base_url, ca) = provision_test_env(); + deployment.secret("postgres-ca.pem", &String::from_utf8_lossy(&ca)); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let (owner, migration, runtime_role, database) = ( + format!("messaging_owner_{suffix}"), + format!("messaging_mig_{suffix}"), + format!("messaging_rt_{suffix}"), + format!("messaging_db_{suffix}"), + ); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let (owner_password, migration_password, runtime_password) = ( + password("owner"), + password("migration"), + password("runtime"), + ); + deployment + .admin + .batch_execute(&format!( + "CREATE ROLE {owner} LOGIN PASSWORD '{owner_password}' NOSUPERUSER CREATEROLE CREATEDB" + )) + .await + .unwrap(); + + let base = registry_platform_provision::admin_config(&base_url, Some(&ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, port) = (base.host(), base.port()); + let url = |role: &str, password: &str, database: &str| { + format!("postgresql://{role}:{password}@{host}:{port}/{database}") + }; + deployment.secret( + "migration-database-url", + &url(&migration, &migration_password, &database), + ); + deployment.secret( + "runtime-database-url", + &url(&runtime_role, &runtime_password, &database), + ); + let admin_file = deployment.path("admin-url"); + std::fs::write(&admin_file, url(&owner, &owner_password, "postgres")).unwrap(); + std::fs::set_permissions(&admin_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let (code, provisioned) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], database.as_str()); + for secret in [&owner_password, &migration_password, &runtime_password] { + assert!( + !provisioned.to_string().contains(secret.as_str()), + "the report holds no password" + ); + } + + let (code, again) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "a second run converges: {again:#}"); + + let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); + assert_eq!(code, 0, "{applied:#}"); + + let server = tokio::spawn({ + let runtime = runtime.clone(); + async move { + registry_messaging::runtime::serve_from_path( + &runtime, + registry_messaging::dispatch::Transports::new(), + ) + .await + } + }); + let mut ready = None; + for _ in 0..300 { + if server.is_finished() { + break; + } + ready = http_status(&bind, "/ready").await; + if ready == Some(200) { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + if server.is_finished() { + let outcome = server.await.expect("the server task does not panic"); + panic!("the service stopped instead of serving: {outcome:?}"); + } + assert_eq!(ready, Some(200), "the service never reported ready"); + server.abort(); + + for statement in [ + format!("DROP DATABASE {database} WITH (FORCE)"), + format!("DROP ROLE {runtime_role}"), + format!("DROP ROLE {migration}"), + format!("DROP ROLE {owner}"), + ] { + deployment.admin.batch_execute(&statement).await.unwrap(); + } +} diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index af0d3ed354..67518531f7 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -93,37 +93,6 @@ Neither acceptance nor `submitted` is proof of delivery to the recipient or of l {/* TODO[evidence]: cite a test that shows a message moving from accepted to failed or unknown after the 202. */} -## Provision PostgreSQL - -Create the roles and the database, then hand the schema to the migration role: - -```sql -CREATE ROLE messaging_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS; -CREATE ROLE messaging_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS; -CREATE DATABASE messaging; -``` - -Set each role's password with `\password messaging_migration` and `\password messaging_runtime` in -`psql`, which prompts for it instead of taking it in a statement. - -In the `messaging` database: - -```sql -REVOKE ALL ON DATABASE messaging FROM PUBLIC; -GRANT CONNECT ON DATABASE messaging TO messaging_migration, messaging_runtime; -ALTER SCHEMA public OWNER TO messaging_migration; -REVOKE ALL ON SCHEMA public FROM PUBLIC; -GRANT USAGE ON SCHEMA public TO messaging_runtime; -ALTER DEFAULT PRIVILEGES FOR ROLE messaging_migration IN SCHEMA public - GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO messaging_runtime; -ALTER DEFAULT PRIVILEGES FOR ROLE messaging_migration IN SCHEMA public - GRANT USAGE, SELECT ON SEQUENCES TO messaging_runtime; -``` - -{/* Evidence: crates/registry-messaging/migrations; crates/registry-messaging/src/store.rs. */} - ## Write the runtime file The package carries no runtime file. `messagingctl init ` writes a starter project with @@ -209,9 +178,9 @@ unset value Write `smtp-username`, `smtp-password`, `sms-gateway-token`, and `sms-gateway-callback-key` the same way. Each must be a regular file owned by the runtime user, mode `0400` or `0600`, with one link. -`serve` never reads the migration credential; only `apply` and `retention erase-expired` connect -with it. Write `migration-database-url`, the URL for `messaging_migration`, only on the host that -runs those two commands. +`serve` never reads the migration credential; only `provision`, `apply`, and +`retention erase-expired` read it. Write `migration-database-url`, the URL for +`messaging_migration`, only on the host that runs those commands. :::caution[Keep the audit key] The audit key derives the pseudonyms the journal uses for callers and recipients. Rotating it @@ -255,6 +224,64 @@ reaching a database. {/* Evidence: crates/registry-messagingctl/src/lib.rs, check(); observed with messagingctl 0.42.0-dev on 2026-10-19, paths replaced. */} +## Provision PostgreSQL + +Your runtime file already names the roles, their passwords, and the database. They are the URLs in +`database.migrationUrlRef` and `database.runtimeUrlRef`. `provision` reads the runtime file and the +package it names, so write the file and build the package first. Put both database URLs in their +secret files, then run `messagingctl provision` once as a PostgreSQL role that can create roles and +databases: + +```sh +messagingctl provision --runtime-config /etc/registry-messaging/runtime.yaml --admin-url-file admin-url +``` + +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and +`CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, +use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set +`database.caBundleRef` in the runtime file to trust a private CA. The command never prints the +administrator URL or a password. + +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it + from `PUBLIC`. + +Run it again at any time. It creates only what is missing. It refuses a role that exists with a +different password than its URL holds, and tells you which role. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a +`\password` line that prompts for the password in `psql`, so the script holds no password: + +```sql +SET createrole_self_grant = 'set,inherit'; +CREATE ROLE "messaging_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "messaging_migration" +CREATE ROLE "messaging_runtime" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "messaging_runtime" +CREATE DATABASE "messaging" WITH ALLOW_CONNECTIONS false; +REVOKE ALL ON DATABASE "messaging" FROM PUBLIC; +GRANT CONNECT ON DATABASE "messaging" TO "messaging_migration", "messaging_runtime"; +ALTER DATABASE "messaging" ALLOW_CONNECTIONS true; +\connect "messaging" +REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "messaging_migration"; +``` + +The names come from your URLs. Add `--format json` for a report of each statement and its outcome. + +`provision` grants the runtime role nothing beyond `CONNECT`. `apply`, in the next section, grants +it its access to the schema and the Messaging tables and sequences. The runtime requires TLS on +its database connection and refuses one it cannot verify; `database.caBundleRef` names the CA +bundle when a private CA fronts PostgreSQL. + +{/* Evidence: crates/registry-messagingctl/src/provision.rs; + crates/registry-messaging/migrations; crates/registry-messaging/src/store.rs. */} + ## Record and serve the package Review what activation would change. `plan` connects with the runtime credential and writes diff --git a/products/messaging/AGENTS.md b/products/messaging/AGENTS.md index 0ffcc8d06b..037bfb183f 100644 --- a/products/messaging/AGENTS.md +++ b/products/messaging/AGENTS.md @@ -33,3 +33,7 @@ examples, and product-local verification scripts. Read the workspace - PostgreSQL verification requires a disposable database and the `postgres-test` feature. A test binary that skips because its database URL is absent is not database verification. + The `provision_postgres` target of `registry-messagingctl` needs + `PROVISION_TEST_DATABASE_URL`, a disposable superuser URL (`sslmode=verify-full` + on a server that offers verified TLS), and + `PROVISION_TEST_DATABASE_CA`, the path of the CA PEM. It fails without them. From 57350b03f301930fb84a2455f5d98ec2b3c500ce Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 03:53:22 +0100 Subject: [PATCH 020/136] test(platform): add the promote journey and journey assists, and run them in CI test(platform): add journey assists so a run can pass stops main cannot clear yet A later milestone is measured against the same counters as an assisted run on main. Each assist use counts as a pass-rule violation. The journey reads a stage from a log line with colour escapes, and handles the token type and claim mapper refusals in order. test(platform): add the promote acceptance journey and its observed stops Promote takes the files a development journey ended with and starts them as production, lists the refusals, applies each fix and checks the contract is the same. On main every product stops at input because no development journey finishes unassisted, and an assisted Scheduling run lists nothing to refuse because no shared posture exists yet. chore(ci): run the token corpus, the provisioning suite and the acceptance journeys The acceptance journeys run in ratchet mode with --strict, so a change that fixes a cell must delete its row in the same commit. The shared provisioning suite needs PostgreSQL 17 with PostGIS and a server below the floor, both over verified TLS, and fails rather than skips without them. The token corpus test needs a feature no platform crate enables, so it runs as its own step. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 77 ++- .github/scripts/test_ci_changes.py | 528 ++++++++++++++++- .github/workflows/ci.yml | 368 +++++++++++- .github/workflows/nightly-rust-coverage.yml | 139 ++++- products/platform/journeys/README.md | 2 + .../platform/journeys/expected-failures.yaml | 93 +-- products/platform/journeys/lib-assists.sh | 234 ++++++++ products/platform/journeys/own-provider.sh | 34 +- products/platform/journeys/promote.sh | 544 ++++++++++++++++++ 9 files changed, 1968 insertions(+), 51 deletions(-) create mode 100644 products/platform/journeys/lib-assists.sh create mode 100755 products/platform/journeys/promote.sh diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 4914488620..979b387f7a 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -168,6 +168,66 @@ # change to either host runs them; the shard builds both before it tests. RSTACK_DEV_HOST_PACKAGES = frozenset({"registry-bregctl", "registry-caseworkctl"}) +# The acceptance journeys start every runtime and `*ctl` tool in their product +# column (products/platform/journeys/products.yaml; test_ci_changes.py checks +# this set against it), `rstack dev`, and the ThunderID tooling the product +# tools link for their development issuer. The starters the journeys copy +# live in product directories and product crates, whose paths already seed +# these packages. +JOURNEY_PACKAGES = frozenset( + { + "registry-adapter", + "registry-adapter-job", + "registry-adapterctl", + "registry-breg", + "registry-breg-mcp", + "registry-breg-review", + "registry-bregctl", + "registry-casework", + "registry-caseworkctl", + "registry-coordinator", + "registry-discovery", + "registry-discoveryctl", + "registry-documents", + "registry-documentsctl", + "registry-evidence", + "registry-evidence-oid4vci", + "registry-evidence-oid4vp", + "registry-evidencectl", + "registry-mcp", + "registry-messaging", + "registry-messagingctl", + "registry-render", + "registry-scheduling", + "registry-schedulingctl", + "registry-thunderid-tooling", + } +) | RSTACK_DEV_HARNESS_PACKAGES +# The journey scripts, their tables, the realm and the per-product inputs. +JOURNEY_INPUTS = ("products/platform/journeys/**",) + +# The token fixture corpus, read by the corpus test in +# registry-platform-testing and by the token characterisation test of every +# runtime that verifies a token. The corpus is not a crate, so its path names +# those crates directly instead of relying on the reverse-dependency closure. +TOKEN_FIXTURE_CORPUS = "products/platform/conformance/tokens/" +TOKEN_FIXTURE_PACKAGES = frozenset( + { + "registry-platform-testing", + "registry-adapter", + "registry-breg", + "registry-casework", + "registry-coordinator", + "registry-documents", + "registry-evidence", + "registry-evidence-oid4vci", + "registry-mcp-edge", + "registry-messaging", + "registry-render", + "registry-scheduling", + } +) + # The runtime configuration conformance gate reads the sources of the runtimes # it holds rows for, their generated runtime schemas, and the canonical shared # configuration blocks schema. A product that joins the gate joins this set. @@ -1238,6 +1298,8 @@ def classify( seeds.update(MANIFEST_PACKAGES) elif path.startswith("products/platform/"): seeds.update(PLATFORM_PACKAGES) + if path.startswith(TOKEN_FIXTURE_CORPUS): + seeds.update(TOKEN_FIXTURE_PACKAGES) elif path.startswith("products/breg/"): seeds.update(BREG_PACKAGES) elif path.startswith("products/casework/"): @@ -1566,6 +1628,12 @@ def classify( or bool(affected & BREG_EVIDENCE_COMPOSITION_PACKAGES) ) + acceptance_journeys = integration and ( + complete + or any(matches(path, *JOURNEY_INPUTS) for path in paths) + or bool(affected & JOURNEY_PACKAGES) + ) + matrix = [] for shard_name, shard_packages in SHARDS.items(): selected = sorted(affected.intersection(shard_packages)) @@ -1596,6 +1664,12 @@ def classify( for path in paths ) ) + # The provisioning PostgreSQL suite runs in the contracts-journeys lane, + # after that lane's TLS proof makes its PostGIS 17 service TLS-only. It + # joins only the breg_contracts output: breg_integration and + # casework_postgres read the selection above, so the provisioning crate + # on its own does not select them. + provision_postgres = "registry-platform-provision" in affected outputs = { "full_sweep": full_sweep, @@ -1617,7 +1691,7 @@ def classify( or bool(affected & DISCOVERY_PACKAGES) or any(matches(path, *DISCOVERY_PROVIDER_INPUTS) for path in paths) or any(matches(path, *DISCOVERY_TUTORIAL_INPUTS) for path in paths), - "breg_contracts": breg_contracts, + "breg_contracts": breg_contracts or provision_postgres, "evidence_contracts": bool(affected & EVIDENCE_PACKAGES), "evidence_assurance": evidence_assurance, "evidence_postgres": bool(affected & EVIDENCE_POSTGRES_PACKAGES), @@ -1660,6 +1734,7 @@ def classify( "render_tutorial": render_tutorial, "scheduling_tutorial": scheduling_tutorial, "breg_evidence_composition": breg_evidence_composition, + "acceptance_journeys": acceptance_journeys, "identifiers": identifiers, } return outputs diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 4a7a620b09..3771f79418 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -28,7 +28,10 @@ EVIDENCE_AUTHORING_GUIDE_IMPLEMENTATION_INPUTS, EVIDENCE_TUTORIAL_INPUTS, IDENTIFIER_CATALOG_INPUTS, + JOURNEY_PACKAGES, REGISTRY_RECORD_CROSS_PRODUCT_INPUTS, + TOKEN_FIXTURE_CORPUS, + TOKEN_FIXTURE_PACKAGES, BREG_PACKAGES, CASEWORK_PACKAGES, DOCUMENTS_PACKAGES, @@ -75,6 +78,74 @@ ) AUTHORING_SCHEMA_DIRECTORY = Path("crates/registry-evidencectl/schemas/authoring") +# The acceptance journeys' directory and the ratchet-mode options every CI +# call of a journey script carries. +JOURNEYS = Path("products/platform/journeys") +JOURNEY_RATCHET = "--expected products/platform/journeys/expected-failures.yaml --strict" +JOURNEY_SCRIPTS = { + "own-provider.sh": "own-provider", + "promote.sh": "own-provider", + "rstack-dev.sh": "rstack-dev", +} + +# The Base Registry Engine lane that runs the provisioning PostgreSQL suite +# after its own TLS proof. +PROVISION_POSTGRES_LANE = "contracts-journeys" + +# The steps that give a coverage job the provisioning suite's two TLS +# servers, in their order before the coverage run, and the step after it +# that removes the PostgreSQL 16 server. +PROVISION_SERVER_STEPS = ( + "Serve the provisioning PostGIS service over TLS", + "Start PostgreSQL 16 for the provisioning floor test", + "Serve PostgreSQL 16 over TLS for the provisioning floor test", + "Bundle the provisioning servers' CAs", +) +PROVISION_STOP_STEP = "Stop PostgreSQL 16 for the provisioning floor test" +# The steps a coverage job shares, key for key, with the contracts-journeys lane. +PROVISION_LANE_STEPS = PROVISION_SERVER_STEPS[1:3] + (PROVISION_STOP_STEP,) + + +def provision_test_variables() -> set[str]: + """Every PROVISION_TEST_* variable the provisioning PostgreSQL suite reads.""" + + return set( + re.findall( + r'"(PROVISION_TEST_[A-Z_]+)"', + Path("crates/registry-platform-provision/tests/postgres.rs").read_text( + encoding="utf-8" + ), + ) + ) + + +def journey_products() -> dict[str, Any]: + """The journeys' product column, read from its checked-in table.""" + + return yaml.safe_load((JOURNEYS / "products.yaml").read_text(encoding="utf-8")) + + +def without_dependency_edges(metadata: dict[str, Any]) -> dict[str, Any]: + """The same workspace with every dependency edge removed. + + A path then reaches only the packages the classifier seeds for it, so a + test sees the path mapping itself rather than what the reverse-dependency + closure adds. + """ + + return { + **metadata, + "packages": [ + {**package, "dependencies": []} for package in metadata["packages"] + ], + } + + +def folded_command(step: dict[str, Any]) -> str: + """A step's run text with continuation lines joined and spaces collapsed.""" + + return " ".join(step.get("run", "").replace("\\\n", " ").split()) + def config_conformance_runner() -> Any: """The configuration conformance corpus runner, loaded as a module.""" @@ -427,6 +498,9 @@ def test_deferred_ci_work_keeps_its_selector_and_explicit_status_guard( "breg-evidence-composition": ( "needs.changes.outputs.breg_evidence_composition == 'true'" ), + "acceptance-journeys": ( + "needs.changes.outputs.acceptance_journeys == 'true'" + ), "docs-archives": "needs.changes.outputs.docs_archives == 'true'", "config-conformance": ( "needs.changes.outputs.config_conformance == 'true'" @@ -547,6 +621,7 @@ def test_ci_scheduling_graph_retains_every_job_and_aggregate_dependency( "render-tutorial", "scheduling-tutorial", "breg-evidence-composition", + "acceptance-journeys", "evidence-anchors", "docs", "docs-required", @@ -626,6 +701,7 @@ def test_ci_scheduling_graph_retains_every_job_and_aggregate_dependency( "render-tutorial", "scheduling-tutorial", "breg-evidence-composition", + "acceptance-journeys", "evidence-anchors", "docs", "client-bindings", @@ -668,6 +744,7 @@ def test_final_aggregate_flattens_rust_results_with_equivalent_outcomes( "render-tutorial", "scheduling-tutorial", "breg-evidence-composition", + "acceptance-journeys", "evidence-anchors", "docs", "client-bindings", @@ -678,7 +755,7 @@ def test_final_aggregate_flattens_rust_results_with_equivalent_outcomes( final_needs, previous_final_needs.difference({"rust-result"}).union(rust_needs), ) - self.assertEqual(43, len(final_needs)) + self.assertEqual(44, len(final_needs)) # Platform line coverage publishes from main and the nightly sweep; # it does not hold the merge queue. self.assertNotIn("platform-coverage", final_needs) @@ -983,6 +1060,7 @@ def test_final_aggregate_refuses_a_selected_integration_job_that_skipped( "breg-tutorial": "breg_tutorial", "casework-tutorial": "casework_tutorial", "breg-evidence-composition": "breg_evidence_composition", + "acceptance-journeys": "acceptance_journeys", "deployment": "deployment", } @@ -1821,23 +1899,127 @@ def test_platform_coverage_has_the_shared_activation_database(self) -> None: def test_nightly_platform_coverage_has_the_pull_request_database(self) -> None: # The nightly platform shard runs the same --all-features build as # platform-coverage, whose PostgreSQL tests fail rather than skip - # without their database, so it needs the same service and URLs. + # without their databases, so it needs the same services, the same + # provisioning servers and the same test variables. pull_request = self.workflow_jobs["platform-coverage"] nightly = yaml.safe_load( Path(".github/workflows/nightly-rust-coverage.yml").read_text() )["jobs"]["rust"] self.assertEqual(nightly.get("services"), pull_request["services"]) - def database_urls(job: dict[str, Any], step_name: str) -> dict[str, str]: + def test_variables(job: dict[str, Any], step_name: str) -> dict[str, str]: step = next(step for step in job["steps"] if step.get("name") == step_name) return { name: value for name, value in step.get("env", {}).items() - if name.endswith("_DATABASE_URL") + if "_TEST_" in name } - expected = database_urls(pull_request, "Enforce platform line coverage") + expected = test_variables(pull_request, "Enforce platform line coverage") self.assertTrue(expected) - self.assertEqual(database_urls(nightly, "Run shard with coverage"), expected) + self.assertLessEqual(provision_test_variables(), set(expected)) + self.assertEqual(test_variables(nightly, "Run shard with coverage"), expected) + + # The provisioning servers' steps match key for key. In the nightly + # sweep only the platform shard, built with --all-features, runs them. + pull_request_steps = {step.get("name"): step for step in pull_request["steps"]} + nightly_names = [step.get("name") for step in nightly["steps"]] + nightly_steps = dict(zip(nightly_names, nightly["steps"])) + for name in (*PROVISION_SERVER_STEPS, PROVISION_STOP_STEP): + with self.subTest(step=name): + for key in ("id", "shell", "env", "run"): + self.assertEqual( + pull_request_steps[name].get(key), nightly_steps[name].get(key), key + ) + for name in PROVISION_SERVER_STEPS: + with self.subTest(step=name): + self.assertEqual("matrix.name == 'platform'", nightly_steps[name]["if"]) + self.assertEqual( + "always() && matrix.name == 'platform' && " + "steps.provision-postgres-16.outputs.container_id != ''", + nightly_steps[PROVISION_STOP_STEP]["if"], + ) + indices = [nightly_names.index(name) for name in PROVISION_SERVER_STEPS] + run = nightly_names.index("Run shard with coverage") + self.assertEqual(sorted(indices), indices) + self.assertLess(nightly_names.index("Checkout"), indices[0]) + self.assertLess(indices[-1], run) + self.assertLess(run, nightly_names.index(PROVISION_STOP_STEP)) + + def test_platform_coverage_serves_the_provisioning_suite(self) -> None: + # --all-features enables registry-platform-provision's postgres-test, + # whose suite fails rather than skips without its two TLS servers. + job = self.workflow_jobs["platform-coverage"] + lane = self.workflow_jobs["breg-contracts"] + service = job["services"]["postgis"] + self.assertEqual(lane["services"]["postgres"]["image"], service["image"]) + self.assertEqual(["5432/tcp"], service["ports"]) + + steps = job["steps"] + names = [step.get("name") for step in steps] + coverage = names.index("Enforce platform line coverage") + indices = [names.index(name) for name in PROVISION_SERVER_STEPS] + self.assertEqual(sorted(indices), indices) + self.assertLess(names.index("Checkout"), indices[0]) + self.assertLess(indices[-1], coverage) + stop = names.index(PROVISION_STOP_STEP) + self.assertLess(coverage, stop) + for index in indices: + with self.subTest(step=names[index]): + self.assertNotIn("if", steps[index]) + self.assertEqual( + "always() && steps.provision-postgres-16.outputs.container_id != ''", + steps[stop]["if"], + ) + + # The PostgreSQL 16 server is started, secured and removed exactly as + # the contracts-journeys lane does it. + lane_steps = {step.get("name"): step for step in lane["steps"]} + for name in PROVISION_LANE_STEPS: + with self.subTest(step=name): + for key in ("id", "shell", "env", "run"): + self.assertEqual( + lane_steps[name].get(key), steps[names.index(name)].get(key), key + ) + + # The service is made TLS-only by the lane's own script. + service_tls = steps[indices[0]] + self.assertEqual( + "${{ job.services.postgis.id }}", service_tls["env"]["SERVICE_CONTAINER_ID"] + ) + self.assertIn("BREG_TEST_TLS_SETUP_ONLY=1", folded_command(service_tls)) + self.assertIn( + "products/breg/scripts/test-postgres-tls.sh", folded_command(service_tls) + ) + + # The bundle joins the two CA files the TLS steps write. + bundle = steps[indices[3]] + self.assertEqual( + service_tls["env"]["SERVICE_CA_PEM_PATH"], bundle["env"]["SERVICE_CA_PEM_PATH"] + ) + self.assertEqual( + lane_steps[PROVISION_SERVER_STEPS[2]]["env"]["OLD_CA_PEM_PATH"], + bundle["env"]["OLD_CA_PEM_PATH"], + ) + self.assertIn( + 'cat "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}" > "${BUNDLE_PATH}"', + bundle["run"], + ) + + # Every variable the suite reads is set on the coverage run; each URL + # verifies the server certificate and its host name. + env = steps[coverage]["env"] + self.assertEqual(bundle["env"]["BUNDLE_PATH"], env["PROVISION_TEST_DATABASE_CA"]) + self.assertEqual( + "postgresql://provision:provision_test@localhost:" + "${{ job.services.postgis.ports['5432'] }}/postgres?sslmode=verify-full", + env["PROVISION_TEST_DATABASE_URL"], + ) + self.assertEqual( + "postgresql://provision:provision_test@localhost:" + "${{ steps.provision-postgres-16.outputs.port }}/postgres?sslmode=verify-full", + env["PROVISION_TEST_OLD_DATABASE_URL"], + ) + self.assertLessEqual(provision_test_variables(), set(env)) def test_source_client_tutorial_includes_messaging_before_release_admission(self) -> None: script = next( @@ -3857,6 +4039,339 @@ def test_non_workflow_file_under_workflow_directory_stays_unselected( ) self.assertFalse(outputs["release_tool"]) + def test_journey_packages_are_the_journey_product_column(self) -> None: + column = journey_products()["products"] + products = { + package + for product in column + for package in (product["crate"], product["ctl"], *product["cargoPackages"]) + if package is not None + } + self.assertEqual( + products + | {"registry-rstack", "registry-rstack-dev", "registry-thunderid-tooling"}, + JOURNEY_PACKAGES, + ) + self.assertLessEqual(JOURNEY_PACKAGES, self.workspace.package_names) + + def test_acceptance_journeys_routing(self) -> None: + # Every package in the product column, and the rstack and ThunderID + # harness packages, selects the journeys in the merge queue. + for package in sorted(JOURNEY_PACKAGES): + path = f"{self.workspace.roots[package]}/Cargo.toml" + with self.subTest(path=path): + self.assertTrue(classify(self.workspace, (path,))["acceptance_journeys"]) + + # Without dependency edges a path reaches only what it seeds, so these + # select the journeys through their own mapping: the harness and its + # tables by path, each starter the journeys copy through the product + # directory or product crate that holds it. + edgeless = Workspace(without_dependency_edges(self.metadata)) + for path in ( + *sorted(path.as_posix() for path in JOURNEYS.iterdir() if path.is_file()), + "products/platform/journeys/own-provider.sh", + "products/platform/journeys/keycloak/realm.json", + "products/platform/journeys/projects/scheduling/runtime.yaml", + "crates/registry-bregctl/src/starters.rs", + "crates/registry-documentsctl/src/starter.rs", + "crates/registry-messagingctl/src/starter.rs", + "crates/registry-evidencectl/templates/starter/README.md", + "products/breg/evidence/starter/README.md", + "products/documents/examples/starter/documents.yaml", + "products/messaging/examples/starter/dev.yaml", + ): + with self.subTest(path=path): + self.assertTrue(classify(edgeless, (path,))["acceptance_journeys"]) + + # A platform path outside the journeys seeds only the platform crates, + # none of which the journeys start. + self.assertFalse( + classify(edgeless, ("products/platform/scripts/run-fuzz-smoke.sh",))[ + "acceptance_journeys" + ] + ) + # Review defers the journeys even for their own inputs. + self.assertFalse( + classify( + self.workspace, + ("products/platform/journeys/products.yaml",), + pull_request=True, + )["acceptance_journeys"] + ) + + def test_acceptance_journeys_job_runs_each_leg_in_ratchet_mode(self) -> None: + job = self.workflow_jobs["acceptance-journeys"] + self.assertEqual("Acceptance journeys (${{ matrix.title }})", job["name"]) + self.assertEqual("ubuntu-24.04", job["runs-on"]) + self.assertFalse(job["strategy"]["fail-fast"]) + self.assertEqual( + [ + {"leg": "own-provider", "title": "own-provider and promote"}, + {"leg": "rstack-dev", "title": "rstack dev"}, + ], + job["strategy"]["matrix"]["include"], + ) + # A leg that passes 40 minutes moves to the nightly sweep and ci:full, + # so the limit is that condition, and nothing retries. + self.assertEqual(40, job["timeout-minutes"]) + self.assertNotIn("continue-on-error", job) + steps = job["steps"] + for step in steps: + with self.subTest(step=step.get("name")): + self.assertNotIn("continue-on-error", step) + self.assertNotIn("retry", step.get("uses", "") + step.get("run", "")) + + def index_of(predicate: Any) -> int: + found = [index for index, step in enumerate(steps) if predicate(step)] + self.assertEqual(1, len(found)) + return found[0] + + # The build covers the product column's packages and features and + # rstack, so every binary the journeys start comes from this commit. + products = journey_products() + build = index_of(lambda step: folded_command(step).startswith("cargo build ")) + words = shlex.split(folded_command(steps[build])) + self.assertEqual(["cargo", "build", "--locked"], words[:3]) + self.assertEqual("--bins", words[-1]) + packages = {words[index + 1] for index, word in enumerate(words) if word == "-p"} + self.assertEqual( + { + package + for product in products["products"] + for package in product["cargoPackages"] + } + | {"registry-rstack"}, + packages, + ) + features = { + feature + for index, word in enumerate(words) + if word == "--features" + for feature in words[index + 1].split(",") + } + self.assertEqual( + { + feature + for product in products["products"] + for feature in product.get("cargoFeatures") or () + }, + features, + ) + for feature in sorted(features): + package, name = feature.split("/") + with self.subTest(feature=feature): + self.assertIn(name, self.workspace.packages[package]["features"]) + + # Keycloak comes from quay.io by the digest the product column pins. + image = products["ownProviderIssuer"]["image"] + self.assertRegex(image, r"^quay\.io/keycloak/keycloak:[0-9.]+@sha256:[0-9a-f]{64}$") + pull = index_of(lambda step: folded_command(step).startswith("docker pull ")) + self.assertEqual(f"docker pull {image}", folded_command(steps[pull])) + self.assertEqual("matrix.leg == 'own-provider'", steps[pull]["if"]) + + calls = { + script: index_of( + lambda step, script=script: f"products/platform/journeys/{script} " + in folded_command(step) + ) + for script in JOURNEY_SCRIPTS + } + for script, leg in JOURNEY_SCRIPTS.items(): + command = folded_command(steps[calls[script]]) + with self.subTest(script=script): + self.assertEqual(f"matrix.leg == '{leg}'", steps[calls[script]]["if"]) + self.assertTrue( + command.startswith(f"products/platform/journeys/{script} --all ") + ) + self.assertIn('--bin-dir "${GITHUB_WORKSPACE}/target/debug"', command) + self.assertIn(JOURNEY_RATCHET, command) + self.assertIn(f'--out "${{RUNNER_TEMP}}/journeys/{script[:-3]}"', command) + self.assertLess(build, calls[script]) + # Promote takes over the own-provider run that ended with --keep. + self.assertIn("--keep", folded_command(steps[calls["own-provider.sh"]])) + self.assertIn( + '--from "${RUNNER_TEMP}/journeys/own-provider"', + folded_command(steps[calls["promote.sh"]]), + ) + self.assertLess(pull, calls["own-provider.sh"]) + self.assertLess(calls["own-provider.sh"], calls["promote.sh"]) + + def test_changes_job_checks_the_journey_tables_on_every_pull_request(self) -> None: + steps = self.workflow_jobs["changes"]["steps"] + names = [step.get("name") for step in steps] + tables = steps[names.index("Test the acceptance journey tables")] + self.assertEqual( + "uv run --no-project --with PyYAML==6.0.2 python -m unittest " + "products/platform/journeys/test_journey_tables.py", + tables["run"], + ) + self.assertNotIn("if", tables) + self.assertNotIn("if", self.workflow_jobs["changes"]) + self.assertLess(names.index("Install uv"), names.index("Test the acceptance journey tables")) + + def test_token_fixture_packages_are_every_crate_that_characterises_tokens( + self, + ) -> None: + characterising = { + self.workspace.package_for_path(path.as_posix()) + for path in Path("crates").glob("*/**/token_characterisation.rs") + } + self.assertNotIn(None, characterising) + self.assertEqual( + characterising | {"registry-platform-testing"}, TOKEN_FIXTURE_PACKAGES + ) + self.assertTrue(Path(TOKEN_FIXTURE_CORPUS).is_dir()) + + def test_a_token_corpus_change_selects_every_crate_that_reads_it(self) -> None: + corpus = f"{TOKEN_FIXTURE_CORPUS}fixtures/entra-id-token.json" + edgeless = Workspace(without_dependency_edges(self.metadata)) + outputs = classify(edgeless, (corpus,)) + sharded = { + package + for entry in outputs["rust_matrix"]["include"] + for package in entry["packages"] + } + self.assertLessEqual(TOKEN_FIXTURE_PACKAGES, sharded) + # Elsewhere under products/platform/ seeds only the platform crates. + other = classify(edgeless, ("products/platform/scripts/run-fuzz-smoke.sh",)) + self.assertFalse( + (TOKEN_FIXTURE_PACKAGES - set(SHARDS["platform"])) + & set(other["rust_packages"]) + ) + # The real graph reaches them as well. + self.assertLessEqual( + TOKEN_FIXTURE_PACKAGES, set(classify(self.workspace, (corpus,))["rust_packages"]) + ) + + def test_platform_shard_runs_the_feature_gated_token_corpus_test(self) -> None: + # No platform crate enables token-fixtures, so the shard's own run + # skips the corpus test; this step runs it. + self.assertIn("registry-platform-testing", SHARDS["platform"]) + manifest = Path("crates/registry-platform-testing/Cargo.toml").read_text( + encoding="utf-8" + ) + self.assertIn( + '[[test]]\nname = "token_fixtures"\nrequired-features = ["token-fixtures"]', + manifest, + ) + steps = [ + step + for step in self.workflow_jobs["rust-tests"]["steps"] + if step.get("name") == "Test the token fixture corpus" + ] + self.assertEqual(1, len(steps)) + self.assertEqual( + "matrix.name == 'platform' && " + "contains(matrix.packages, 'registry-platform-testing')", + steps[0]["if"], + ) + self.assertEqual( + "cargo test --locked -p registry-platform-testing " + "--features token-fixtures --test token_fixtures", + steps[0]["run"], + ) + + def test_provisioning_changes_select_the_tls_postgres_lane(self) -> None: + # The suite runs in the contracts-journeys lane, which review keeps. + self.assertIn(PROVISION_POSTGRES_LANE, BREG_CONTRACTS_LANES[:2]) + # Without dependency edges the provisioning crate reaches nothing + # else, so its own mapping has to select the lane, not a dependent + # that happens to link it. + edgeless = Workspace(without_dependency_edges(self.metadata)) + for graph, workspace in (("real", self.workspace), ("edgeless", edgeless)): + for path in ( + "crates/registry-platform-provision/src/lib.rs", + "crates/registry-platform-provision/tests/postgres.rs", + ): + for event, outputs in ( + ("pull_request", classify(workspace, (path,), pull_request=True)), + ("merge_group", classify(workspace, (path,))), + ): + with self.subTest(graph=graph, path=path, event=event): + self.assertTrue(outputs["breg_contracts"]) + self.assertIn( + PROVISION_POSTGRES_LANE, outputs["breg_contracts_lanes"] + ) + # The suite needs no other PostgreSQL job, so the provisioning crate on + # its own selects none. + alone = classify(edgeless, ("crates/registry-platform-provision/src/lib.rs",)) + self.assertFalse(alone["breg_integration"]) + self.assertFalse(alone["casework_postgres"]) + + def test_contracts_journeys_lane_runs_the_provisioning_postgres_suite( + self, + ) -> None: + steps = self.workflow_jobs["breg-contracts"]["steps"] + names = [step.get("name") for step in steps] + tls = names.index("Base Registry Engine PostgreSQL TLS proof") + start = names.index("Start PostgreSQL 16 for the provisioning floor test") + secure = names.index("Serve PostgreSQL 16 over TLS for the provisioning floor test") + suite = names.index("Provisioning PostgreSQL suite") + stop = names.index("Stop PostgreSQL 16 for the provisioning floor test") + self.assertLess(tls, start) + self.assertLess(start, secure) + self.assertLess(secure, suite) + self.assertLess(suite, stop) + lane = f"matrix.lane == '{PROVISION_POSTGRES_LANE}'" + for index in (start, secure, suite): + with self.subTest(step=names[index]): + self.assertEqual(lane, steps[index]["if"]) + self.assertEqual("provision-postgres-16", steps[start]["id"]) + self.assertEqual( + f"always() && {lane} && " + "steps.provision-postgres-16.outputs.container_id != ''", + steps[stop]["if"], + ) + + self.assertRegex( + steps[start]["run"], + r"image='docker\.io/library/postgres:16\.[0-9]+@sha256:[0-9a-f]{64}'", + ) + self.assertIn("--label org.registrystack.ci.postgres-service=true", folded_command(steps[start])) + self.assertIn("--publish 127.0.0.1::5432", folded_command(steps[start])) + + # The lane's own TLS script gives the old server a throwaway CA. + secure_command = folded_command(steps[secure]) + self.assertIn("BREG_TEST_TLS_SETUP_ONLY=1", secure_command) + self.assertIn("products/breg/scripts/test-postgres-tls.sh", secure_command) + + # Every variable the suite reads is set, each URL verifies the + # certificate and its host name, and a run that passes no test fails. + suite_run = steps[suite]["run"] + variables = provision_test_variables() + self.assertEqual( + { + "PROVISION_TEST_DATABASE_URL", + "PROVISION_TEST_DATABASE_CA", + "PROVISION_TEST_OLD_DATABASE_URL", + }, + variables, + ) + for variable in sorted(variables): + with self.subTest(variable=variable): + self.assertRegex(suite_run, rf"(?m)^export {variable}=\S") + self.assertEqual(2, suite_run.count("/postgres?sslmode=verify-full\"")) + # The suite target and the library's command tests, which need cli. + for target, log in (("--lib", "lib"), ("--test postgres", "suite")): + with self.subTest(target=target): + self.assertIn( + "cargo test --locked -p registry-platform-provision " + f"--features postgres-test,cli {target} " + f'| tee "${{RUNNER_TEMP}}/provision-postgres-{log}.log"', + folded_command(steps[suite]), + ) + self.assertIn( + "for target in lib suite; do grep -Eq " + "'^test result: ok\\. [1-9][0-9]* passed; 0 failed; 0 ignored' " + '"${RUNNER_TEMP}/provision-postgres-${target}.log"', + folded_command(steps[suite]), + ) + + stop_run = steps[stop]["run"] + self.assertIn("org.registrystack.ci.postgres-service", stop_run) + self.assertIn('docker rm --force "${CONTAINER_ID}"', stop_run) + + def edit_lock_package(text: str, name: str, **fields: str) -> str: """Return the lockfile with one uniquely named package's fields replaced.""" @@ -4114,6 +4629,7 @@ def test_heavy_integration_waits_for_the_merge_queue_or_ci_full(self) -> None: "breg_tutorial", "casework_tutorial", "breg_evidence_composition", + "acceptance_journeys", ) # Each heavy selector keeps its own path gate; this change reaches all. paths = ( diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dda895aa05..ce555a0533 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,6 +95,7 @@ jobs: render_tutorial: ${{ steps.filter.outputs.render_tutorial }} scheduling_tutorial: ${{ steps.filter.outputs.scheduling_tutorial }} breg_evidence_composition: ${{ steps.filter.outputs.breg_evidence_composition }} + acceptance_journeys: ${{ steps.filter.outputs.acceptance_journeys }} identifiers: ${{ steps.filter.outputs.identifiers }} steps: - name: Checkout @@ -161,6 +162,11 @@ jobs: - name: Test evidence fuzz runner run: uv run --no-project --with PyYAML==6.0.2 python -m unittest products/evidence/scripts/test_run_fuzz_smoke.py + # The acceptance journeys run in the heavy tier; their tables are + # checked on every pull request. + - name: Test the acceptance journey tables + run: uv run --no-project --with PyYAML==6.0.2 python -m unittest products/platform/journeys/test_journey_tables.py + - name: Install pinned actionlint shell: bash run: | @@ -300,7 +306,10 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 15 # --all-features enables the dispatch and activation PostgreSQL tests, - # which fail rather than skip without their disposable database. + # which fail rather than skip without their disposable database. It also + # enables the provisioning suite, which fails rather than skips without a + # PostgreSQL 17 superuser with PostGIS over TLS and a server below the + # floor signed by a CA it trusts. services: postgres: image: docker.io/library/postgres:17.11@sha256:67f41722b7a8cbdb868a44a4995c846eddfdc2973bccb291ce937dce88ad5675 @@ -315,6 +324,20 @@ jobs: --health-retries 5 ports: - 5432/tcp + postgis: + # The PostgreSQL 17 / PostGIS 3.5.2 image breg-contracts pins. + image: postgis/postgis@sha256:01a6a70e41e6c4467c8f55f6063555ed72db2d6662cd0d571040d42eadaeb6f6 + env: + POSTGRES_DB: provision + POSTGRES_USER: provision + POSTGRES_PASSWORD: provision_test + options: >- + --health-cmd "pg_isready -U provision -d provision" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432/tcp steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -323,6 +346,105 @@ jobs: persist-credentials: false submodules: false + # The contracts-journeys lane's TLS script, in setup-only mode, gives + # the service a throwaway CA and makes it TLS-only. + - name: Serve the provisioning PostGIS service over TLS + shell: bash + env: + SERVICE_CONTAINER_ID: ${{ job.services.postgis.id }} + SERVICE_PORT: ${{ job.services.postgis.ports['5432'] }} + SERVICE_CA_PEM_PATH: ${{ runner.temp }}/provision-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${SERVICE_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${SERVICE_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${SERVICE_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${SERVICE_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + # The same PostgreSQL 16 steps as the contracts-journeys lane, which + # test_ci_changes.py holds equal. + - name: Start PostgreSQL 16 for the provisioning floor test + id: provision-postgres-16 + shell: bash + run: | + set -euo pipefail + # PostgreSQL 16.15, verified 2026-11-27. + image='docker.io/library/postgres:16.15@sha256:f9a7b9ebf6f56201f949db745e47bc423c0f0f8294bafe991cc10bf74b029657' + container_name="provision-postgres-16-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + container_id="$( + docker run --detach \ + --name "${container_name}" \ + --label org.registrystack.ci.postgres-service=true \ + --env POSTGRES_USER=provision \ + --env POSTGRES_PASSWORD=provision_test \ + --health-cmd 'pg_isready -U provision -d provision' \ + --health-interval 10s \ + --health-timeout 5s \ + --health-retries 5 \ + --publish 127.0.0.1::5432 \ + "${image}" + )" + printf 'container_id=%s\n' "${container_id}" >> "${GITHUB_OUTPUT}" + + for _ in $(seq 1 30); do + health="$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" + if [[ "${health}" == healthy ]]; then + break + fi + if [[ "${health}" == unhealthy ]]; then + docker logs "${container_id}" + exit 1 + fi + sleep 2 + done + if [[ "$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" != healthy ]]; then + docker logs "${container_id}" + exit 1 + fi + + endpoint="$(docker port "${container_id}" 5432/tcp)" + port="${endpoint##*:}" + [[ "${port}" =~ ^[0-9]+$ ]] + printf 'port=%s\n' "${port}" >> "${GITHUB_OUTPUT}" + + - name: Serve PostgreSQL 16 over TLS for the provisioning floor test + shell: bash + env: + OLD_CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + OLD_PORT: ${{ steps.provision-postgres-16.outputs.port }} + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${OLD_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${OLD_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + # One bundle trusts both servers' throwaway CAs. + - name: Bundle the provisioning servers' CAs + shell: bash + env: + SERVICE_CA_PEM_PATH: ${{ runner.temp }}/provision-postgres-ca.pem + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + BUNDLE_PATH: ${{ runner.temp }}/provision-postgres-ca-bundle.pem + run: | + set -euo pipefail + for ca in "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}"; do + if [[ ! -s "${ca}" ]]; then + echo "::error::the provisioning suite needs the CA file ${ca}" + exit 1 + fi + done + cat "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}" > "${BUNDLE_PATH}" + - name: Cache Cargo registry and build artifacts uses: Swatinem/rust-cache@eedcf2fb1c22f010a0eb66b92f378c110977f266 # v2 with: @@ -338,6 +460,9 @@ jobs: env: DISPATCH_TEST_DATABASE_URL: postgresql://dispatch:dispatch_test@localhost:${{ job.services.postgres.ports['5432'] }}/dispatch ACTIVATION_TEST_DATABASE_URL: postgresql://dispatch:dispatch_test@localhost:${{ job.services.postgres.ports['5432'] }}/dispatch + PROVISION_TEST_DATABASE_URL: postgresql://provision:provision_test@localhost:${{ job.services.postgis.ports['5432'] }}/postgres?sslmode=verify-full + PROVISION_TEST_DATABASE_CA: ${{ runner.temp }}/provision-postgres-ca-bundle.pem + PROVISION_TEST_OLD_DATABASE_URL: postgresql://provision:provision_test@localhost:${{ steps.provision-postgres-16.outputs.port }}/postgres?sslmode=verify-full run: >- cargo llvm-cov --locked -p 'registry-platform-*' @@ -363,6 +488,21 @@ jobs: if-no-files-found: error retention-days: 1 + - name: Stop PostgreSQL 16 for the provisioning floor test + if: always() && steps.provision-postgres-16.outputs.container_id != '' + env: + CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + shell: bash + run: | + set -euo pipefail + label="$( + docker inspect \ + --format '{{ index .Config.Labels "org.registrystack.ci.postgres-service" }}' \ + "${CONTAINER_ID}" + )" + [[ "${label}" == true ]] + docker rm --force "${CONTAINER_ID}" + platform-coverage-upload: name: Upload platform coverage needs: @@ -716,6 +856,12 @@ jobs: if: matrix.name == 'platform' && contains(matrix.packages, 'registry-platform-testing') run: cargo test --locked -p registry-platform-testing --features test-authorization-server --test test_authorization_server + # The corpus test needs token-fixtures, which no platform crate enables, + # so the shard's own run skips it. + - name: Test the token fixture corpus + if: matrix.name == 'platform' && contains(matrix.packages, 'registry-platform-testing') + run: cargo test --locked -p registry-platform-testing --features token-fixtures --test token_fixtures + - name: Check Casework schemas against their generators if: matrix.name == 'casework' run: products/casework/scripts/check-schemas.sh @@ -1737,6 +1883,127 @@ jobs: if: matrix.lane == 'contracts-journeys' run: products/breg/quickstart/run.sh --spatial --smoke + # The provisioning suite needs a PostgreSQL 17 superuser with PostGIS + # over TLS, which this lane's service is once the TLS proof has run, and + # a server below the floor signed by a CA the suite also trusts. It + # fails, never skips, when one of its variables is missing. + - name: Start PostgreSQL 16 for the provisioning floor test + id: provision-postgres-16 + if: matrix.lane == 'contracts-journeys' + shell: bash + run: | + set -euo pipefail + # PostgreSQL 16.15, verified 2026-11-27. + image='docker.io/library/postgres:16.15@sha256:f9a7b9ebf6f56201f949db745e47bc423c0f0f8294bafe991cc10bf74b029657' + container_name="provision-postgres-16-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + container_id="$( + docker run --detach \ + --name "${container_name}" \ + --label org.registrystack.ci.postgres-service=true \ + --env POSTGRES_USER=provision \ + --env POSTGRES_PASSWORD=provision_test \ + --health-cmd 'pg_isready -U provision -d provision' \ + --health-interval 10s \ + --health-timeout 5s \ + --health-retries 5 \ + --publish 127.0.0.1::5432 \ + "${image}" + )" + printf 'container_id=%s\n' "${container_id}" >> "${GITHUB_OUTPUT}" + + for _ in $(seq 1 30); do + health="$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" + if [[ "${health}" == healthy ]]; then + break + fi + if [[ "${health}" == unhealthy ]]; then + docker logs "${container_id}" + exit 1 + fi + sleep 2 + done + if [[ "$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" != healthy ]]; then + docker logs "${container_id}" + exit 1 + fi + + endpoint="$(docker port "${container_id}" 5432/tcp)" + port="${endpoint##*:}" + [[ "${port}" =~ ^[0-9]+$ ]] + printf 'port=%s\n' "${port}" >> "${GITHUB_OUTPUT}" + + # Setup-only mode gives this server its own throwaway CA and makes it + # TLS-only, the way the proof above does for the lane's service. + - name: Serve PostgreSQL 16 over TLS for the provisioning floor test + if: matrix.lane == 'contracts-journeys' + shell: bash + env: + OLD_CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + OLD_PORT: ${{ steps.provision-postgres-16.outputs.port }} + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${OLD_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${OLD_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + - name: Provisioning PostgreSQL suite + if: matrix.lane == 'contracts-journeys' + shell: bash + env: + DATABASE_PORT: ${{ job.services.postgres.ports['5432'] }} + OLD_PORT: ${{ steps.provision-postgres-16.outputs.port }} + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + run: | + set -euo pipefail + if [[ ! "${DATABASE_PORT}" =~ ^[0-9]+$ || ! "${OLD_PORT}" =~ ^[0-9]+$ ]]; then + echo "::error::the provisioning suite needs the port of both PostgreSQL servers" + exit 1 + fi + for ca in "${BREG_TEST_TLS_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}"; do + if [[ ! -s "${ca}" ]]; then + echo "::error::the provisioning suite needs the CA file ${ca}" + exit 1 + fi + done + # One bundle trusts both servers' throwaway CAs. + bundle="${RUNNER_TEMP}/provision-postgres-ca-bundle.pem" + cat "${BREG_TEST_TLS_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}" > "${bundle}" + export PROVISION_TEST_DATABASE_URL="postgresql://breg:breg_test@localhost:${DATABASE_PORT}/postgres?sslmode=verify-full" + export PROVISION_TEST_DATABASE_CA="${bundle}" + export PROVISION_TEST_OLD_DATABASE_URL="postgresql://provision:provision_test@localhost:${OLD_PORT}/postgres?sslmode=verify-full" + # With cli on, the library's command tests also run against the + # first server. No rust-tests shard enables cli. + cargo test --locked -p registry-platform-provision --features postgres-test,cli --lib \ + | tee "${RUNNER_TEMP}/provision-postgres-lib.log" + cargo test --locked -p registry-platform-provision --features postgres-test,cli --test postgres \ + | tee "${RUNNER_TEMP}/provision-postgres-suite.log" + # A run that selected no test still exits 0, so each target needs a + # pass count and no ignored test. + for target in lib suite; do + grep -Eq '^test result: ok\. [1-9][0-9]* passed; 0 failed; 0 ignored' "${RUNNER_TEMP}/provision-postgres-${target}.log" || { echo "::error::expected the provisioning PostgreSQL ${target} tests to pass with no test ignored"; exit 1; } + done + + - name: Stop PostgreSQL 16 for the provisioning floor test + if: always() && matrix.lane == 'contracts-journeys' && steps.provision-postgres-16.outputs.container_id != '' + env: + CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + shell: bash + run: | + set -euo pipefail + label="$( + docker inspect \ + --format '{{ index .Config.Labels "org.registrystack.ci.postgres-service" }}' \ + "${CONTAINER_ID}" + )" + [[ "${label}" == true ]] + docker rm --force "${CONTAINER_ID}" + breg-postgres-18: name: Base Registry Engine PostgreSQL 18 portability needs: changes @@ -3083,6 +3350,103 @@ jobs: --evidencectl "$GITHUB_WORKSPACE/target/debug/evidencectl" \ --evidence "$GITHUB_WORKSPACE/target/debug/evidence" + acceptance-journeys: + # The first-hour journeys of products/platform/journeys/ in ratchet mode: + # a leg passes when every product's outcome equals expected-failures.yaml, + # and --strict fails it when a listed failure no longer fails, so the + # change that fixes a cell deletes its row. Owner: platform. A leg that + # passes this 40 minute limit, or fails for harness reasons more than + # twice in a week, moves to the nightly sweep and ci:full only. No step + # retries. + name: Acceptance journeys (${{ matrix.title }}) + needs: + - changes + - rust-policy + if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.acceptance_journeys == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 40 + strategy: + fail-fast: false + matrix: + include: + - leg: own-provider + title: own-provider and promote + - leg: rstack-dev + title: rstack dev + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + submodules: false + + - name: Cache Cargo registry + uses: Swatinem/rust-cache@eedcf2fb1c22f010a0eb66b92f378c110977f266 # v2 + with: + shared-key: workspace-registry + cache-targets: false + save-if: ${{ github.ref == 'refs/heads/main' }} + + # The digest products/platform/journeys/products.yaml pins. No other + # job pulls from quay.io, so a registry outage fails here, before any + # product step runs. + - name: Pull the Keycloak issuer image + if: matrix.leg == 'own-provider' + run: docker pull quay.io/keycloak/keycloak:26.7.3@sha256:ff4257d0d64efbe99ed1ddfaf07765cc3c36dc7518bf8324d41961327f441c54 + + # Every package and feature in the journeys' product column, and rstack. + - name: Build the journey binaries + run: >- + cargo build --locked + -p registry-adapter -p registry-adapter-job -p registry-adapterctl + -p registry-breg -p registry-breg-mcp -p registry-breg-review -p registry-bregctl + -p registry-casework -p registry-caseworkctl + -p registry-coordinator + -p registry-discovery -p registry-discoveryctl + -p registry-documents -p registry-documentsctl + -p registry-evidence -p registry-evidence-oid4vci -p registry-evidence-oid4vp -p registry-evidencectl + -p registry-mcp + -p registry-messaging -p registry-messagingctl + -p registry-render + -p registry-rstack + -p registry-scheduling -p registry-schedulingctl + --features registry-breg/runtime,registry-discovery/server + --bins + + - name: Run the own-provider journey + if: matrix.leg == 'own-provider' + run: >- + products/platform/journeys/own-provider.sh --all + --bin-dir "${GITHUB_WORKSPACE}/target/debug" + --expected products/platform/journeys/expected-failures.yaml --strict + --keep + --out "${RUNNER_TEMP}/journeys/own-provider" + + # Promote takes over the containers and run directory the own-provider + # journey kept, and its cleanup removes them. + - name: Run the promote journey + if: matrix.leg == 'own-provider' + run: >- + products/platform/journeys/promote.sh --all + --from "${RUNNER_TEMP}/journeys/own-provider" + --bin-dir "${GITHUB_WORKSPACE}/target/debug" + --expected products/platform/journeys/expected-failures.yaml --strict + --out "${RUNNER_TEMP}/journeys/promote" + + - name: Run the rstack dev journey + if: matrix.leg == 'rstack-dev' + run: >- + products/platform/journeys/rstack-dev.sh --all + --bin-dir "${GITHUB_WORKSPACE}/target/debug" + --expected products/platform/journeys/expected-failures.yaml --strict + --out "${RUNNER_TEMP}/journeys/rstack-dev" + + - name: Report disk usage + if: always() + run: | + df -h / + du -sh target 2>/dev/null || true + evidence-anchors: # The documentation anchors cite source across the whole workspace, so this check # runs on every pull request rather than behind the changed-path classifier: a @@ -3574,6 +3938,7 @@ jobs: - render-tutorial - scheduling-tutorial - breg-evidence-composition + - acceptance-journeys - evidence-anchors - docs - client-bindings @@ -3609,6 +3974,7 @@ jobs: "breg-tutorial": "breg_tutorial", "casework-tutorial": "casework_tutorial", "breg-evidence-composition": "breg_evidence_composition", + "acceptance-journeys": "acceptance_journeys", "deployment": "deployment", } selection = jobs["changes"].get("outputs", {}) diff --git a/.github/workflows/nightly-rust-coverage.yml b/.github/workflows/nightly-rust-coverage.yml index 4c336fa155..813e3d5654 100644 --- a/.github/workflows/nightly-rust-coverage.yml +++ b/.github/workflows/nightly-rust-coverage.yml @@ -55,9 +55,11 @@ jobs: COVERAGE_PACKAGES: ${{ matrix.packages }} # The platform shard's --all-features build enables the dispatch and # activation PostgreSQL tests, which fail rather than skip without their - # disposable database. The other shards start the service and leave it - # unused, so this definition stays identical to platform-coverage in - # ci.yml, which .github/scripts/test_ci_changes.py holds. + # disposable database, and the provisioning suite, which fails rather + # than skips without its two TLS servers. The other shards start the + # services and leave them unused, so this definition stays identical to + # platform-coverage in ci.yml, which .github/scripts/test_ci_changes.py + # holds. The provisioning server steps run in the platform shard only. services: postgres: image: docker.io/library/postgres:17.11@sha256:67f41722b7a8cbdb868a44a4995c846eddfdc2973bccb291ce937dce88ad5675 @@ -72,6 +74,20 @@ jobs: --health-retries 5 ports: - 5432/tcp + postgis: + # The PostgreSQL 17 / PostGIS 3.5.2 image breg-contracts pins. + image: postgis/postgis@sha256:01a6a70e41e6c4467c8f55f6063555ed72db2d6662cd0d571040d42eadaeb6f6 + env: + POSTGRES_DB: provision + POSTGRES_USER: provision + POSTGRES_PASSWORD: provision_test + options: >- + --health-cmd "pg_isready -U provision -d provision" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432/tcp steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -80,6 +96,105 @@ jobs: persist-credentials: false submodules: false + # The same provisioning server steps as platform-coverage in ci.yml. + - name: Serve the provisioning PostGIS service over TLS + if: matrix.name == 'platform' + shell: bash + env: + SERVICE_CONTAINER_ID: ${{ job.services.postgis.id }} + SERVICE_PORT: ${{ job.services.postgis.ports['5432'] }} + SERVICE_CA_PEM_PATH: ${{ runner.temp }}/provision-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${SERVICE_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${SERVICE_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${SERVICE_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${SERVICE_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + - name: Start PostgreSQL 16 for the provisioning floor test + id: provision-postgres-16 + if: matrix.name == 'platform' + shell: bash + run: | + set -euo pipefail + # PostgreSQL 16.15, verified 2026-11-27. + image='docker.io/library/postgres:16.15@sha256:f9a7b9ebf6f56201f949db745e47bc423c0f0f8294bafe991cc10bf74b029657' + container_name="provision-postgres-16-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + container_id="$( + docker run --detach \ + --name "${container_name}" \ + --label org.registrystack.ci.postgres-service=true \ + --env POSTGRES_USER=provision \ + --env POSTGRES_PASSWORD=provision_test \ + --health-cmd 'pg_isready -U provision -d provision' \ + --health-interval 10s \ + --health-timeout 5s \ + --health-retries 5 \ + --publish 127.0.0.1::5432 \ + "${image}" + )" + printf 'container_id=%s\n' "${container_id}" >> "${GITHUB_OUTPUT}" + + for _ in $(seq 1 30); do + health="$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" + if [[ "${health}" == healthy ]]; then + break + fi + if [[ "${health}" == unhealthy ]]; then + docker logs "${container_id}" + exit 1 + fi + sleep 2 + done + if [[ "$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" != healthy ]]; then + docker logs "${container_id}" + exit 1 + fi + + endpoint="$(docker port "${container_id}" 5432/tcp)" + port="${endpoint##*:}" + [[ "${port}" =~ ^[0-9]+$ ]] + printf 'port=%s\n' "${port}" >> "${GITHUB_OUTPUT}" + + - name: Serve PostgreSQL 16 over TLS for the provisioning floor test + if: matrix.name == 'platform' + shell: bash + env: + OLD_CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + OLD_PORT: ${{ steps.provision-postgres-16.outputs.port }} + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${OLD_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${OLD_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + - name: Bundle the provisioning servers' CAs + if: matrix.name == 'platform' + shell: bash + env: + SERVICE_CA_PEM_PATH: ${{ runner.temp }}/provision-postgres-ca.pem + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + BUNDLE_PATH: ${{ runner.temp }}/provision-postgres-ca-bundle.pem + run: | + set -euo pipefail + for ca in "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}"; do + if [[ ! -s "${ca}" ]]; then + echo "::error::the provisioning suite needs the CA file ${ca}" + exit 1 + fi + done + cat "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}" > "${BUNDLE_PATH}" + - name: Cache Cargo registry uses: Swatinem/rust-cache@eedcf2fb1c22f010a0eb66b92f378c110977f266 # v2 with: @@ -97,6 +212,9 @@ jobs: env: DISPATCH_TEST_DATABASE_URL: postgresql://dispatch:dispatch_test@localhost:${{ job.services.postgres.ports['5432'] }}/dispatch ACTIVATION_TEST_DATABASE_URL: postgresql://dispatch:dispatch_test@localhost:${{ job.services.postgres.ports['5432'] }}/dispatch + PROVISION_TEST_DATABASE_URL: postgresql://provision:provision_test@localhost:${{ job.services.postgis.ports['5432'] }}/postgres?sslmode=verify-full + PROVISION_TEST_DATABASE_CA: ${{ runner.temp }}/provision-postgres-ca-bundle.pem + PROVISION_TEST_OLD_DATABASE_URL: postgresql://provision:provision_test@localhost:${{ steps.provision-postgres-16.outputs.port }}/postgres?sslmode=verify-full run: | set -euo pipefail @@ -158,6 +276,21 @@ jobs: use_oidc: true version: v11.3.1 + - name: Stop PostgreSQL 16 for the provisioning floor test + if: always() && matrix.name == 'platform' && steps.provision-postgres-16.outputs.container_id != '' + env: + CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + shell: bash + run: | + set -euo pipefail + label="$( + docker inspect \ + --format '{{ index .Config.Labels "org.registrystack.ci.postgres-service" }}' \ + "${CONTAINER_ID}" + )" + [[ "${label}" == true ]] + docker rm --force "${CONTAINER_ID}" + - name: Report disk usage if: always() run: | diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index 61e060e407..074577dcf9 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -32,6 +32,8 @@ issuer the run starts and does not start an identity provider. | `test_lib.sh` | The library's self-test. It runs against fake `docker`, `curl` and `cargo` commands, so it starts no container and builds nothing: `bash products/platform/journeys/test_lib.sh`. | | `rstack-dev.sh` | The `rstack dev` journey, with a recipe per product for the steps from `start` on. | | `own-provider.sh` | The own-provider journey: a stock Keycloak and a stock PostgreSQL started on loopback, then each product from its starter to a first authenticated call. | +| `lib-assists.sh` | The assists, sourced only when `--assist` names one: `sql` (provisioning statements through psql), `certificate` (a private CA and a TLS server certificate for the pg container), `token-type` (Keycloak's at+jwt header setting) and `mapper` (a hardcoded actor-kind claim mapper). The only journey file allowed to call psql, openssl or docker exec. Each use counts as a pass-rule violation. | +| `promote.sh` | The promote journey: `promote.sh --from RUN_DIR --bin-dir DIR`, where RUN_DIR is a run directory of a development journey (an `own-provider.sh` run ended with `--keep` when any cell finished). It starts the files in place with no development declaration, lists the refusals and applies each fix. A product whose development cell did not finish stops at `input`. | | `keycloak/realm.json` | The realm the own-provider journey imports: per product, one caller client with a service account and one API client for the product's audience. It holds no protocol mappers. | | `projects/` | The runtime files the own-provider journey gives the products whose starter has none (Render, Coordinator). | diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index c0ecb52be6..a09611761f 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -221,71 +221,81 @@ expectedFailures: step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: casework step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: messaging step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: evidence step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: scheduling step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: documents step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: coordinator step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: adapter step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: render step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The development journey did not finish for this product, so there are no files to promote." - journey: promote product: discovery step: input code: journey.promote.no-input removedBy: M4 - basis: predicted - reason: The development journey does not finish for this product, so there are no files to promote. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "The own-provider cell of discovery is unreached (it verifies no token and keeps no database), so there are no files to promote." unreached: - journey: own-provider @@ -369,32 +379,51 @@ unreached: - journey: promote product: breg-mcp step: input - basis: predicted - reason: Supporting runtime. It is promoted with its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "Supporting runtime. It is promoted with its parent." - journey: promote product: breg-review step: input - basis: predicted - reason: Supporting runtime. It is promoted with its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "Supporting runtime. It is promoted with its parent." - journey: promote product: registry-mcp step: input - basis: predicted - reason: Supporting runtime. It is promoted with its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "Supporting runtime. It is promoted with its parent." - journey: promote product: evidence-oid4vci step: input - basis: predicted - reason: Supporting runtime. It is promoted with its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "Supporting runtime. It is promoted with its parent." - journey: promote product: evidence-oid4vp step: input - basis: predicted - reason: Supporting runtime. It is promoted with its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "Supporting runtime. It is promoted with its parent." - journey: promote product: adapter-job step: input - basis: predicted - reason: Supporting runtime. It is promoted with its parent. + basis: observed + observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" + reason: "Supporting runtime. It is promoted with its parent." +# The scheduling row above is the unassisted outcome, which the ratchet checks +# against an unassisted input. The assisted baseline input (run +# 20261127024425-265d, kept) gives this observed outcome instead, in promote +# run 20261127025000-816f (acceptance mode, exit 1): +# +# - journey: promote +# product: scheduling +# step: refusals +# code: journey.promote.nothing-refused +# removedBy: M6 +# basis: observed +# observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), promote run 20261127025000-816f on own-provider run 20261127024425-265d (assisted: sql, certificate, token-type, mapper)" +# reason: "The assisted Scheduling cell reached T1. Started with no development declaration, schedulingctl check (which has no --production flag) lists no refusal and the server starts and answers /readyz, so zero refusals are listed. No shared posture exists on main, so nothing can refuse. The count becomes meaningful at M1 with M6." passes: [] diff --git a/products/platform/journeys/lib-assists.sh b/products/platform/journeys/lib-assists.sh new file mode 100644 index 0000000000..d6c943592f --- /dev/null +++ b/products/platform/journeys/lib-assists.sh @@ -0,0 +1,234 @@ +#!/usr/bin/env bash +# Assists for the acceptance journeys: what a developer must do by hand today +# where a product offers no command. This is the one journey file allowed to +# call psql, openssl and docker exec, which the pass rule forbids the reader. +# lib.sh sources it only when --assist names an assist, and each use is counted +# there as a pass-rule violation. +# +# Written for the products the baseline run meets on main (Scheduling and the +# other PostgreSQL products that share the operate pages' provisioning SQL). +# The assists are sourced into the journey's shell: they read JOURNEY_OUT and +# JOURNEY_CONTAINER_PREFIX from lib.sh and call its secret and container +# helpers. +# +# journey_assist_sql PRODUCT ADMIN_URL_FILE MIGRATION_URL_FILE RUNTIME_URL_FILE +# The statements of the product's operate page: two login roles, the +# database, the connect grants and the schema handed to the migration +# role. Run with psql as the administrator. +# journey_assist_certificate PRODUCT RUNTIME_FILE +# A private CA and a server certificate for 127.0.0.1, installed into the +# journey's pg container, TLS switched on, and the runtime file's +# database.caBundleRef set to the CA. +# journey_assist_mapper PRODUCT CLIENT TOKEN_VARIABLE CLAIM... +# A hardcoded-claim mapper on the caller's client in Keycloak for each +# missing claim, then a fresh client-credentials token in TOKEN_VARIABLE. +# Written for registry_actor_kind, the one claim Scheduling needs. +# journey_assist_token_type PRODUCT CLIENT TOKEN_VARIABLE +# Keycloak's setting that makes the client's access tokens carry the +# at+jwt header type, then a fresh token in TOKEN_VARIABLE. The shared +# verifier refuses every other type. +# +# shellcheck disable=SC2034 # the assist variables are read by the sourcing shell +set -euo pipefail + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + printf 'lib-assists.sh is sourced by lib.sh; it does nothing on its own.\n' >&2 + exit 2 +fi + +_assist_identifier='^[a-z][a-z0-9_]*$' + +# _assist_url_part FILE PART: user, password, port or database of the +# PostgreSQL URL in FILE, on stdout. The URL is the journey's own shape, +# postgresql://USER:PASSWORD@127.0.0.1:PORT/DATABASE with a hexadecimal password. +_assist_url_part() { + perl -e ' + my ($path, $part) = @ARGV; + open my $fh, "<", $path or die "cannot read $path: $!\n"; + my $url = <$fh>; + chomp $url; + my %p; + @p{qw(user password port database)} = + $url =~ m{^postgresql://([a-z][a-z0-9_]*):([0-9a-f]+)\@127\.0\.0\.1:([0-9]+)/([a-z][a-z0-9_]*)$} + or die "$path does not hold a PostgreSQL URL of the journey shape\n"; + print $p{$part};' "$1" "$2" +} + +# _assist_psql PGPASS_FILE PORT DATABASE: psql as the administrator, the +# statements on standard input. The password reaches psql as a pgpass file. +_assist_psql() { + PGPASSFILE=$1 psql --no-psqlrc --quiet --set ON_ERROR_STOP=1 \ + --host 127.0.0.1 --port "$2" --username postgres --dbname "$3" --file - +} + +# _assist_wait_for_postgres PGPASS_FILE PORT: the container's TCP port opens +# while the image's entrypoint is still initialising, so wait until the final +# server answers a query. +_assist_wait_for_postgres() { + local attempt + for attempt in $(seq 1 60); do + if printf 'SELECT 1;\n' | _assist_psql "$1" "$2" postgres >/dev/null 2>&1; then + return 0 + fi + sleep 1 + done + printf 'assist: PostgreSQL on port %s did not answer within 60 seconds\n' "$2" >&2 + return 1 +} + +_assist_admin_pgpass() { + local admin_file=$1 port password pgpass=$JOURNEY_OUT/secrets/assist-pgpass + port=$(_assist_url_part "$admin_file" port) + password=$(_assist_url_part "$admin_file" password) + ( + umask 077 + printf '127.0.0.1:%s:*:postgres:%s\n' "$port" "$password" >"$pgpass" + ) + chmod 600 "$pgpass" + printf '%s' "$pgpass" +} + +journey_assist_sql() { + local product=$1 admin_file=$2 migration_file=$3 runtime_file=$4 + local port database migration_role runtime_role migration_password runtime_password pgpass status=0 + port=$(_assist_url_part "$admin_file" port) + database=$(_assist_url_part "$migration_file" database) + migration_role=$(_assist_url_part "$migration_file" user) + migration_password=$(_assist_url_part "$migration_file" password) + runtime_role=$(_assist_url_part "$runtime_file" user) + runtime_password=$(_assist_url_part "$runtime_file" password) + [[ "$database" =~ $_assist_identifier && "$migration_role" =~ $_assist_identifier && "$runtime_role" =~ $_assist_identifier ]] || { + printf 'assist sql: %s has a name psql would need quoted\n' "$product" >&2 + return 1 + } + pgpass=$(_assist_admin_pgpass "$admin_file") + _assist_wait_for_postgres "$pgpass" "$port" || return 1 + _assist_psql "$pgpass" "$port" postgres </dev/null + openssl req -newkey rsa:2048 -nodes -subj '/CN=127.0.0.1' \ + -keyout "$tls_dir/server.key" -out "$tls_dir/server.csr" 2>/dev/null + printf 'subjectAltName=IP:127.0.0.1,DNS:localhost\n' >"$tls_dir/san.ext" + openssl x509 -req -days 2 -in "$tls_dir/server.csr" -CA "$JOURNEY_OUT/secrets/postgres-ca.pem" \ + -CAkey "$tls_dir/ca.key" -CAcreateserial -CAserial "$tls_dir/ca.srl" -extfile "$tls_dir/san.ext" \ + -out "$tls_dir/server.crt" 2>/dev/null + ) + docker exec --user root "$container" mkdir -p /var/lib/postgresql/journey-tls >/dev/null + docker cp "$tls_dir/server.crt" "$container:/var/lib/postgresql/journey-tls/server.crt" >/dev/null + docker cp "$tls_dir/server.key" "$container:/var/lib/postgresql/journey-tls/server.key" >/dev/null + docker exec --user root "$container" sh -c \ + 'chown postgres:postgres /var/lib/postgresql/journey-tls/server.crt /var/lib/postgresql/journey-tls/server.key && chmod 600 /var/lib/postgresql/journey-tls/server.key' >/dev/null + pgpass=$(_assist_admin_pgpass "$admin_file") + _assist_wait_for_postgres "$pgpass" "$port" || return 1 + _assist_psql "$pgpass" "$port" postgres >/dev/null <<'SQL' || status=$? +ALTER SYSTEM SET ssl_cert_file = '/var/lib/postgresql/journey-tls/server.crt'; +ALTER SYSTEM SET ssl_key_file = '/var/lib/postgresql/journey-tls/server.key'; +ALTER SYSTEM SET ssl = on; +SELECT pg_reload_conf(); +SQL + command rm -f "$pgpass" "$tls_dir/ca.key" "$tls_dir/ca.srl" "$tls_dir/server.key" "$tls_dir/server.crt" \ + "$tls_dir/server.csr" "$tls_dir/san.ext" "$JOURNEY_OUT/secrets/postgres-ca.srl" + rmdir "$tls_dir" + [[ $status -eq 0 ]] || return "$status" + # The CA certificate sits in the secret folder because the runtime file + # resolves it there. own-provider.sh deletes it with its other files. + OWN_SECRET_FILES+=("$JOURNEY_OUT/secrets/postgres-ca.pem") + perl -i -pe 's{^(\s*)#\s*(caBundleRef: secret:file/)postgres-ca\.pem\s*$}{$1$2postgres-ca.pem\n}' "$runtime_file" + grep -q '^[[:space:]]*caBundleRef: secret:file/postgres-ca.pem$' "$runtime_file" || { + printf 'assist certificate: %s has no caBundleRef line to set in %s\n' "$product" "$runtime_file" >&2 + return 1 + } +} + +# _assist_claim_value CLAIM: the value a service caller's token carries. +_assist_claim_value() { + case "$1" in + registry_actor_kind) printf 'service' ;; + *) + printf 'assist mapper: no value is written for the claim %s\n' "$1" >&2 + return 1 + ;; + esac +} + +journey_assist_mapper() { + local product=$1 client=$2 token_variable=$3 claim value uuid body secret_file response token + shift 3 + # The administrator token the journey took at setup lives 60 seconds. + keycloak_admin_login + keycloak_client_uuid "$client" uuid + for claim in "$@"; do + value=$(_assist_claim_value "$claim") || return 1 + body=$(jq -cn --arg claim "$claim" --arg value "$value" \ + '{name: $claim, protocol: "openid-connect", protocolMapper: "oidc-hardcoded-claim-mapper", + config: {"claim.name": $claim, "claim.value": $value, "jsonType.label": "String", + "access.token.claim": "true", "id.token.claim": "false", "userinfo.token.claim": "false"}}') + keycloak_admin POST "/clients/$uuid/protocol-mappers/models" "$body" + [[ "$KC_STATUS" == 201 ]] || { + printf 'assist mapper: Keycloak refused the mapper for %s (HTTP %s)\n' "$claim" "$KC_STATUS" >&2 + return 1 + } + done + _assist_fresh_token "$product" "$client" "$token_variable" +} + +journey_assist_token_type() { + local product=$1 client=$2 token_variable=$3 uuid body + keycloak_admin_login + keycloak_client_uuid "$client" uuid + keycloak_admin GET "/clients/$uuid" + [[ "$KC_STATUS" == 200 ]] || { + printf 'assist token-type: Keycloak cannot read client %s (HTTP %s)\n' "$client" "$KC_STATUS" >&2 + return 1 + } + body=$(printf '%s' "$KC_BODY" | jq -c '.attributes["access.token.header.type.rfc9068"] = "true"') + keycloak_admin PUT "/clients/$uuid" "$body" + [[ "$KC_STATUS" == 204 ]] || { + printf 'assist token-type: Keycloak refused the client update for %s (HTTP %s)\n' "$client" "$KC_STATUS" >&2 + return 1 + } + _assist_fresh_token "$product" "$client" "$token_variable" +} + +# _assist_fresh_token PRODUCT CLIENT TOKEN_VARIABLE: a client-credentials +# token from the journey's Keycloak into TOKEN_VARIABLE, registered as a secret. +_assist_fresh_token() { + local product=$1 client=$2 token_variable=$3 secret_file response token + journey_secret_path "client-$product" secret_file + response=$(curl --silent --show-error --max-time 30 \ + --data grant_type=client_credentials --data-urlencode "client_id=$client" \ + --data-urlencode "client_secret@$secret_file" \ + "$KC_ISSUER/protocol/openid-connect/token") || return 1 + token=$(printf '%s' "$response" | jq -r '.access_token // empty') || return 1 + [[ -n "$token" ]] || { + printf 'assist mapper: Keycloak issued no token after the client change\n' >&2 + return 1 + } + printf -v "$token_variable" '%s' "$token" + journey_secret_register "$product-access-token" "$token_variable" +} diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 5741f0198e..c6b10e5ca8 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -970,6 +970,7 @@ logged_stage() { open my $fh, "<", $path or next; my $text = <$fh>; next unless defined $text; + $text =~ s/\e\[[0-9;]*m//g; while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2/g) { $stage = defined $1 ? $1 : $3; } @@ -1032,13 +1033,27 @@ step_call() { [[ -z "$stage" ]] || break [[ $attempt -eq 3 ]] || sleep 1 done - # shellcheck disable=SC2086 # CLAIMS is a list of words - missing=$(missing_claims ACCESS_TOKEN $CLAIMS) - if [[ -n "$missing" && (-z "$stage" || "$stage" == profile) ]]; then - # shellcheck disable=SC2086 # missing is a list of words - if ! journey_blocker call journey.needs.claim-mapper mapper "$CELL" "$CLIENT" ACCESS_TOKEN $missing; then - CELL_OVER=1 - return 0 + # Each blocker the assists can clear is met once. After an assist the call + # is made again. The shared verifier logs a stage at most once a minute, so + # the log of a second refusal repeats the stage of the first: a token-type + # refusal already assisted is followed by the claim check, not by a second + # token-type assist. + for attempt in 1 2; do + # shellcheck disable=SC2086 # CLAIMS is a list of words + missing=$(missing_claims ACCESS_TOKEN $CLAIMS) + if [[ "$stage" == token-type && $attempt -eq 1 ]]; then + if ! journey_blocker call "http.$JOURNEY_HTTP_STATUS.token-type" token-type "$CELL" "$CLIENT" ACCESS_TOKEN; then + CELL_OVER=1 + return 0 + fi + elif [[ -n "$missing" && (-z "$stage" || "$stage" == profile || $attempt -eq 2) ]]; then + # shellcheck disable=SC2086 # missing is a list of words + if ! journey_blocker call journey.needs.claim-mapper mapper "$CELL" "$CLIENT" ACCESS_TOKEN $missing; then + CELL_OVER=1 + return 0 + fi + else + break fi status=0 call_request || status=$? @@ -1046,9 +1061,12 @@ step_call() { journey_reached t1 return 0 fi + # The refusal of this call is logged after the response is written, and + # the log already holds the one before it. + sleep 1 refresh_server_log stage=$(logged_stage "$SERVER_LOG_OUT" "$SERVER_LOG_ERR") - fi + done if [[ -z "$stage" ]]; then # A product whose log names no stage still names its refusal in the # problem body. That code is recorded rather than a stage the journey diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh new file mode 100755 index 0000000000..139d0e32a8 --- /dev/null +++ b/products/platform/journeys/promote.sh @@ -0,0 +1,544 @@ +#!/usr/bin/env bash +# The promote acceptance journey: the files a development journey ended with, +# started as production. +# +# Steps, as the pass rule counts them: input, start-as-production, refusals, +# fix, start, call, same-contract. A cell is one product and stops at its first +# failing step. See README.md for the options, the two modes and the exit codes. +# +# input the development journey's run directory holds a +# finished cell for the product: a pass, or a cell +# that reached its first authenticated read (toT1) and +# stopped only at a step that cannot be walked by +# design, as an assisted cell does at hook. Otherwise the cell stops with +# journey.promote.no-input. +# start-as-production the same files, started with no development +# declaration. A refused start is an observation, not a +# failure: the step passes once the product either +# answered its readiness route or exited printing a +# diagnostic code. +# refusals the list of diagnostic codes from the product's +# production check and the list from the start. The two +# lists must be equal, or the run stops as a harness +# failure. An empty list stops the cell with +# journey.promote.nothing-refused. The count goes to +# refusalsMet in summary.json. +# fix each refusal is fixed by the function fix_. A +# code with no function is a harness failure that names +# it, so a new refusal is looked at and never recorded +# under a code the product did not print. Before the +# fixes the step fetches a token from the input's +# identity provider and keeps its claim names. +# start the fixed files, started. A refusal stops the cell +# with the product's code. +# call the same token source and the same request as the +# development journey. A refusal stops the cell with +# http... +# same-contract the request line, the headers other than the token +# and the token's claim names equal those the files gave +# before the fixes. The development journey saves no +# request, so the request is rebuilt from the same +# recipe and only the claim names are a real comparison. +# +# The input. --from RUN_DIR is a run directory of own-provider.sh that ended +# with --keep, under the same JOURNEY_CONTAINER_PREFIX. Without --from this run +# first runs own-provider.sh --keep into -input. The runtime files hold absolute paths into that +# directory, so promote uses it in place and never copies it. The run takes +# over the kept containers and secrets, so its cleanup removes them. Without +# any finished cell, and with --from, the input is only read and no container is +# touched. +# +# What this script starts: no container of its own (a run without --from makes +# own-provider.sh start the two). One product process at a time, on the port the +# input's own-provider.json records. When the run ends it removes the input's +# containers and deletes its secrets/, through lib.sh's take-over. +# +# Run it from anywhere: +# products/platform/journeys/promote.sh --bin-dir DIR [--from RUN_DIR] +# [--product ID]... [--out DIR] [--expected FILE [--strict]] + +set -euo pipefail + +# shellcheck disable=SC1091 # lib.sh is checked on its own +source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" + +journey_init promote --value-option from -- "$@" + +journey_resolve_binaries "${JOURNEY_PRODUCTS[@]}" + +# The input: --from RUN_DIR, or a run of own-provider.sh that this run makes +# with --keep, in a sibling of its own output directory so that the kept +# secrets are never inside the folder this run scans. A run this script made +# is always taken over, so a run in which no cell finishes still removes the +# containers the input left. +FROM='' +INPUT_JOURNEY='' +INPUT_MADE=0 +prepare_input() { + local option status=0 + local -a arguments=() + journey_option_value from option + if [[ -z "$option" ]]; then + FROM=$JOURNEY_OUT-input + for option in ${JOURNEY_SELECTED[@]+"${JOURNEY_SELECTED[@]}"}; do + arguments+=(--product "$option") + done + "$JOURNEY_LIB_DIR/own-provider.sh" --keep --bin-dir "$JOURNEY_BIN_DIR" --out "$FROM" ${arguments[@]+"${arguments[@]}"} || status=$? + # Exit 1 is the development journey's own answer on main: some cell + # did not finish. Anything else is a harness or usage failure. + [[ $status -le 1 ]] || journey_harness_failure "own-provider.sh, run as the input, exited with status $status; see its output above" + INPUT_MADE=1 + else + [[ -d "$option" ]] || journey_usage_error "--from $option is not a directory" + FROM=$(CDPATH='' cd -- "$option" && pwd -P) || journey_usage_error "cannot resolve --from $option" + fi + [[ -f "$FROM/run.json" && -f "$FROM/summary.json" ]] || + journey_usage_error "$FROM holds no run.json and summary.json: it is not a journey run directory" + INPUT_JOURNEY=$(jq -er '.journey' "$FROM/run.json") || journey_usage_error "cannot read the journey name in $FROM/run.json" +} + +# The cell's product, its input and the facts the steps share. +CELL='' +PROJECT='' +RUNTIME_FILE='' +PORT='' +TOOL_BIN='' +SERVER_BIN='' +READY_PATH=/ready +STATE_FILE='' +TAKEN_OVER=0 +SERVE_COMMAND=() +CHECK_COMMAND=() +START_CODES='' +CHECK_CODES='' + +# field PRODUCT FIELD: a products.yaml field on stdout. +field() { + local value + journey_product_field "$1" "$2" value + printf '%s' "$value" +} + +# input_outcome PRODUCT VAR: whether the development journey finished the +# product: `finished`, else the outcome it recorded (fail, unreached) or +# `missing` when summary.json has no cell. A cell finished when it passed, or +# when it reached the first authenticated read (toT1) and then stopped only at a +# step the journey cannot walk by design, as an assisted cell does at the hook +# step. An assisted cell is accepted: the baseline input is an assisted run, and +# promote starts from the files the assists left. +input_outcome() { + local value + value=$(jq -r --arg product "$1" '[.cells[] | select(.product == $product)] | if length != 1 then "missing" + elif .[0].outcome == "pass" or (.[0].outcome == "unreached" and .[0].toT1 != null) then "finished" + else .[0].outcome end' "$FROM/summary.json") || + journey_harness_failure "cannot read the cell of $1 in $FROM/summary.json" + printf -v "$2" '%s' "$value" +} + +# take_over_input: the run becomes responsible for the kept containers and +# secrets of the input, once, before the first product is started. +take_over_input() { + [[ $TAKEN_OVER -eq 0 ]] || return 0 + [[ -f "$FROM/kept" ]] || + journey_usage_error "$FROM has a finished cell but was not run with --keep, so its database and identity provider are gone; run $INPUT_JOURNEY with --keep" + journey_require_docker + journey_take_over_run "$FROM" + TAKEN_OVER=1 +} + +# locate_input PRODUCT: PROJECT, RUNTIME_FILE and PORT of the input's files. +locate_input() { + local product=$1 + case "$INPUT_JOURNEY" in + own-provider) ;; + *) journey_harness_failure "no input layout is written for journey $INPUT_JOURNEY; add one to locate_input in promote.sh" ;; + esac + PROJECT=$FROM/work/$product/$product + case "$product" in + evidence) RUNTIME_FILE=$PROJECT/local-target.yaml ;; + render) RUNTIME_FILE=$FROM/work/render/runtime.yaml ;; + *) RUNTIME_FILE=$PROJECT/runtime.yaml ;; + esac + [[ -f "$RUNTIME_FILE" ]] || journey_harness_failure "the input of $product holds no runtime file at $RUNTIME_FILE" + PORT=$(jq -er '.productPort' "$FROM/own-provider.json") || + journey_harness_failure "cannot read productPort in $FROM/own-provider.json" +} + +# recipe PRODUCT: the tool, the server, the readiness route, the command that +# starts the runtime and the production check, as the reader types them. A +# product without a recipe is a harness failure that names the gap. +recipe() { + local product=$1 tool server help + READY_PATH=/ready + server=$(field "$product" binary) + case "$product" in + breg) tool=bregctl ;; + casework) tool=caseworkctl ;; + messaging) tool=messagingctl ;; + scheduling) tool=schedulingctl ;; + documents) tool=documentsctl ;; + coordinator) tool=coordinatorctl ;; + adapter) tool=adapterctl ;; + evidence) tool=evidencectl ;; + render) tool=registry-render ;; + *) journey_harness_failure "no recipe is written for product $product; add one to recipe in promote.sh" ;; + esac + journey_bin "$tool" TOOL_BIN + journey_bin "$server" SERVER_BIN + case "$product" in + breg | coordinator) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE") ;; + casework | messaging | scheduling | documents) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE" serve) ;; + render) SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE") ;; + *) journey_harness_failure "no start recipe is written for $product; add one to recipe in promote.sh" ;; + esac + [[ "$product" != scheduling ]] || READY_PATH=/readyz + case "$product" in + breg | casework | scheduling) CHECK_COMMAND=("$TOOL_BIN" --format json check "$PROJECT" --runtime-config "$RUNTIME_FILE") ;; + messaging | documents) CHECK_COMMAND=("$TOOL_BIN" --format json check --runtime-config "$RUNTIME_FILE") ;; + coordinator) CHECK_COMMAND=("$TOOL_BIN" --format json --runtime-config "$RUNTIME_FILE" check --project "$PROJECT") ;; + render) CHECK_COMMAND=("$TOOL_BIN" check --runtime-config "$RUNTIME_FILE" --format json) ;; + adapter) + CHECK_COMMAND=("$TOOL_BIN" --format json check "$PROJECT/project.yaml" + --profile "$JOURNEY_ROOT/products/adapter/profiles/breg-records/profile.yaml" + --pack "$PROJECT/pack.yaml" --runtime "$RUNTIME_FILE") + ;; + evidence) CHECK_COMMAND=("$TOOL_BIN" check "$PROJECT" --target "$RUNTIME_FILE" --format json) ;; + esac + # The production check is the same check with the tool's production flag, + # for a tool that has one. A tool without it has no production check, so + # its list is the plain check's. + help=$("$TOOL_BIN" check --help 2>&1) || journey_harness_failure "cannot read the help of $tool check" + if [[ "$help" == *--production* ]]; then + CHECK_COMMAND+=(--production) + fi +} + +# diagnostic_codes FILE...: every diagnostic code a product printed in FILE, one +# per line, sorted and unique: the code nested in a diagnostic's message as +# error[code], else the diagnostic's own code, plus the code of a human +# error[code] line. +diagnostic_codes() { + local file + for file in "$@"; do + [[ -s "$file" ]] || continue + jq -r '(.diagnostics[]? | ((.message // "") | [match("error\\[([a-z0-9._-]+)\\]").captures[0].string] | first) // .code), + (.error.code? // empty)' "$file" 2>/dev/null || true + perl -ne 'print "$1\n" if /^error\[([a-z0-9._-]+)\]/' "$file" + done | LC_ALL=C sort -u +} + +# port_is_free PORT +port_is_free() { + perl -MIO::Socket::INET -e ' + IO::Socket::INET->new(LocalAddr => "127.0.0.1", LocalPort => $ARGV[0], Proto => "tcp", Listen => 1, ReuseAddr => 1) + or exit 1;' "$1" +} + +# production_start: start the product with the input's files and no +# development declaration, wait for its readiness route or its exit, and write +# `started` or `refused` to STATE_FILE. The product's own output is the step's +# output. A started product is stopped before this returns. Exits 0 once the +# attempt has an answer, so a refused start is an observation. +# shellcheck disable=SC2329 # run through journey_step +production_start() { + local pid attempt=0 state='' + "${SERVE_COMMAND[@]}" & + pid=$! + while ((attempt < 60)); do + if ! kill -0 "$pid" 2>/dev/null; then + state=refused + break + fi + if curl --silent --fail --output /dev/null "http://127.0.0.1:$PORT$READY_PATH"; then + state=started + break + fi + sleep 0.5 + attempt=$((attempt + 1)) + done + if [[ -z "$state" ]]; then + printf 'the product neither answered %s nor exited within 30 seconds\n' "$READY_PATH" >&2 + kill -TERM "$pid" 2>/dev/null || true + wait "$pid" 2>/dev/null || true + return 1 + fi + if [[ "$state" == refused ]]; then + wait "$pid" 2>/dev/null || printf 'the product exited with status %s\n' "$?" >&2 + else + kill -TERM "$pid" + for attempt in $(seq 1 100); do + kill -0 "$pid" 2>/dev/null || break + sleep 0.1 + done + if kill -0 "$pid" 2>/dev/null; then + kill -KILL "$pid" + printf 'the product ignored SIGTERM and was killed\n' >&2 + fi + wait "$pid" 2>/dev/null || true + fi + printf '%s\n' "$state" >"$STATE_FILE" +} + +# production_check: the production check, whatever it answers. Its exit status +# goes to stderr; its report is the step's stdout. +# shellcheck disable=SC2329 # run through journey_step +production_check() { + local status=0 + "${CHECK_COMMAND[@]}" || status=$? + printf 'check exit status %s\n' "$status" >&2 +} + +# FIX_TABLE: the fix for each diagnostic code a production refusal may carry, +# applied to the reader's files. A function per code, named +# fix_, is looked up here. The table +# is empty until a production posture exists to refuse anything. +apply_fix() { + local code=$1 function + function=fix_${code//[.-]/_} + if ! declare -F "$function" >/dev/null; then + journey_harness_failure "the production refusal '$code' of $CELL has no fix in promote.sh; add $function and the sentence it applies" + fi + "$function" +} + +# call_recipe PRODUCT: the caller's client in the input's identity provider +# and the first authenticated request, as the development journey makes it. +# Sets CLIENT, CALL_METHOD, CALL_PATH and +# CALL_OPTIONS (extra request options). The request has no body unless the +# product's tutorial needs one. +call_recipe() { + local product=$1 work + journey_workdir "$product" work + CALL_METHOD=GET + CALL_OPTIONS=() + case "$product" in + breg) + CLIENT="directory-client" + CALL_PATH=/v1/records/contacts + ;; + casework) + CLIENT="casework-client" + CALL_PATH=/v1/review-policies + ;; + messaging) + CLIENT="case-system" + CALL_METHOD=POST + CALL_PATH=/v1/messages + printf '%s\n' '{"senderProfile":"reminders-sms","to":{"phone":"+15555550100"},"template":{"id":"appointment-reminder-sms","version":"1"},"locale":"en","data":{"name":"Ada Lovelace","day":"2026-10-01","office":"Central Registry Office"}}' | + journey_write_file "$work/call-body.json" + CALL_OPTIONS=(--header 'Content-Type: application/json' --header 'Idempotency-Key: journey-first-call' --data-file "$work/call-body.json") + ;; + scheduling) + CLIENT="scheduling-booking-agent" + CALL_PATH=/v1/locations + ;; + documents) + CLIENT="case-portal" + CALL_PATH=/v1/document-policies + ;; + coordinator) + CLIENT="coordinator-producer" + CALL_PATH=/v1/workflows/coordinator + ;; + render) + CLIENT="portal" + CALL_METHOD=POST + CALL_PATH=/v1/render/letter + [[ -f "$FROM/work/render/request.json" ]] || journey_harness_failure "the input of render holds no request.json" + CALL_OPTIONS=(--header 'Content-Type: application/json' --data-file "$FROM/work/render/request.json") + ;; + *) journey_harness_failure "no call recipe is written for $product; add one to call_recipe in promote.sh" ;; + esac +} + +# fetch_token STEP VAR: a client-credentials token for CLIENT from the input's +# identity provider, the same source the development journey used, into VAR. +# The client secret is the input's kept secret client-. +fetch_token() { + local step=$1 variable=$2 token_url + token_url=$(jq -er '.issuerUrl' "$FROM/own-provider.json")/protocol/openid-connect/token || + journey_harness_failure "cannot read issuerUrl in $FROM/own-provider.json" + journey_http "$step" --concepts client,grant,scopes \ + --typed "curl -X POST $token_url -d grant_type=client_credentials -d client_id=$CLIENT -d client_secret=\$SECRET" \ + --form grant_type=client_credentials --form "client_id=$CLIENT" --form-secret "client_secret=client-$CELL" \ + --capture-secret .access_token "$variable" POST "$token_url" || + journey_harness_failure "the identity provider refused the client credentials of $CLIENT (HTTP $JOURNEY_HTTP_STATUS); see $JOURNEY_STEP_STDOUT" +} + +# claim_names VARIABLE: the names of the claims in the token held in VARIABLE, +# sorted, one per line. The token reaches perl through a pipe. +claim_names() { + local variable=$1 + printf '%s' "${!variable}" | perl -MMIME::Base64 -MJSON::PP -e ' + local $/; my $token = ; + my $payload = (split /\./, $token)[1] // ""; + $payload =~ tr{-_}{+/}; + $payload .= "=" x ((4 - length($payload) % 4) % 4); + print "$_\n" for sort keys %{ decode_json(decode_base64($payload)) };' || + journey_harness_failure "cannot read the claims of the token of $CELL" +} + +# logged_stage FILE...: the last authentication stage the product logged. +logged_stage() { + perl -e ' + my $stage = ""; + local $/; + for my $path (@ARGV) { + open my $fh, "<", $path or next; + my $text = <$fh>; + next unless defined $text; + $text =~ s/\e\[[0-9;]*m//g; + while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2/g) { + $stage = defined $1 ? $1 : $3; + } + } + print $stage;' "$@" +} + +# The request as the development journey made it and as promote makes it: the +# method, the path and the headers other than the token's. The development +# journey does not save its request, so the contract is rebuilt from the same +# recipe, and the token's claim names are read from a token fetched from the +# same source before the fixes. +request_contract() { + printf '%s %s\n' "$CALL_METHOD" "$CALL_PATH" + printf '%s\n' "${CALL_OPTIONS[@]+"${CALL_OPTIONS[@]}"}" | LC_ALL=C sort +} + +# promote_call_failure: the call after the fixes was refused. The cell stops +# with the status and the authentication stage the product logged, or with the +# problem code when its log names no stage. +promote_call_failure() { + local stage='' attempt + [[ "$JOURNEY_HTTP_STATUS" != 000 ]] || + journey_harness_failure "the call to $CELL got no answer; see $JOURNEY_STEP_STDERR" + for attempt in 1 2 3; do + journey_process_log server SERVER_LOG_UNUSED + stage=$(logged_stage "$START_STDOUT" "$START_STDERR") + [[ -z "$stage" ]] || break + [[ $attempt -eq 3 ]] || sleep 1 + done + if [[ -n "$stage" ]]; then + journey_fail call "http.$JOURNEY_HTTP_STATUS.$stage" + elif [[ "${JOURNEY_HTTP_PROBLEM_CODE:-}" =~ ^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)*$ ]]; then + journey_fail call "product.$JOURNEY_HTTP_PROBLEM_CODE" + else + journey_harness_failure "the call to $CELL answered HTTP $JOURNEY_HTTP_STATUS with no authentication stage in its log and no problem code; see $JOURNEY_HTTP_HEADERS" + fi +} + +walk_product() { + local product=$1 tier outcome count code dev_claims dev_contract + journey_product_field "$product" tier tier + CELL=$product + journey_cell_begin "$product" + if [[ "$tier" == supporting ]]; then + journey_unreached input "Supporting runtime. It is promoted with its parent." + journey_cell_end + return 0 + fi + + # input + input_outcome "$product" outcome + if [[ "$outcome" != finished ]]; then + printf 'promote: the %s journey did not finish for %s (cell outcome %s); nothing to promote\n' "$INPUT_JOURNEY" "$product" "$outcome" >&2 + journey_fail input journey.promote.no-input + journey_cell_end + return 0 + fi + locate_input "$product" + recipe "$product" + call_recipe "$product" + take_over_input + journey_pass input + + # start-as-production + STATE_FILE=$JOURNEY_OUT/$product/production-start.state + port_is_free "$PORT" || journey_harness_failure "port $PORT is in use; promote cannot start $product on it" + journey_step start-as-production --timeout 90 --typed "${SERVE_COMMAND[*]##*/}" -- production_start || + journey_harness_failure "the start of $product neither answered nor exited; see $JOURNEY_STEP_STDERR" + [[ -f "$STATE_FILE" ]] || journey_harness_failure "the start attempt of $product left no state; see $JOURNEY_STEP_STDERR" + START_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR") + if [[ "$(<"$STATE_FILE")" == refused && -z "$START_CODES" ]]; then + journey_harness_failure "the start of $product was refused and printed no diagnostic code; see $JOURNEY_STEP_STDERR" + fi + if [[ "$(<"$STATE_FILE")" == started ]]; then + START_CODES='' + fi + journey_pass start-as-production + + # refusals + journey_step refusals --typed "${CHECK_COMMAND[*]##*/}" -- production_check || + journey_harness_failure "the production check of $product did not run; see $JOURNEY_STEP_STDERR" + CHECK_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT") + if [[ "$CHECK_CODES" != "$START_CODES" ]]; then + journey_harness_failure "the production check of $product lists [${CHECK_CODES//$'\n'/ }] and its start lists [${START_CODES//$'\n'/ }]; the two lists must be equal (see $JOURNEY_STEP_STDOUT)" + fi + if [[ -z "$CHECK_CODES" ]]; then + journey_fail refusals journey.promote.nothing-refused + journey_cell_end + return 0 + fi + count=$(printf '%s\n' "$CHECK_CODES" | wc -l | tr -d ' ') + journey_count refusals "$count" + journey_pass refusals + + # fix: first the contract as the development files give it (the claim names + # of a token from the same source and the request), then each refusal's fix. + fetch_token fix DEV_TOKEN + dev_claims=$(claim_names DEV_TOKEN) + dev_contract=$(request_contract) + while IFS= read -r code; do + apply_fix "$code" + done <<<"$CHECK_CODES" + journey_pass fix + + # start: the fixed files, started as production. Any refusal now is the + # cell's stop, with the product's code. + local status=0 + port_is_free "$PORT" || journey_harness_failure "port $PORT is in use; promote cannot start $product on it" + journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? + if [[ $status -ne 0 ]]; then + code=$(diagnostic_codes "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" | head -n 1) + [[ -n "$code" ]] || journey_harness_failure "the start of $product after the fixes was refused and printed no diagnostic code; see $JOURNEY_STEP_STDERR" + journey_fail start "product.$code" + journey_cell_end + return 0 + fi + START_STDOUT=$JOURNEY_STEP_STDOUT + START_STDERR=$JOURNEY_STEP_STDERR + journey_ready start server --timeout 90 -- curl --silent --show-error --fail --output /dev/null "http://127.0.0.1:$PORT$READY_PATH" || + journey_harness_failure "$product kept running but did not answer $READY_PATH within 90 seconds; see $START_STDERR" + journey_pass start + + # call: the same token source and the same request. + fetch_token call TOKEN + journey_http call --bearer TOKEN "${CALL_OPTIONS[@]+"${CALL_OPTIONS[@]}"}" "$CALL_METHOD" "http://127.0.0.1:$PORT$CALL_PATH" || status=$? + if [[ $status -ne 0 ]]; then + promote_call_failure + journey_cell_end + return 0 + fi + journey_pass call + + # same-contract: the request and the token's claim names are those the + # development files gave. Stopping the server is part of this step. + if [[ "$(claim_names TOKEN)" != "$dev_claims" ]]; then + journey_harness_failure "the token claims of $product differ between the development files and the production start" + fi + [[ "$(request_contract)" == "$dev_contract" ]] || journey_harness_failure "the request of $product changed between the development files and the production start" + journey_stop same-contract server || journey_harness_failure "the server of $product ignored SIGTERM" + journey_pass same-contract + journey_cell_end +} + +prepare_input +if [[ $INPUT_MADE -eq 1 ]]; then + take_over_input +fi + +for product in "${JOURNEY_PRODUCTS[@]}"; do + walk_product "$product" +done + +journey_finish From 4b269bf0e034318828d48a05ab5e477d948b02d6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 03:54:37 +0100 Subject: [PATCH 021/136] fix(platform): name each token refusal's cause and type the refusal trace id A header alg that does not fit the named key, or a kid that names an encryption key, is a token fault, not a key-source fault. Missing aud, iss and time claims each map to their own variant, and a UserInfo subject mismatch has its own. record_refusal! takes only a typed trace id, so authcommon no longer depends on httpsec. An empty private range list for a private service fails at construction. The failed-check names, the private JWK member list and the documentation each have one source. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + .../src/convert.rs | 20 +- .../src/convert.rs | 20 +- .../registry-platform-authcommon/Cargo.toml | 2 + crates/registry-platform-authcommon/README.md | 18 + .../registry-platform-authcommon/src/lib.rs | 4 +- .../src/refusal.rs | 450 +++++++++++------- crates/registry-platform-httpsec/Cargo.toml | 14 +- crates/registry-platform-httpsec/README.md | 13 +- .../registry-platform-httpsec/src/loopback.rs | 29 +- .../registry-platform-httpsec/src/server.rs | 28 ++ .../src/client/outbound.rs | 2 + .../src/destination.rs | 54 ++- crates/registry-platform-httputil/src/lib.rs | 51 +- .../registry-platform-oidc/src/diagnostics.rs | 70 ++- crates/registry-platform-oidc/src/lib.rs | 316 ++++++++++-- .../registry-platform-oidc/src/static_jwks.rs | 101 +++- products/platform/AGENTS.md | 3 +- products/platform/CHANGELOG.md | 60 ++- 19 files changed, 997 insertions(+), 259 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a0f195d2f..ab21645037 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7942,6 +7942,7 @@ version = "0.49.0" dependencies = [ "axum", "http", + "registry-platform-authcommon", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/registry-evidence-client-node/src/convert.rs b/crates/registry-evidence-client-node/src/convert.rs index fa1d412fd3..8bbc417818 100644 --- a/crates/registry-evidence-client-node/src/convert.rs +++ b/crates/registry-evidence-client-node/src/convert.rs @@ -18,7 +18,7 @@ use registry_evidence_client::{ SelectorValue, StaticToken, SubjectBindingReceipt, SubjectExpectations, SubjectRequest, TokenError, TokenProvider, }; -use registry_platform_crypto::PrivateJwk; +use registry_platform_crypto::{PrivateJwk, PRIVATE_JWK_MEMBERS}; use registry_platform_httputil::{exchange_authorization_from_json, ExchangeAuthorization}; use serde_json::{Map, Value}; use url::Url; @@ -595,15 +595,15 @@ fn response_format_from_json(value: &Value) -> Result Result` format. - Constant-time API-key fingerprint comparison through `subtle`. - A 32-byte minimum raw API-key entropy floor for generated keys. +- `FailedCheck`, the closed set of checks a request can fail, each with a + stable kebab-case label (`as_str`). It is operator-side only and is never + written to a response. +- `RefusalTraceId`, the trace id a refusal line may carry. It is sealed by + convention, and `registry_platform_httpsec::TraceId` implements it under + httpsec's `server` feature. This crate does not depend on httpsec. +- Behind the `refusal-recorder` feature: `RefusalRecorder`, which counts + every refusal in `_request_refusals_total{check}` and admits at + most five log lines per check per minute, and `record_refusal!`, which + writes the admitted line with `failed_check`, `suppressed`, an optional + code-defined `remedy` and an optional `trace_id` (a `RefusalTraceId`). ## Typical Use @@ -43,11 +54,18 @@ Ok(()) generation still belongs to a cryptographically secure generator. - Store and compare fingerprints, not plaintext API keys. - Treat returned Bearer tokens as secrets and avoid logging them. +- Alert and diagnose on the refusal counter, not on the log line. The log + budget is process-wide, so unauthenticated traffic can spend a check's + lines; `suppressed` on the next admitted line shows how many were dropped. +- Call `record_refusal!` outside any span that records request values (a + URI, query, header, client id or subject). Formatters print the enclosing + span's fields on the refusal line. ## Testing ```sh cargo test -p registry-platform-authcommon +cargo test -p registry-platform-authcommon --features refusal-recorder ``` ## License diff --git a/crates/registry-platform-authcommon/src/lib.rs b/crates/registry-platform-authcommon/src/lib.rs index 7624bda2c1..5d8b5b516e 100644 --- a/crates/registry-platform-authcommon/src/lib.rs +++ b/crates/registry-platform-authcommon/src/lib.rs @@ -4,7 +4,9 @@ pub mod client_assertion; pub mod refusal; -pub use refusal::FailedCheck; +#[doc(hidden)] +pub use refusal::__refusal_trace_id_seal; +pub use refusal::{FailedCheck, RefusalTraceId}; #[cfg(feature = "refusal-recorder")] pub use refusal::{ RefusalLine, RefusalNote, RefusalRecorder, REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, diff --git a/crates/registry-platform-authcommon/src/refusal.rs b/crates/registry-platform-authcommon/src/refusal.rs index 012661cf64..9e1f05c2d3 100644 --- a/crates/registry-platform-authcommon/src/refusal.rs +++ b/crates/registry-platform-authcommon/src/refusal.rs @@ -3,205 +3,146 @@ //! //! The check is operator-side only. It is never written to a response body. -/// The check a request failed. Closed. Operator-side only: never written to a -/// response. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum FailedCheck { +/// Declares [`FailedCheck`], [`FailedCheck::ALL`] and [`FailedCheck::as_str`] +/// from one list, so a member cannot exist without its label and its place in +/// `ALL`. +macro_rules! failed_checks { + ($($(#[$doc:meta])* $member:ident => $label:literal,)+) => { + /// The check a request failed. Closed. Operator-side only: never written to a + /// response. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub enum FailedCheck { + $($(#[$doc])* $member,)+ + } + + impl FailedCheck { + /// Every member, in declaration order. + pub const ALL: [Self; [$($label),+].len()] = [$(Self::$member),+]; + + /// The number of members. + pub const COUNT: usize = Self::ALL.len(); + + /// Stable kebab-case label for the counter and the log line. + pub const fn as_str(self) -> &'static str { + match self { + $(Self::$member => $label,)+ + } + } + } + }; +} + +failed_checks! { /// No credential, or not the scheme the route takes. - CredentialMissing, + CredentialMissing => "credential-missing", /// Credential header repeated or unreadable, or the credential is not in the expected shape. - CredentialMalformed, + CredentialMalformed => "credential-malformed", /// Signing algorithm not allowed. - TokenAlgorithm, + TokenAlgorithm => "token-algorithm", /// Token type not allowed. - TokenType, + TokenType => "token-type", /// Key id missing, too long or unknown. - TokenKey, + TokenKey => "token-key", /// Signature does not verify. - TokenSignature, + TokenSignature => "token-signature", /// Issuer is not the configured one. - TokenIssuer, + TokenIssuer => "token-issuer", /// Audience does not include this service. - TokenAudience, + TokenAudience => "token-audience", /// Expired, not yet valid, or time claims unusable. - TokenTime, + TokenTime => "token-time", /// Client not on the verifier's allow list, or the matched client is unusable. - TokenClient, + TokenClient => "token-client", /// An exchanged token whose assertion issuer is not allowed or not declared. - TokenAssertionIssuer, + TokenAssertionIssuer => "token-assertion-issuer", /// A required identity claim is missing or malformed (principal, subject, issuer, expiry). - TokenClaims, + TokenClaims => "token-claims", /// Actor kind claim missing, malformed, or not the kind the route or profile takes. - ActorKind, + ActorKind => "actor-kind", /// A delegated actor is present where none is allowed, or is not the trusted one. - Delegation, + Delegation => "delegation", /// The token is sender-constrained and the service does not accept that. - SenderConstraint, + SenderConstraint => "sender-constraint", /// The verifier could not reach or use its key source. - KeySourceUnavailable, + KeySourceUnavailable => "key-source-unavailable", /// A static secret, API key, Basic pair or path token does not match. - SharedSecret, + SharedSecret => "shared-secret", /// A single-use code or token is unknown, expired, already used or locked out. - OneTimeCredential, + OneTimeCredential => "one-time-credential", /// A signed delivery or provider callback has a missing, malformed, unsupported or wrong signature. - DeliverySignature, + DeliverySignature => "delivery-signature", /// A signed delivery time is outside the receiver's window. - DeliveryFreshness, + DeliveryFreshness => "delivery-freshness", /// A signed delivery's source, type, schema, route or target is not what the receiver expects. - DeliveryBinding, + DeliveryBinding => "delivery-binding", /// The request's host or origin is not accepted. - HostOrigin, + HostOrigin => "host-origin", /// A required scope is missing. - Scope, + Scope => "scope", /// No access profile, policy or authority entry admits this caller on this surface. - AccessProfile, + AccessProfile => "access-profile", /// The profile or resource does not admit this requester client. - RequesterClient, + RequesterClient => "requester-client", /// The declared purpose is missing or not admitted. - Purpose, + Purpose => "purpose", /// The caller's profile or policy does not allow this operation, action, workflow, template or record type. - Operation, + Operation => "operation", /// The request asks for fields or a response format beyond what the caller's profile discloses. - Disclosure, + Disclosure => "disclosure", /// The subject selector is not one the caller's grant or authority covers. - SubjectSelector, + SubjectSelector => "subject-selector", /// The caller pinned a configuration revision that is not the deployed one. - RevisionPin, + RevisionPin => "revision-pin", /// The acquisition channel is not open to the resolved profile. - AcquisitionChannel, + AcquisitionChannel => "acquisition-channel", /// The source or target authority refused the access. - SourceAuthority, + SourceAuthority => "source-authority", /// The caller already acted in a role that excludes this one. - SeparationOfDuties, + SeparationOfDuties => "separation-of-duties", /// The operation needs a task grant and none was presented. - TaskGrantMissing, + TaskGrantMissing => "task-grant-missing", /// The task grant is partial or malformed. - TaskGrantClaims, + TaskGrantClaims => "task-grant-claims", /// The task grant has expired. - TaskGrantExpired, + TaskGrantExpired => "task-grant-expired", /// The task grant is bound to another client, audience, principal, issuer or task. - TaskGrantBinding, + TaskGrantBinding => "task-grant-binding", /// The task grant does not cover this service, location, action or operation. - TaskGrantScope, + TaskGrantScope => "task-grant-scope", /// The task grant has more lifetime, or more lifetime left, than the receiver accepts. - TaskGrantLifetime, + TaskGrantLifetime => "task-grant-lifetime", /// The status authority says the grant is inactive, or its source is not listed. - TaskGrantStatus, + TaskGrantStatus => "task-grant-status", /// The target row is outside the caller's row boundary. - RowBoundary, + RowBoundary => "row-boundary", /// The target exists and belongs to another caller. - Ownership, + Ownership => "ownership", /// The target is absent or not visible to the caller, and the product does not tell which. - Visibility, + Visibility => "visibility", /// A BReg Action guard refused. Operator-side only, so an answer never tells a guard from a boundary. - ActionGuard, + ActionGuard => "action-guard", /// An identity-keyed or route-keyed request budget is spent. - RateLimit, + RateLimit => "rate-limit", } -impl FailedCheck { - /// Every member, in declaration order. - pub const ALL: [Self; 45] = [ - Self::CredentialMissing, - Self::CredentialMalformed, - Self::TokenAlgorithm, - Self::TokenType, - Self::TokenKey, - Self::TokenSignature, - Self::TokenIssuer, - Self::TokenAudience, - Self::TokenTime, - Self::TokenClient, - Self::TokenAssertionIssuer, - Self::TokenClaims, - Self::ActorKind, - Self::Delegation, - Self::SenderConstraint, - Self::KeySourceUnavailable, - Self::SharedSecret, - Self::OneTimeCredential, - Self::DeliverySignature, - Self::DeliveryFreshness, - Self::DeliveryBinding, - Self::HostOrigin, - Self::Scope, - Self::AccessProfile, - Self::RequesterClient, - Self::Purpose, - Self::Operation, - Self::Disclosure, - Self::SubjectSelector, - Self::RevisionPin, - Self::AcquisitionChannel, - Self::SourceAuthority, - Self::SeparationOfDuties, - Self::TaskGrantMissing, - Self::TaskGrantClaims, - Self::TaskGrantExpired, - Self::TaskGrantBinding, - Self::TaskGrantScope, - Self::TaskGrantLifetime, - Self::TaskGrantStatus, - Self::RowBoundary, - Self::Ownership, - Self::Visibility, - Self::ActionGuard, - Self::RateLimit, - ]; - - /// The number of members. - pub const COUNT: usize = Self::ALL.len(); - - /// Stable kebab-case label for the counter and the log line. - pub const fn as_str(self) -> &'static str { - match self { - Self::CredentialMissing => "credential-missing", - Self::CredentialMalformed => "credential-malformed", - Self::TokenAlgorithm => "token-algorithm", - Self::TokenType => "token-type", - Self::TokenKey => "token-key", - Self::TokenSignature => "token-signature", - Self::TokenIssuer => "token-issuer", - Self::TokenAudience => "token-audience", - Self::TokenTime => "token-time", - Self::TokenClient => "token-client", - Self::TokenAssertionIssuer => "token-assertion-issuer", - Self::TokenClaims => "token-claims", - Self::ActorKind => "actor-kind", - Self::Delegation => "delegation", - Self::SenderConstraint => "sender-constraint", - Self::KeySourceUnavailable => "key-source-unavailable", - Self::SharedSecret => "shared-secret", - Self::OneTimeCredential => "one-time-credential", - Self::DeliverySignature => "delivery-signature", - Self::DeliveryFreshness => "delivery-freshness", - Self::DeliveryBinding => "delivery-binding", - Self::HostOrigin => "host-origin", - Self::Scope => "scope", - Self::AccessProfile => "access-profile", - Self::RequesterClient => "requester-client", - Self::Purpose => "purpose", - Self::Operation => "operation", - Self::Disclosure => "disclosure", - Self::SubjectSelector => "subject-selector", - Self::RevisionPin => "revision-pin", - Self::AcquisitionChannel => "acquisition-channel", - Self::SourceAuthority => "source-authority", - Self::SeparationOfDuties => "separation-of-duties", - Self::TaskGrantMissing => "task-grant-missing", - Self::TaskGrantClaims => "task-grant-claims", - Self::TaskGrantExpired => "task-grant-expired", - Self::TaskGrantBinding => "task-grant-binding", - Self::TaskGrantScope => "task-grant-scope", - Self::TaskGrantLifetime => "task-grant-lifetime", - Self::TaskGrantStatus => "task-grant-status", - Self::RowBoundary => "row-boundary", - Self::Ownership => "ownership", - Self::Visibility => "visibility", - Self::ActionGuard => "action-guard", - Self::RateLimit => "rate-limit", - } - } +/// A trace id that `record_refusal!` may write on a refusal line. +/// +/// `registry_platform_httpsec::TraceId` implements it when httpsec's `server` +/// feature is on. That type holds only a validated W3C trace id, 32 lowercase +/// hexadecimal digits, so no other request value (a header, client id or +/// subject) can reach the line through this field. The trait is sealed by +/// convention: its supertrait is a hidden item, and that `TraceId`, with a +/// reference to one, is its only implementation outside this crate's tests. +pub trait RefusalTraceId: core::fmt::Display + __refusal_trace_id_seal::Sealed {} + +impl __refusal_trace_id_seal::Sealed for &T {} +impl RefusalTraceId for &T {} + +/// The hidden supertrait of [`RefusalTraceId`]. Implemented only beside a +/// `RefusalTraceId` implementation. +#[doc(hidden)] +pub mod __refusal_trace_id_seal { + pub trait Sealed {} } #[cfg(feature = "refusal-recorder")] @@ -269,6 +210,14 @@ mod recorder { /// /// State is one counter family and a fixed array of slots, one per /// [`FailedCheck`]. Nothing is keyed by a value a caller sends. + /// + /// The counter, not the log line, is the alert and diagnosis signal. Every + /// refusal is counted. The log admits at most + /// [`REFUSAL_LOG_LINES_PER_WINDOW`] lines per check per + /// [`REFUSAL_LOG_WINDOW`], process-wide, so unauthenticated traffic can + /// spend a check's lines before an honest client's refusal arrives. The + /// `suppressed` field on the first line of the next window shows how many + /// refusals of that check the window counted but did not log. pub struct RefusalRecorder { counter: CounterVec, pub(super) slots: Mutex<[Slot; FailedCheck::COUNT]>, @@ -352,31 +301,60 @@ mod recorder { } /// Count a refusal and write the admitted line at the call site's own - /// tracing target. The line names the check and nothing a caller sent. + /// tracing target. + /// + /// The line carries `decision`, `failed_check`, `suppressed`, the note's + /// code-defined `remedy` when it has one, and `trace_id` when one is + /// given. The macro takes no other value. `trace_id` must be a + /// [`RefusalTraceId`](crate::RefusalTraceId) or a reference to one, in + /// practice the request's `registry_platform_httpsec::TraceId`, as in + /// `record_refusal!(recorder, note, trace_id = &trace.trace_id)`. A raw + /// header, client id or subject does not compile: + /// + /// ```compile_fail + /// # use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote, RefusalRecorder}; + /// let recorder = RefusalRecorder::new("doc").unwrap(); + /// let client_id = String::from("a value the caller sent"); + /// record_refusal!(recorder, RefusalNote::new(FailedCheck::Scope), trace_id = client_id); + /// ``` + /// + /// The caller's obligation: tracing formatters also print the fields of + /// every span that encloses the event. Do not call this macro inside a + /// span that records request values (a URI, query, header, client id or + /// subject), or those values reach the refusal line through the span. #[macro_export] macro_rules! record_refusal { - ($recorder:expr, $note:expr $(, trace_id = $trace_id:expr)?) => {{ + (@write $recorder:expr, $note:expr, $trace_id:expr) => {{ let note: $crate::RefusalNote = $note; + let trace_id: ::core::option::Option<&dyn $crate::RefusalTraceId> = $trace_id; if let Some(line) = $recorder.record(note.check) { + let trace_id = trace_id.map($crate::__tracing::field::display); match note.remedy { Some(remedy) => $crate::__tracing::info!( decision = "refused", failed_check = line.failed_check, suppressed = line.suppressed, - remedy - $(, trace_id = %$trace_id)?, + remedy, + trace_id, "request refused" ), None => $crate::__tracing::info!( decision = "refused", failed_check = line.failed_check, - suppressed = line.suppressed - $(, trace_id = %$trace_id)?, + suppressed = line.suppressed, + trace_id, "request refused" ), } } }}; + ($recorder:expr, $note:expr) => { + $crate::record_refusal!(@write $recorder, $note, ::core::option::Option::None) + }; + ($recorder:expr, $note:expr, trace_id = $trace_id:expr) => {{ + let typed: &dyn $crate::RefusalTraceId = &$trace_id; + $crate::record_refusal!(@write $recorder, $note, ::core::option::Option::Some(typed)) + }}; } } @@ -403,6 +381,66 @@ mod tests { ); } } + + #[test] + fn the_members_labels_and_order_are_the_published_ones() { + let published = [ + ("CredentialMissing", "credential-missing"), + ("CredentialMalformed", "credential-malformed"), + ("TokenAlgorithm", "token-algorithm"), + ("TokenType", "token-type"), + ("TokenKey", "token-key"), + ("TokenSignature", "token-signature"), + ("TokenIssuer", "token-issuer"), + ("TokenAudience", "token-audience"), + ("TokenTime", "token-time"), + ("TokenClient", "token-client"), + ("TokenAssertionIssuer", "token-assertion-issuer"), + ("TokenClaims", "token-claims"), + ("ActorKind", "actor-kind"), + ("Delegation", "delegation"), + ("SenderConstraint", "sender-constraint"), + ("KeySourceUnavailable", "key-source-unavailable"), + ("SharedSecret", "shared-secret"), + ("OneTimeCredential", "one-time-credential"), + ("DeliverySignature", "delivery-signature"), + ("DeliveryFreshness", "delivery-freshness"), + ("DeliveryBinding", "delivery-binding"), + ("HostOrigin", "host-origin"), + ("Scope", "scope"), + ("AccessProfile", "access-profile"), + ("RequesterClient", "requester-client"), + ("Purpose", "purpose"), + ("Operation", "operation"), + ("Disclosure", "disclosure"), + ("SubjectSelector", "subject-selector"), + ("RevisionPin", "revision-pin"), + ("AcquisitionChannel", "acquisition-channel"), + ("SourceAuthority", "source-authority"), + ("SeparationOfDuties", "separation-of-duties"), + ("TaskGrantMissing", "task-grant-missing"), + ("TaskGrantClaims", "task-grant-claims"), + ("TaskGrantExpired", "task-grant-expired"), + ("TaskGrantBinding", "task-grant-binding"), + ("TaskGrantScope", "task-grant-scope"), + ("TaskGrantLifetime", "task-grant-lifetime"), + ("TaskGrantStatus", "task-grant-status"), + ("RowBoundary", "row-boundary"), + ("Ownership", "ownership"), + ("Visibility", "visibility"), + ("ActionGuard", "action-guard"), + ("RateLimit", "rate-limit"), + ]; + let actual: Vec<(String, &str)> = FailedCheck::ALL + .iter() + .map(|check| (format!("{check:?}"), check.as_str())) + .collect(); + let expected: Vec<(String, &str)> = published + .iter() + .map(|(member, label)| ((*member).to_string(), *label)) + .collect(); + assert_eq!(actual, expected); + } } #[cfg(all(test, feature = "refusal-recorder"))] @@ -414,6 +452,19 @@ mod recorder_tests { use crate::record_refusal; use registry_platform_metrics::Exposition; + /// A stand-in for `registry_platform_httpsec::TraceId`, which this crate + /// does not depend on. httpsec's own tests pass its `TraceId` to the macro. + struct ServerTraceId(&'static str); + + impl std::fmt::Display for ServerTraceId { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.0) + } + } + + impl crate::__refusal_trace_id_seal::Sealed for ServerTraceId {} + impl crate::RefusalTraceId for ServerTraceId {} + #[test] fn a_new_recorder_exposes_every_check_at_zero() { let recorder = RefusalRecorder::new("breg").unwrap(); @@ -527,14 +578,32 @@ mod recorder_tests { } #[test] - fn the_macro_writes_one_fixed_line_with_the_member_only() { + fn every_member_is_counted_and_logged_under_its_own_label() { let recorder = RefusalRecorder::new("breg").unwrap(); - let canary = String::from("canary-token-value-7f3a"); + for check in FailedCheck::ALL { + let label = check.as_str(); + let output = captured(|| { + record_refusal!(recorder, RefusalNote::new(check)); + }); + assert_eq!(output.lines().count(), 1, "{label}: {output}"); + assert!( + output.contains(&format!("failed_check=\"{label}\"")), + "{label}: {output}" + ); + assert!(!output.contains("ERROR"), "{label}: {output}"); + assert_eq!(recorder.counter().get(&[label]), Some(1), "{label}"); + } + assert_eq!(recorder.counter().refused(), 0); + } + + #[test] + fn a_caller_value_reaches_the_line_only_through_an_enclosing_span() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let canary = "canary-request-value-7f3a"; + + // Outside a request span the line holds the fixed fields only. let output = captured(|| { - // The caller-supplied string is in scope but is not an argument. - let note = RefusalNote::new(FailedCheck::TokenAudience); - let _unused = &canary; - record_refusal!(recorder, note); + record_refusal!(recorder, RefusalNote::new(FailedCheck::TokenAudience)); }); assert_eq!(output.lines().count(), 1, "{output}"); assert!(output.contains("request refused")); @@ -542,18 +611,65 @@ mod recorder_tests { assert!(output.contains("failed_check=\"token-audience\"")); assert!(output.contains("suppressed=0")); assert!(!output.contains("remedy")); - assert!(!output.contains("canary")); + assert!(!output.contains("trace_id")); + assert!(!output.contains("canary"), "{output}"); + + // The trace id is the only value the macro takes from a request. It + // must be a `RefusalTraceId`, so a `&str` or `String` does not compile + // (see the macro's `compile_fail` example). httpsec's tests show that + // caller text cannot become its `TraceId`. + let from_traceparent = ServerTraceId("4bf92f3577b34da6a3ce929d0e0e4736"); + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::TokenAudience), + trace_id = from_traceparent + ); + }); + assert!(output.contains("trace_id=4bf92f3577b34da6a3ce929d0e0e4736")); + assert!(!output.contains("canary"), "{output}"); + + // The documented rule: a span that records a request value prints it + // on every event inside it, the refusal line included. The macro + // cannot prevent this, so call sites must not record refusals there. + let output = captured(|| { + let span = tracing::info_span!("request", uri = canary); + let _entered = span.enter(); + record_refusal!(recorder, RefusalNote::new(FailedCheck::TokenAudience)); + }); + assert_eq!(output.lines().count(), 1, "{output}"); + assert!(output.contains(canary), "{output}"); } #[test] fn the_macro_carries_a_remedy_and_a_trace_id_when_given() { let recorder = RefusalRecorder::new("breg").unwrap(); + let trace_id = ServerTraceId("4bf92f3577b34da6a3ce929d0e0e4736"); let output = captured(|| { let note = RefusalNote::new(FailedCheck::Scope).with_remedy("check readsScope"); - record_refusal!(recorder, note, trace_id = "01TRACE"); + record_refusal!(recorder, note, trace_id = trace_id); }); assert!(output.contains("remedy=\"check readsScope\""), "{output}"); - assert!(output.contains("trace_id=01TRACE"), "{output}"); + assert!( + output.contains("trace_id=4bf92f3577b34da6a3ce929d0e0e4736"), + "{output}" + ); + + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + trace_id = &trace_id + ); + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + trace_id = ServerTraceId("0af7651916cd43dd8448eb211c80319c") + ); + }); + assert_eq!(output.lines().count(), 2, "{output}"); + assert!(!output.contains("remedy"), "{output}"); + assert!(output.contains("trace_id=0af7651916cd43dd8448eb211c80319c")); } #[test] diff --git a/crates/registry-platform-httpsec/Cargo.toml b/crates/registry-platform-httpsec/Cargo.toml index ef1780c393..49212d38f3 100644 --- a/crates/registry-platform-httpsec/Cargo.toml +++ b/crates/registry-platform-httpsec/Cargo.toml @@ -12,7 +12,17 @@ workspace = true [features] default = ["server"] -server = ["dep:axum", "dep:tokio", "dep:tower", "dep:tower-http", "dep:ulid", "dep:url"] +# `server` also implements authcommon's `RefusalTraceId` for `TraceId`, so a +# service passes its request trace id to `record_refusal!`. +server = [ + "dep:axum", + "dep:registry-platform-authcommon", + "dep:tokio", + "dep:tower", + "dep:tower-http", + "dep:ulid", + "dep:url", +] [[test]] name = "integration" @@ -21,6 +31,7 @@ required-features = ["server"] [dependencies] axum = { workspace = true, optional = true } http.workspace = true +registry-platform-authcommon = { workspace = true, optional = true } serde.workspace = true serde_json.workspace = true thiserror.workspace = true @@ -31,4 +42,5 @@ ulid = { workspace = true, optional = true } url = { workspace = true, optional = true } [dev-dependencies] +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } tokio.workspace = true diff --git a/crates/registry-platform-httpsec/README.md b/crates/registry-platform-httpsec/README.md index 6f08728ea4..c41f58ec35 100644 --- a/crates/registry-platform-httpsec/README.md +++ b/crates/registry-platform-httpsec/README.md @@ -22,7 +22,18 @@ Client-safe HTTP validation plus Axum and Tower helpers for HTTP security. 422 framework bodies in the service's own problem vocabulary through a caller-supplied mapping from `FrameworkRejection`. - `TraceId` and `TraceContext`, the shared strict W3C `traceparent` transport - primitives for Registry service responses. + primitives for Registry service responses. With the `server` feature, + `TraceId` implements `registry_platform_authcommon::RefusalTraceId`, so a + service passes its request trace id to `record_refusal!`. +- `loopback`, the one definition of loopback for outbound destinations and + loopback origins: `loopback_address`, `loopback_host` and + `loopback_literal`. A literal in `127.0.0.0/8`, `::1` or the IPv4-mapped + form of `127.0.0.0/8` is loopback, and so is the exact name `localhost` + once the connection is pinned to loopback addresses + (`LoopbackHost::pinned_by`). A site that accepts the name must pin the + connection; a site that cannot pin uses `loopback_literal`. Bind sites keep + their own, stricter rule. The module is available with + `default-features = false`. - `ProblemBody`, the fixed value-free Registry Stack problem envelope with `type`, `title`, `status`, `detail`, `code`, and `traceId` members. - `response_trace_id` for exact-one canonical W3C v0 response correlation. diff --git a/crates/registry-platform-httpsec/src/loopback.rs b/crates/registry-platform-httpsec/src/loopback.rs index 9d5aaedf07..58aae8fa0b 100644 --- a/crates/registry-platform-httpsec/src/loopback.rs +++ b/crates/registry-platform-httpsec/src/loopback.rs @@ -1,4 +1,5 @@ -//! The one definition of "loopback" for outbound and bind decisions. +//! The one definition of "loopback" for outbound destinations and loopback origins. +//! Bind sites keep their own, stricter rule. //! //! A host is loopback when it is an address literal in `127.0.0.0/8`, `::1`, or an //! IPv4-mapped IPv6 form of an address in `127.0.0.0/8`, or when it is the exact @@ -6,7 +7,7 @@ //! caller has checked. `*.localhost`, `localhost.` and every other name are never //! loopback. -use std::net::IpAddr; +use std::net::{IpAddr, Ipv6Addr}; /// The one name that may stand for the loopback interface. const LOCALHOST: &str = "localhost"; @@ -43,6 +44,11 @@ impl LoopbackHost { /// Classify a URL host. `[::1]` and `::1` are both accepted. Returns `None` for every /// other host. +/// +/// `loopback_host(..).is_some()` treats the bare name `localhost` as loopback. A +/// site that accepts the name that way must also pin the connection to loopback +/// addresses, as [`LoopbackHost::pinned_by`] checks, or a hosts file or resolver +/// can send it off the machine. A site that cannot pin uses [`loopback_literal`]. #[must_use] pub fn loopback_host(host: &str) -> Option { if host.eq_ignore_ascii_case(LOCALHOST) { @@ -51,14 +57,17 @@ pub fn loopback_host(host: &str) -> Option { loopback_literal(host).map(LoopbackHost::Literal) } -/// The literal arm alone, for a site that cannot pin a name. +/// The literal arm alone, for a site that cannot pin a name. Brackets are +/// accepted around an IPv6 literal only, as in a URL host. #[must_use] pub fn loopback_literal(host: &str) -> Option { - let bare = host + let ip = match host .strip_prefix('[') .and_then(|rest| rest.strip_suffix(']')) - .unwrap_or(host); - let ip: IpAddr = bare.parse().ok()?; + { + Some(inner) => IpAddr::V6(inner.parse::().ok()?), + None => host.parse().ok()?, + }; loopback_address(ip).then_some(ip) } @@ -91,6 +100,9 @@ mod tests { "[::ffff:10.0.0.1]", "[::1", "::1]", + "[127.0.0.1]", + "[127.0.0.2]", + "[localhost]", "", ] { assert!( @@ -112,6 +124,11 @@ mod tests { ); assert!(loopback_literal("localhost").is_none()); assert!(loopback_literal("[::1]").is_some()); + assert!(loopback_literal("[::ffff:127.0.0.1]").is_some()); + assert!( + loopback_literal("[127.0.0.1]").is_none(), + "a bracketed IPv4 literal is not a URL host" + ); } #[test] diff --git a/crates/registry-platform-httpsec/src/server.rs b/crates/registry-platform-httpsec/src/server.rs index fa7b9e4e75..9fc730bbd2 100644 --- a/crates/registry-platform-httpsec/src/server.rs +++ b/crates/registry-platform-httpsec/src/server.rs @@ -103,6 +103,11 @@ fn parse_traceparent(value: &str) -> Option { }) } +// The request trace id is the one value `record_refusal!` takes from a request: +// it is a validated W3C trace id, so it carries no other caller text. +impl registry_platform_authcommon::__refusal_trace_id_seal::Sealed for TraceId {} +impl registry_platform_authcommon::RefusalTraceId for TraceId {} + fn fresh_span_id() -> String { let value = u128::from(Ulid::generate()); let span = u64::try_from(value & u128::from(u64::MAX)).unwrap_or(1); @@ -804,6 +809,29 @@ mod tests { assert!(TraceId::parse("not-a-trace").is_err()); } + #[test] + fn the_request_trace_id_is_the_one_a_refusal_line_takes() { + use registry_platform_authcommon::{ + record_refusal, FailedCheck, RefusalNote, RefusalRecorder, + }; + + // Caller text never becomes a trace id, so it cannot reach a refusal + // line through the macro's `trace_id` field. + assert!(TraceId::parse("canary-request-value-7f3a").is_err()); + + let recorder = RefusalRecorder::new("httpsec").unwrap(); + let trace = TraceContext::server_created(); + let note = RefusalNote::new(FailedCheck::Scope); + record_refusal!(recorder, note, trace_id = &trace.trace_id); + record_refusal!(recorder, note, trace_id = trace.trace_id.clone()); + record_refusal!( + recorder, + note, + trace_id = TraceId::parse("4bf92f3577b34da6a3ce929d0e0e4736").unwrap() + ); + assert_eq!(recorder.counter().get(&["scope"]), Some(3)); + } + #[test] fn version_zero_traceparent_rejects_non_lowercase_hex() { for value in [ diff --git a/crates/registry-platform-httputil/src/client/outbound.rs b/crates/registry-platform-httputil/src/client/outbound.rs index 4fc2239ed2..7952b00c8c 100644 --- a/crates/registry-platform-httputil/src/client/outbound.rs +++ b/crates/registry-platform-httputil/src/client/outbound.rs @@ -161,6 +161,7 @@ mod tests { "http://127.0.0.1/", "http://127.9.9.9:8080/", "http://[::1]/", + "http://[::ffff:127.0.0.1]/", "http://localhost:8080/", "http://LOCALHOST/", "https://example.org/", @@ -172,6 +173,7 @@ mod tests { "http://a.localhost/", "http://localhost./", "http://10.0.0.1/", + "http://[::ffff:10.0.0.1]/", "http://0.0.0.0/", "http://example.org/", "ftp://127.0.0.1/", diff --git a/crates/registry-platform-httputil/src/destination.rs b/crates/registry-platform-httputil/src/destination.rs index 4814825086..cca6736819 100644 --- a/crates/registry-platform-httputil/src/destination.rs +++ b/crates/registry-platform-httputil/src/destination.rs @@ -441,6 +441,8 @@ impl FixedDestinationPolicy { /// allocation. An origin id is canonical lowercase ASCII using alphanumeric /// characters with internal `.`, `_`, `:`, or `-` separators. Each CIDR /// must be wholly contained by RFC 1918, RFC 6598 CGNAT, or IPv6 ULA space. + /// A [`DestinationProfile::PrivateServiceHttp`] destination needs at least + /// one CIDR, since it sends only to addresses inside the listed ranges. pub fn new( origin_id: &str, origin: &str, @@ -559,6 +561,12 @@ impl FixedDestinationPolicy { #[cfg(any(test, feature = "test-support"))] DestinationProfile::PinnedLoopbackHttpsTest => {} } + // A private service hop admits only addresses inside the listed + // ranges, so with none it could never send. Refuse it here, at + // activation, rather than at the first send. + if profile == DestinationProfile::PrivateServiceHttp && allowed_private_cidrs.is_empty() { + return Err(DestinationPolicyError::PrivateServiceRequiresPrivateCidr); + } if dns_family == DestinationDnsFamily::Ipv4Only && allowed_private_cidrs @@ -1236,6 +1244,10 @@ pub enum DestinationPolicyError { ProductionRequiresHttps, #[error("private service destination requires HTTP")] PrivateServiceRequiresHttp, + #[error( + "private service destination requires at least one private CIDR; name the range that holds the service's addresses" + )] + PrivateServiceRequiresPrivateCidr, #[error("destination profile denies the localhost namespace")] LocalhostNamespaceDenied, #[error("loopback development destination requires HTTP")] @@ -5664,25 +5676,28 @@ mod tests { #[test] fn private_service_http_is_dns_pinned_to_private_address_space() { - let policy = DataDestinationPolicy::new( + let error = DataDestinationPolicy::new( "private-service", "http://registry-service:8080/", DestinationProfile::PrivateServiceHttp, &[], ) - .expect("private service destination validates"); - for address in ["10.89.0.4", "fd42::4"] { - assert_eq!( - classify(&policy, &[address]), - Err(DestinationSendError::PrivateAddressNotAllowed), - "an empty private range list admits no private address: {address}" - ); - } - for address in ["127.0.0.1", "169.254.169.254", "8.8.8.8", "::1"] { - assert!( - classify(&policy, &[address]).is_err(), - "private service accepted {address}" - ); + .expect_err("an empty private range list is refused at activation, not at the first send"); + assert_eq!( + error, + DestinationPolicyError::PrivateServiceRequiresPrivateCidr + ); + assert!(error.to_string().contains("private CIDR"), "{error}"); + for profile in [ + DestinationProfile::ProductionHttps, + DestinationProfile::LoopbackDevelopmentHttp, + ] { + let origin = match profile { + DestinationProfile::ProductionHttps => "https://registry.example/", + _ => "http://127.0.0.1:8080/", + }; + DataDestinationPolicy::new("destination", origin, profile, &[]) + .expect("a public or loopback destination needs no private range"); } let listed = DataDestinationPolicy::new( @@ -5693,6 +5708,17 @@ mod tests { ) .expect("listed private service destination validates"); assert_eq!(classify(&listed, &["10.0.0.5"]), Ok(())); + assert_eq!( + classify(&listed, &["fd42::4"]), + Err(DestinationSendError::PrivateAddressNotAllowed), + "a private address outside the listed ranges stays refused at send" + ); + for address in ["127.0.0.1", "8.8.8.8", "::1"] { + assert!( + classify(&listed, &[address]).is_err(), + "private service accepted {address}" + ); + } assert_eq!( classify(&listed, &["169.254.169.254"]), Err(DestinationSendError::CloudMetadataDenied), diff --git a/crates/registry-platform-httputil/src/lib.rs b/crates/registry-platform-httputil/src/lib.rs index 4345b57d28..10d0c02e10 100644 --- a/crates/registry-platform-httputil/src/lib.rs +++ b/crates/registry-platform-httputil/src/lib.rs @@ -177,7 +177,17 @@ impl OutboundClientBuilder { /// Fallibly build one hardened client with rustls, redirects and retries disabled, /// proxy environment variables ignored, and optional exact CA pinning. pub fn try_build(self) -> Result { - let mut builder = reqwest::Client::builder() + self.try_build_from(reqwest::Client::builder()) + } + + /// Apply every setting of [`Self::try_build`] to `builder`. Tests pass a + /// builder that carries their own resolver; every other caller goes + /// through [`Self::try_build`]. + fn try_build_from( + self, + builder: reqwest::ClientBuilder, + ) -> Result { + let mut builder = builder .timeout(self.timeout) .connect_timeout(self.connect_timeout) .redirect(reqwest::redirect::Policy::none()) @@ -1107,6 +1117,45 @@ mod tests { assert!(reaches(&client, &v6_only).await, "IPv6-only listener"); } + /// Answers every name, `localhost` included, with an address off this + /// machine, as a hosts-file override or a hostile resolver could. + struct OffHostResolver { + asked_for_localhost: std::sync::Arc, + } + + impl reqwest::dns::Resolve for OffHostResolver { + fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { + if name.as_str().eq_ignore_ascii_case(LOCALHOST_NAME) { + self.asked_for_localhost + .store(true, std::sync::atomic::Ordering::SeqCst); + } + let off_host: reqwest::dns::Addrs = + Box::new(std::iter::once(SocketAddr::from(([192, 0, 2, 1], 0)))); + Box::pin(std::future::ready(Ok(off_host))) + } + } + + #[tokio::test] + async fn the_localhost_pin_holds_against_a_resolver_that_answers_off_host() { + let url = serve_on("127.0.0.1:0").await; + let asked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let resolver = OffHostResolver { + asked_for_localhost: std::sync::Arc::clone(&asked), + }; + let client = OutboundClientBuilder::new() + .connect_timeout(Duration::from_millis(500)) + .try_build_from(reqwest::Client::builder().dns_resolver(std::sync::Arc::new(resolver))) + .expect("client"); + assert!( + reaches(&client, &url).await, + "localhost reaches the loopback listener" + ); + assert!( + !asked.load(std::sync::atomic::Ordering::SeqCst), + "the resolver is never asked for localhost" + ); + } + #[test] fn the_localhost_name_is_allowed_only_when_every_answer_is_loopback() { let name = ::url::Host::Domain("localhost"); diff --git a/crates/registry-platform-oidc/src/diagnostics.rs b/crates/registry-platform-oidc/src/diagnostics.rs index 840de87f99..2ce828f3cb 100644 --- a/crates/registry-platform-oidc/src/diagnostics.rs +++ b/crates/registry-platform-oidc/src/diagnostics.rs @@ -47,7 +47,9 @@ impl OidcError { /// Never format the underlying error to diagnose a public authentication failure. pub fn authentication_stage(&self) -> AuthenticationStage { match self { - Self::MalformedToken | Self::InvalidToken => AuthenticationStage::Header, + Self::MalformedToken | Self::InvalidToken | Self::SubjectMismatch => { + AuthenticationStage::Header + } Self::AlgorithmNotAllowed => AuthenticationStage::Algorithm, Self::TokenTypeNotAllowed => AuthenticationStage::TokenType, Self::MissingKid | Self::KidTooLong | Self::UnknownKid => AuthenticationStage::Key, @@ -87,6 +89,7 @@ impl OidcError { Self::SignatureInvalid => FailedCheck::TokenSignature, Self::IssuerMismatch { .. } => FailedCheck::TokenIssuer, Self::AudienceMismatch => FailedCheck::TokenAudience, + Self::SubjectMismatch => FailedCheck::TokenClaims, Self::TokenExpired | Self::TokenNotYetValid | Self::InvalidTimeClaims => { FailedCheck::TokenTime } @@ -201,8 +204,9 @@ mod tests { #[cfg(test)] mod failed_check_tests { - use crate::OidcError; + use crate::{OidcEndpoint, OidcError, StaticJwksError}; use registry_platform_authcommon::FailedCheck; + use registry_platform_httputil::{BoundedReadError, FetchUrlError}; #[test] fn issuer_mismatch_maps_without_the_issuers() { @@ -222,28 +226,66 @@ mod failed_check_tests { assert!(!OidcError::SignatureInvalid.is_key_source_unavailable()); } + /// One row per `OidcError` variant: the reviewable spec of the mapping. + /// A header the named key cannot serve is `AlgorithmNotAllowed`, a token + /// fault; `InvalidJwk` is reserved for a key the source should not have + /// published, a key-source fault. #[test] - fn every_simple_variant_maps_to_its_member() { + fn every_variant_maps_to_its_member() { + let transport = reqwest::Client::new() + .get("not a url") + .build() + .expect_err("an unparsable URL is a client error"); let table = [ + ( + OidcError::Transport(transport), + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::BoundedRead(BoundedReadError::LengthOverflow), + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::FetchUrl(FetchUrlError::MissingHost), + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::HttpStatus(503), + FailedCheck::KeySourceUnavailable, + ), + (OidcError::InvalidUrl, FailedCheck::KeySourceUnavailable), + (OidcError::Parse, FailedCheck::KeySourceUnavailable), + ( + OidcError::IssuerMismatch { + expected: String::new(), + actual: String::new(), + }, + FailedCheck::TokenIssuer, + ), (OidcError::MalformedToken, FailedCheck::CredentialMalformed), - (OidcError::InvalidToken, FailedCheck::CredentialMalformed), (OidcError::AlgorithmNotAllowed, FailedCheck::TokenAlgorithm), (OidcError::TokenTypeNotAllowed, FailedCheck::TokenType), (OidcError::MissingKid, FailedCheck::TokenKey), (OidcError::KidTooLong, FailedCheck::TokenKey), (OidcError::UnknownKid, FailedCheck::TokenKey), - (OidcError::SignatureInvalid, FailedCheck::TokenSignature), - (OidcError::AudienceMismatch, FailedCheck::TokenAudience), + (OidcError::InvalidJwk, FailedCheck::KeySourceUnavailable), + (OidcError::EmptyKeySet, FailedCheck::KeySourceUnavailable), + ( + OidcError::StaticKeySet(StaticJwksError::Empty), + FailedCheck::KeySourceUnavailable, + ), (OidcError::TokenExpired, FailedCheck::TokenTime), (OidcError::TokenNotYetValid, FailedCheck::TokenTime), + (OidcError::AudienceMismatch, FailedCheck::TokenAudience), + (OidcError::SubjectMismatch, FailedCheck::TokenClaims), + (OidcError::SignatureInvalid, FailedCheck::TokenSignature), + (OidcError::InvalidToken, FailedCheck::CredentialMalformed), (OidcError::InvalidTimeClaims, FailedCheck::TokenTime), (OidcError::ClientNotAllowed, FailedCheck::TokenClient), ( OidcError::AssertionIssuerNotAllowed, FailedCheck::TokenAssertionIssuer, ), - (OidcError::Parse, FailedCheck::KeySourceUnavailable), - (OidcError::InvalidJwk, FailedCheck::KeySourceUnavailable), (OidcError::MissingIssuer, FailedCheck::KeySourceUnavailable), ( OidcError::ConflictingEndpointConfiguration, @@ -253,9 +295,21 @@ mod failed_check_tests { OidcError::InsecureHttpRequiresOptIn, FailedCheck::KeySourceUnavailable, ), + ( + OidcError::EndpointRefused { + endpoint: OidcEndpoint::DeclaredJwks, + remedy: "a fixed remedy", + }, + FailedCheck::KeySourceUnavailable, + ), ]; for (error, expected) in table { assert_eq!(error.failed_check(), expected, "{error:?}"); + assert_eq!( + error.is_key_source_unavailable(), + expected == FailedCheck::KeySourceUnavailable, + "{error:?}" + ); } } } diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index 76520515f1..235ff26efe 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -472,9 +472,15 @@ impl fmt::Debug for JwksFetcher { /// A symmetric key, a private-key member or an unnamed key is refused here, /// at startup, rather than when a token first selects it. The rule on members /// is [`public_jwks_document`]. An OKP key passes that rule and is refused -/// here with [`OidcError::InvalidJwk`]. +/// here with [`StaticJwksError::OctetKeyPair`], which names its position. pub fn parse_static_jwks(bytes: &[u8]) -> Result { let document = public_jwks_document(bytes)?; + let okp = document["keys"] + .as_array() + .and_then(|keys| keys.iter().position(|key| key["kty"] == "OKP")); + if let Some(key) = okp { + return Err(StaticJwksError::OctetKeyPair { key }.into()); + } let jwks: JwkSet = serde_json::from_value(document).map_err(|_| OidcError::Parse)?; let all_asymmetric = jwks.keys.iter().all(|key| { matches!( @@ -948,14 +954,19 @@ fn validate_jwk(jwk: &Jwk) -> Result<(), OidcError> { Ok(()) } +/// Check that the key a token's `kid` names can serve the token's header +/// `alg`. A key the source should not publish stays [`OidcError::InvalidJwk`], +/// a key-source fault. A header the key cannot serve, including a `kid` that +/// names an encryption key, is [`OidcError::AlgorithmNotAllowed`]: the caller +/// chose that header, so it is a token fault. fn validate_jwk_for_header(jwk: &Jwk, header_alg: Algorithm) -> Result<(), OidcError> { validate_jwk(jwk)?; if jwk_family(jwk) != algorithm_family(header_alg) { - return Err(OidcError::InvalidJwk); + return Err(OidcError::AlgorithmNotAllowed); } if let Some(jwk_alg) = explicit_or_inferred_jwk_algorithm(jwk)? { if jwk_alg != header_alg { - return Err(OidcError::InvalidJwk); + return Err(OidcError::AlgorithmNotAllowed); } } Ok(()) @@ -1017,6 +1028,8 @@ fn explicit_or_inferred_jwk_algorithm(jwk: &Jwk) -> Result, Oi } } +/// A key whose declared `alg` is not a signing algorithm cannot verify any +/// token, so a header that names it fails as [`OidcError::AlgorithmNotAllowed`]. fn key_algorithm_to_jwt_algorithm(algorithm: KeyAlgorithm) -> Result { match algorithm { KeyAlgorithm::HS256 => Ok(Algorithm::HS256), @@ -1034,7 +1047,7 @@ fn key_algorithm_to_jwt_algorithm(algorithm: KeyAlgorithm) -> Result Err(OidcError::InvalidJwk), + | KeyAlgorithm::UNKNOWN_ALGORITHM => Err(OidcError::AlgorithmNotAllowed), } } @@ -1482,10 +1495,10 @@ impl TokenVerifier { return Err(OidcError::AudienceMismatch); } let Some(access_sub) = access_token.claims.sub.as_deref() else { - return Err(OidcError::InvalidToken); + return Err(OidcError::SubjectMismatch); }; if data.claims.sub.as_deref() != Some(access_sub) { - return Err(OidcError::InvalidToken); + return Err(OidcError::SubjectMismatch); } Ok(data.claims) } @@ -1729,20 +1742,48 @@ fn map_jwt_error( expected_issuer: &str, token: &str, ) -> OidcError { + let issuer_mismatch = || OidcError::IssuerMismatch { + expected: expected_issuer.to_string(), + actual: issuer_from_untrusted_payload(token).unwrap_or_default(), + }; match error.kind() { JwtErrorKind::ExpiredSignature => OidcError::TokenExpired, JwtErrorKind::ImmatureSignature => OidcError::TokenNotYetValid, - JwtErrorKind::InvalidIssuer => OidcError::IssuerMismatch { - expected: expected_issuer.to_string(), - actual: issuer_from_untrusted_payload(token).unwrap_or_default(), - }, + JwtErrorKind::InvalidIssuer => issuer_mismatch(), JwtErrorKind::InvalidAudience => OidcError::AudienceMismatch, - JwtErrorKind::MissingRequiredClaim(claim) if claim == "exp" => OidcError::InvalidTimeClaims, + JwtErrorKind::MissingRequiredClaim(claim) => match claim.as_str() { + "aud" => OidcError::AudienceMismatch, + "iss" => issuer_mismatch(), + "exp" | "nbf" => OidcError::InvalidTimeClaims, + _ => OidcError::InvalidToken, + }, + JwtErrorKind::InvalidClaimFormat(_) => OidcError::InvalidTimeClaims, + JwtErrorKind::Json(_) if time_claim_is_malformed(token) => OidcError::InvalidTimeClaims, JwtErrorKind::InvalidSignature => OidcError::SignatureInvalid, _ => OidcError::InvalidToken, } } +/// True when a time claim is present but is not a whole number of seconds +/// [`Claims`] can hold. [`decode`] reports such a claim as a JSON error, +/// after the signature has been verified. +fn time_claim_is_malformed(token: &str) -> bool { + let Some(payload) = token.split('.').nth(1) else { + return false; + }; + let Ok(decoded) = URL_SAFE_NO_PAD.decode(payload) else { + return false; + }; + let Ok(claims) = serde_json::from_slice::>(&decoded) else { + return false; + }; + ["exp", "nbf", "iat"].iter().any(|name| { + claims + .get(*name) + .is_some_and(|value| !value.is_null() && value.as_i64().is_none()) + }) +} + fn issuer_from_untrusted_payload(token: &str) -> Option { let payload = token.split('.').nth(1)?; let decoded = URL_SAFE_NO_PAD.decode(payload).ok()?; @@ -1799,6 +1840,10 @@ pub enum OidcError { TokenNotYetValid, #[error("token audience does not match")] AudienceMismatch, + /// A UserInfo response names another subject than the access token, or + /// the access token names none. + #[error("token subject does not match the access token")] + SubjectMismatch, #[error("token signature is invalid")] SignatureInvalid, #[error("token is invalid")] @@ -1835,10 +1880,12 @@ impl OidcEndpoint { #[cfg(test)] mod tests { use super::*; + use crate::static_jwks::tests::{keycloak_realm_jwks, KEYCLOAK_ENC_KID, KEYCLOAK_SIG_KID}; use axum::{http::StatusCode, response::IntoResponse, routing::get, Json, Router}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine; use jsonwebtoken::{encode, EncodingKey, Header}; + use registry_platform_authcommon::FailedCheck; use serde_json::json; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use tokio::net::TcpListener; @@ -2506,9 +2553,36 @@ mod tests { validate_jwk_for_header(&rsa, Algorithm::RS256).expect("matching alg accepts"); assert!(matches!( validate_jwk_for_header(&rsa, Algorithm::RS384), - Err(OidcError::InvalidJwk) + Err(OidcError::AlgorithmNotAllowed) + )); + assert!(matches!( + validate_jwk_for_header(&rsa, Algorithm::ES256), + Err(OidcError::AlgorithmNotAllowed) + )); + + let rsa_oaep: Jwk = serde_json::from_value(json!({ + "kty": "RSA", + "kid": "enc", + "alg": "RSA-OAEP", + "use": "enc", + "n": URL_SAFE_NO_PAD.encode(vec![0xff; 256]), + "e": "AQAB", + })) + .expect("RSA-OAEP JWK parses"); + assert!(matches!( + validate_jwk_for_header(&rsa_oaep, Algorithm::RS256), + Err(OidcError::AlgorithmNotAllowed) )); + let short = rsa_jwk_with_modulus_bytes("short", 128); + assert!( + matches!( + validate_jwk_for_header(&short, Algorithm::RS256), + Err(OidcError::InvalidJwk) + ), + "a key the source should not publish stays a key-source fault" + ); + let oct: Jwk = serde_json::from_value(json!({ "kty": "oct", "kid": "oct", @@ -2519,7 +2593,7 @@ mod tests { validate_jwk_for_header(&oct, Algorithm::HS256).expect("matching alg accepts"); assert!(matches!( validate_jwk_for_header(&oct, Algorithm::EdDSA), - Err(OidcError::InvalidJwk) + Err(OidcError::AlgorithmNotAllowed) )); let p256: Jwk = serde_json::from_value(json!({ @@ -2532,10 +2606,159 @@ mod tests { validate_jwk_for_header(&p256, Algorithm::ES256).expect("matching curve accepts"); assert!(matches!( validate_jwk_for_header(&p256, Algorithm::ES384), - Err(OidcError::InvalidJwk) + Err(OidcError::AlgorithmNotAllowed) )); } + fn keycloak_realm_verifier() -> TokenVerifier { + let keys = parse_static_jwks(&keycloak_realm_jwks()).expect("a realm key set loads"); + TokenVerifier::new( + TokenVerifierConfig::access_token_profile( + "https://keycloak.example/realms/registry", + vec!["registry-api".to_string()], + vec![Algorithm::RS256, Algorithm::ES256], + vec!["at+jwt".to_string()], + ), + Arc::new(JwksFetcher::new_static(keys, jwks_test_config())), + ) + } + + #[tokio::test] + async fn a_header_the_named_key_cannot_serve_is_a_token_fault() { + let verifier = keycloak_realm_verifier(); + let claims = json!({ + "iss": "https://keycloak.example/realms/registry", + "aud": "registry-api", + "sub": "subject-1", + "exp": 4_102_444_800_i64, + }); + for (reason, alg, kid) in [ + ( + "an ES256 header naming the RSA signing key", + "ES256", + KEYCLOAK_SIG_KID, + ), + ( + "an RS256 header naming the RSA-OAEP encryption key", + "RS256", + KEYCLOAK_ENC_KID, + ), + ] { + let header = json!({"alg": alg, "typ": "at+jwt", "kid": kid}); + let token = unsigned_token(header, claims.clone()); + let error = verifier.verify(&token).await.expect_err(reason); + assert_eq!( + error.failed_check(), + FailedCheck::TokenAlgorithm, + "{reason}: {error:?}" + ); + assert!(!error.is_key_source_unavailable(), "{reason}"); + assert_eq!( + error.authentication_stage().label(), + "algorithm", + "{reason}" + ); + } + + let header = json!({"alg": "RS256", "typ": "at+jwt", "kid": KEYCLOAK_SIG_KID}); + let error = verifier + .verify(&unsigned_token(header, claims)) + .await + .expect_err("an unsigned token is refused"); + assert!( + matches!(error, OidcError::SignatureInvalid), + "the signing key reaches the signature check: {error:?}" + ); + } + + fn signed_hs256_value(kid: &str, claims: &Value, secret: &[u8]) -> String { + let mut header = Header::new(Algorithm::HS256); + header.kid = Some(kid.to_string()); + header.typ = Some("at+jwt".to_string()); + encode(&header, claims, &EncodingKey::from_secret(secret)).expect("sign HS256 test token") + } + + #[tokio::test] + async fn a_missing_or_malformed_claim_names_the_check_it_failed() { + let secret = b"registry-platform-oidc-claim-check-secret"; + let verifier = hs256_test_verifier( + "https://issuer.example", + vec!["registry-api".to_string()], + Vec::new(), + "kid", + secret, + ) + .await; + let base = json!({ + "iss": "https://issuer.example", + "aud": "registry-api", + "sub": "subject-1", + "exp": 4_102_444_800_i64, + }); + let without = |name: &str| { + let mut claims = base.clone(); + claims + .as_object_mut() + .expect("claims are an object") + .remove(name); + claims + }; + let with = |name: &str, value: Value| { + let mut claims = base.clone(); + claims[name] = value; + claims + }; + verifier + .verify(&signed_hs256_value("kid", &base, secret)) + .await + .expect("the base token verifies"); + + for (reason, claims, expected) in [ + ("no aud", without("aud"), FailedCheck::TokenAudience), + ("no iss", without("iss"), FailedCheck::TokenIssuer), + ("no exp", without("exp"), FailedCheck::TokenTime), + ( + "a string exp", + with("exp", json!("soon")), + FailedCheck::TokenTime, + ), + ( + "a fractional exp", + with("exp", json!(4_102_444_800.5_f64)), + FailedCheck::TokenTime, + ), + ( + "a negative exp", + with("exp", json!(-1)), + FailedCheck::TokenTime, + ), + ( + "a string nbf", + with("nbf", json!("now")), + FailedCheck::TokenTime, + ), + ( + "a negative nbf", + with("nbf", json!(-1)), + FailedCheck::TokenTime, + ), + ( + "a string iat", + with("iat", json!("now")), + FailedCheck::TokenTime, + ), + ( + "a numeric sub", + with("sub", json!(7)), + FailedCheck::CredentialMalformed, + ), + ] { + let token = signed_hs256_value("kid", &claims, secret); + let error = verifier.verify(&token).await.expect_err(reason); + assert_eq!(error.failed_check(), expected, "{reason}: {error:?}"); + } + } + fn verifier_for_header_tests() -> TokenVerifier { let fetcher = Arc::new(JwksFetcher::new( "http://127.0.0.1/jwks".to_string(), @@ -3293,7 +3516,13 @@ mod tests { .extra .insert("scope".to_string(), json!("record:read")); // Preserve the selected claim's explicit null; the generic test - // signer omits nulls to represent absent registered claims. + // signer omits nulls to represent absent registered claims. A + // null `nbf` is itself a malformed time claim, so it is omitted + // here and the refusal comes from the selected claim. + let mut claims = serde_json::to_value(claims).expect("claims serialize"); + if let Value::Object(map) = &mut claims { + map.retain(|name, value| name == "permissions" || !value.is_null()); + } let mut header = Header::new(Algorithm::HS256); header.kid = Some("kid".to_string()); header.typ = Some("at+jwt".to_string()); @@ -3647,17 +3876,31 @@ mod tests { secret, Some("JWT"), ); - assert!(matches!( - verifier - .verify_userinfo_jwt_with_claims_policy( - &wrong_subject, - &access, - &accepted_issuers, - &accepted_audiences, - ) - .await, - Err(OidcError::InvalidToken) - )); + let error = verifier + .verify_userinfo_jwt_with_claims_policy( + &wrong_subject, + &access, + &accepted_issuers, + &accepted_audiences, + ) + .await + .expect_err("a UserInfo response about another subject is refused"); + assert!(matches!(error, OidcError::SubjectMismatch), "{error:?}"); + assert_eq!(error.failed_check(), FailedCheck::TokenClaims, "{error:?}"); + + let mut access_without_subject = access.clone(); + access_without_subject.claims.sub = None; + let error = verifier + .verify_userinfo_jwt_with_claims_policy( + &valid, + &access_without_subject, + &accepted_issuers, + &accepted_audiences, + ) + .await + .expect_err("an access token without a subject matches no UserInfo response"); + assert!(matches!(error, OidcError::SubjectMismatch), "{error:?}"); + assert_eq!(error.failed_check(), FailedCheck::TokenClaims, "{error:?}"); } #[tokio::test] @@ -4658,7 +4901,7 @@ mod tests { ( "an OKP key", br#"{"keys":[{"kty":"OKP","kid":"one","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]}"#, - "jwk", + "static", ), ] { let error = parse_static_jwks(invalid).expect_err(reason); @@ -4670,4 +4913,23 @@ mod tests { assert_eq!(kind, expected, "{reason}"); } } + + #[test] + fn an_okp_key_is_refused_with_its_position_and_the_remedy() { + let error = parse_static_jwks( + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"OKP","kid":"two","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]}"#, + ) + .expect_err("an OKP key is refused"); + assert!( + matches!( + error, + OidcError::StaticKeySet(StaticJwksError::OctetKeyPair { key: 1 }) + ), + "{error:?}" + ); + let text = error.to_string(); + assert!(text.contains("key 1 "), "{text}"); + assert!(text.contains("use an RSA or EC key"), "{text}"); + assert!(error.is_key_source_unavailable()); + } } diff --git a/crates/registry-platform-oidc/src/static_jwks.rs b/crates/registry-platform-oidc/src/static_jwks.rs index d05d8f8b2a..0efef00e7b 100644 --- a/crates/registry-platform-oidc/src/static_jwks.rs +++ b/crates/registry-platform-oidc/src/static_jwks.rs @@ -1,9 +1,11 @@ //! Public-key rule for operator-pinned JSON Web Key Sets. //! //! One rule for every product that loads a static key set. Members this -//! module does not name are ignored, as RFC 7517 sections 4 and 5 require. -//! A refusal names the position of the key and the rule it broke, never a -//! `kid` or a member value. +//! module does not name are ignored, as RFC 7517 sections 4 and 5 require, +//! apart from the strict JSON rule that applies to the whole document: no +//! repeated member name, and no integer a binary64 number cannot hold +//! exactly. A refusal names the position of the key and the rule it broke, +//! never a `kid` or a member value. use std::collections::BTreeSet; @@ -14,7 +16,7 @@ use serde_json::Value; #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] pub enum StaticJwksError { - #[error("the document is not JSON, or repeats a member name")] + #[error("the document is not JSON, repeats a member name, or holds an integer that a 64-bit floating-point number cannot represent exactly")] NotJson, #[error("the document is not a JSON Web Key Set: it needs a top-level \"keys\" array")] NotAKeySet, @@ -34,11 +36,16 @@ pub enum StaticJwksError { MissingKeyId { key: usize }, #[error("key {key} repeats the \"kid\" of an earlier key; give every key its own \"kid\"")] RepeatedKeyId { key: usize }, + #[error("key {key} is an OKP key (\"kty\": \"OKP\"), which the token verifier does not load; use an RSA or EC key")] + OctetKeyPair { key: usize }, } /// Check that `bytes` is a JSON Web Key Set that holds public keys only. -/// Returns the parsed document. Members this function does not name are not -/// inspected. The caller bounds the size of `bytes`. +/// Returns the parsed document. Apart from the strict JSON rule (no repeated +/// member name, no integer a binary64 number cannot hold exactly, anywhere in +/// the document), members this function does not name are not inspected. An +/// OKP key passes here; [`crate::parse_static_jwks`] refuses it for the token +/// verifier. The caller bounds the size of `bytes`. pub fn public_jwks_document(bytes: &[u8]) -> Result { let document = parse_json_strict(bytes).map_err(|_| StaticJwksError::NotJson)?; let keys = document @@ -80,13 +87,65 @@ pub fn public_jwks_document(bytes: &[u8]) -> Result { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; + use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; + use base64::Engine; + use jsonwebtoken::jwk::{KeyAlgorithm, PublicKeyUse}; use registry_platform_crypto::PRIVATE_JWK_MEMBERS; use serde_json::json; const RSA: &str = r#"{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}"#; + /// The `kid` of the RS256 signing key in [`keycloak_realm_jwks`]. + pub(crate) const KEYCLOAK_SIG_KID: &str = "kXbJ0QJ3Yx3qhJpU0rT9d8nqk1Z6m2Vw4sFhL7cE5aA"; + /// The `kid` of the RSA-OAEP encryption key in [`keycloak_realm_jwks`]. + pub(crate) const KEYCLOAK_ENC_KID: &str = "Rz8tYp4WmQ1nV6bH2cL9xK3fJ7sD0gA5eU8iO2wN4qM"; + + /// A key set in the shape a Keycloak realm publishes at + /// `/realms//protocol/openid-connect/certs`: an RSA-OAEP `enc` key + /// listed before the RS256 `sig` key, each with a 2048-bit modulus, a + /// one-certificate `x5c` chain of a self-signed realm certificate's length, + /// `x5t` and `x5t#S256`. Every value is synthetic: the moduli are not real + /// keys and the certificates are filler bytes behind a DER sequence header. + pub(crate) fn keycloak_realm_jwks() -> Vec { + fn filler(seed: u8, len: usize) -> Vec { + (0..len) + .map(|index| (index as u8).wrapping_mul(167).wrapping_add(seed)) + .collect() + } + fn modulus(seed: u8) -> String { + let mut bytes = filler(seed, 256); + bytes[0] |= 0x80; + bytes[255] |= 0x01; + URL_SAFE_NO_PAD.encode(bytes) + } + fn certificate(seed: u8) -> String { + let mut der = vec![0x30, 0x82, 0x02, 0xa9]; + der.extend(filler(seed, 0x02a9)); + STANDARD.encode(der) + } + fn key(kid: &str, alg: &str, key_use: &str, seed: u8) -> Value { + json!({ + "kid": kid, + "kty": "RSA", + "alg": alg, + "use": key_use, + "n": modulus(seed), + "e": "AQAB", + "x5c": [certificate(seed)], + "x5t": URL_SAFE_NO_PAD.encode(filler(seed, 20)), + "x5t#S256": URL_SAFE_NO_PAD.encode(filler(seed, 32)), + }) + } + json!({"keys": [ + key(KEYCLOAK_ENC_KID, "RSA-OAEP", "enc", 0x5a), + key(KEYCLOAK_SIG_KID, "RS256", "sig", 0xa5), + ]}) + .to_string() + .into_bytes() + } + fn set(keys: &str) -> Vec { format!(r#"{{"keys":[{keys}]}}"#).into_bytes() } @@ -104,10 +163,30 @@ mod tests { } #[test] - fn a_keycloak_shaped_set_loads() { - let sig = r#"{"kid":"sig","kty":"RSA","alg":"RS256","use":"sig","n":"AQAB","e":"AQAB","x5c":["MIIC"],"x5t":"aa","x5t#S256":"bb"}"#; - let enc = r#"{"kid":"enc","kty":"RSA","alg":"RSA-OAEP","use":"enc","n":"AQAB","e":"AQAB","x5c":["MIIC"],"x5t":"aa","x5t#S256":"bb"}"#; - public_jwks_document(&set(&format!("{sig},{enc}"))).expect("loads"); + fn a_keycloak_realm_set_loads_through_the_verifier_parser() { + let bytes = keycloak_realm_jwks(); + let keys = crate::parse_static_jwks(&bytes).expect("a realm key set loads"); + assert_eq!(keys.keys.len(), 2); + let sig = keys.find(KEYCLOAK_SIG_KID).expect("the signing key loads"); + assert_eq!(sig.common.public_key_use, Some(PublicKeyUse::Signature)); + assert_eq!(sig.common.key_algorithm, Some(KeyAlgorithm::RS256)); + let chain = sig.common.x509_chain.as_deref().expect("x5c is kept"); + assert!(chain[0].len() > 900, "the certificate has a realm length"); + let enc = keys + .find(KEYCLOAK_ENC_KID) + .expect("the encryption key loads"); + assert_eq!(enc.common.public_key_use, Some(PublicKeyUse::Encryption)); + assert_eq!(enc.common.key_algorithm, Some(KeyAlgorithm::RSA_OAEP)); + } + + #[test] + fn an_inexact_integer_anywhere_is_refused_and_the_text_says_so() { + let bytes = format!(r#"{{"keys":[{RSA}],"serial":9007199254740993}}"#); + let error = refusal(bytes.as_bytes()); + assert_eq!(error, StaticJwksError::NotJson); + assert!(error.to_string().contains("integer"), "{error}"); + public_jwks_document(format!(r#"{{"keys":[{RSA}],"serial":9007199254740992}}"#).as_bytes()) + .expect("an integer binary64 holds exactly is kept"); } #[test] diff --git a/products/platform/AGENTS.md b/products/platform/AGENTS.md index d058f74514..a6c1a44c34 100644 --- a/products/platform/AGENTS.md +++ b/products/platform/AGENTS.md @@ -37,7 +37,8 @@ Preserve these shared boundaries: `#[derive(Debug)]` is easy to miss in review. - Security logs use stable, low-cardinality field names (`request_id`, `principal_id_hash`, `auth_mode`, `issuer`, `client_id`, `azp`, `scope`, - `policy`, `decision`, `audit_envelope_id`, `error_code`) and never include + `policy`, `decision`, `audit_envelope_id`, `error_code`, `failed_check`, + `suppressed`, `trace_id`) and never include bearer tokens, raw API keys, private key material, full SD-JWTs, or unredacted subject identifiers. - Audit primitives provide minimized, fail-closed records with keyed diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 0b47a39595..5bacd85ada 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -13,7 +13,65 @@ refused. Members the rule does not name (`ext`, `x5c`, `x5t`, `x5u` and others) are ignored. A refusal is `OidcError::StaticKeySet` and names the key position and the rule, never a `kid` or a value. The member list is - `registry_platform_crypto::PRIVATE_JWK_MEMBERS`. + `registry_platform_crypto::PRIVATE_JWK_MEMBERS`. The whole document also + follows the strict JSON rule: an integer that a 64-bit floating-point + number cannot hold exactly is refused as `StaticJwksError::NotJson`. + `parse_static_jwks` refuses an OKP key with + `StaticJwksError::OctetKeyPair`, which names the key position and says to + use an RSA or EC key. + +- One definition of loopback, `registry_platform_httpsec::loopback` (also + `registry_platform_httputil::loopback`), for outbound destinations and + loopback origins. A host is loopback when it is an address literal in + `127.0.0.0/8`, `::1` or an IPv4-mapped form of `127.0.0.0/8`, or the exact + name `localhost` with the connection pinned to loopback addresses. + `*.localhost`, `localhost.` and a bracketed IPv4 literal such as + `[127.0.0.1]` are never loopback. Sites that use it accept more literal + spellings than before, for example `127.0.0.2` and `[::ffff:127.0.0.1]`. + +- Every client built by `OutboundClientBuilder` resolves the name + `localhost` to `127.0.0.1` and `::1` itself, so no resolver is asked for + it. A host whose resolver or hosts file maps `localhost` elsewhere is no + longer followed. + +- BREAKING: a `PrivateServiceHttp` fixed destination needs at least one + private CIDR. In 0.48.0 an empty list admitted any eligible private + address. It is now refused when the destination is frozen, with + `DestinationPolicyError::PrivateServiceRequiresPrivateCidr`, so the + operator learns it at activation instead of at the first send. Name the + range that holds the service's addresses. `ProductionHttps` and loopback + destinations still take an empty list. + +- `registry-platform-hooks` gives a receiver that names no window of its own + a default one: `DEFAULT_DELIVERY_SKEW`, 300 seconds either side of the + receiver clock, through `DeliveryFreshness::default_at`. + +- `registry_platform_authcommon::FailedCheck` is the closed set of checks a + request can fail, with a stable kebab-case label for each. It is + operator-side only and is never written to a response. Behind the + `refusal-recorder` feature, `RefusalRecorder` counts every refusal in + `_request_refusals_total{check}` and admits at most five log lines + per check per minute, and `record_refusal!` writes the line with + `failed_check`, `suppressed`, an optional code-defined `remedy` and an + optional `trace_id`, which must be a `RefusalTraceId`. The request's + `registry_platform_httpsec::TraceId` implements it under httpsec's `server` + feature, and authcommon does not depend on httpsec. Alert on the counter, + not on the log line. + +- A token whose header `alg` does not fit the key its `kid` names, or whose + `kid` names an encryption key such as an RSA-OAEP `use: enc` key, now fails + as `OidcError::AlgorithmNotAllowed` (`token-algorithm`) instead of + `OidcError::InvalidJwk` (`key-source-unavailable`). Products that answer a + key-source failure with 503 answer such a token with their 401 instead. + `InvalidJwk` stays a key-source failure for a key the source should not + publish. + +- `OidcError` names the claim a token failed: a missing `aud` is + `AudienceMismatch`, a missing `iss` is `IssuerMismatch`, and a malformed + `exp`, `nbf` or `iat` is `InvalidTimeClaims`, as a missing `exp` already + was. A UserInfo response about another subject than the access token is + the new `OidcError::SubjectMismatch` (`token-claims`). Each of these was + `InvalidToken` (`credential-malformed`) before. ## 0.48.0 - 2026-11-23 From da6b39c213dbf271c76d25a2a2a3861c054e6087 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:02:16 +0100 Subject: [PATCH 022/136] feat(breg): add bregctl provision for roles, schemas and the database The runtime file's two database URLs name the roles, the database and both passwords; with --package the command also plans the PostGIS steps a spatial package needs. It reads the managed schemas, the PostGIS schema and the PostGIS floor from registry-breg, so the command cannot drift from what apply and the runtime check. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-breg/src/generated_ddl.rs | 3 +- crates/registry-breg/src/postgres/catalog.rs | 4 +- crates/registry-breg/src/postgres/mod.rs | 4 +- crates/registry-breg/src/postgres/roles.rs | 6 +- crates/registry-breg/src/runtime_config.rs | 12 + crates/registry-bregctl/Cargo.toml | 12 +- crates/registry-bregctl/src/lib.rs | 38 ++ crates/registry-bregctl/src/provision.rs | 131 +++++ .../registry-bregctl/tests/provision_cli.rs | 230 ++++++++ .../tests/provision_postgres.rs | 522 ++++++++++++++++++ docs/site/src/content/docs/operate/breg.mdx | 202 ++++--- products/breg/AGENTS.md | 6 + 13 files changed, 1087 insertions(+), 84 deletions(-) create mode 100644 crates/registry-bregctl/src/provision.rs create mode 100644 crates/registry-bregctl/tests/provision_cli.rs create mode 100644 crates/registry-bregctl/tests/provision_postgres.rs diff --git a/Cargo.lock b/Cargo.lock index ab21645037..f28870e4ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6414,6 +6414,7 @@ dependencies = [ "registry-platform-hooks", "registry-platform-httpsec", "registry-platform-httputil", + "registry-platform-provision", "registry-platform-testing", "registry-platform-yaml", "registry-rstack-dev", diff --git a/crates/registry-breg/src/generated_ddl.rs b/crates/registry-breg/src/generated_ddl.rs index 40efe47493..f1b5ac18c3 100644 --- a/crates/registry-breg/src/generated_ddl.rs +++ b/crates/registry-breg/src/generated_ddl.rs @@ -27,7 +27,8 @@ use crate::physical_names::{ const RECORD_ID_COLUMN: &str = "record_id"; const GENERATED_TEXT_COLLATION: &str = "pg_catalog.pg_c_utf8"; pub(crate) const REFERENCE_LIFECYCLE_COLUMN: &str = "record_reference_lifecycle"; -pub(crate) const POSTGIS_EXTENSION_SCHEMA: &str = "registry_spatial_ext"; +/// The schema the generated spatial SQL reads PostGIS from. +pub const POSTGIS_EXTENSION_SCHEMA: &str = "registry_spatial_ext"; pub(crate) const SPATIAL_BBOX_FUNCTION_NAME: &str = "spatial_bbox_geometry"; pub(crate) const SPATIAL_POLYGON_CONTRACT_FUNCTION_NAME: &str = "valid_crs84_polygon"; const SPATIAL_POLYGON_CONTRACT_ARGUMENTS: &str = diff --git a/crates/registry-breg/src/postgres/catalog.rs b/crates/registry-breg/src/postgres/catalog.rs index 58c822a535..147f822d83 100644 --- a/crates/registry-breg/src/postgres/catalog.rs +++ b/crates/registry-breg/src/postgres/catalog.rs @@ -22,7 +22,9 @@ use super::{ RuntimeRevoke, SqlIdentifier, }; -pub(super) const MANAGED_SCHEMAS: &[&str] = &[ +/// The schemas a package creates its tables, functions and policies in. The +/// migration role owns them. +pub const MANAGED_SCHEMAS: &[&str] = &[ "registry_internal", "registry_data", "registry_source", diff --git a/crates/registry-breg/src/postgres/mod.rs b/crates/registry-breg/src/postgres/mod.rs index 6d946e771e..dad73109de 100644 --- a/crates/registry-breg/src/postgres/mod.rs +++ b/crates/registry-breg/src/postgres/mod.rs @@ -36,7 +36,7 @@ pub use baseline::{ }; pub use catalog::{ catalog_drift_objects, managed_schema_fingerprint, verify_catalog_identity_for_catalog, - CatalogIdentity, ExpectedManagedCatalog, ExpectedRegistryIdentity, + CatalogIdentity, ExpectedManagedCatalog, ExpectedRegistryIdentity, MANAGED_SCHEMAS, }; #[cfg(feature = "postgres-test")] #[doc(hidden)] @@ -226,7 +226,7 @@ pub fn strong_record_etag_for_test( pub use roles::{ provision_managed_schemas, provision_postgis_prerequisites, provision_spatial_bbox_role, spatial_bbox_role, verify_btree_gist, verify_migration_role, verify_postgis, - RuntimeWriteAuthority, SqlIdentifier, + RuntimeWriteAuthority, SqlIdentifier, MIN_POSTGIS_MAJOR, MIN_POSTGIS_MINOR, }; pub(crate) use schema::compiled_pattern_field; pub use schema::install_compiled_schema; diff --git a/crates/registry-breg/src/postgres/roles.rs b/crates/registry-breg/src/postgres/roles.rs index 527e50d513..d64b948a38 100644 --- a/crates/registry-breg/src/postgres/roles.rs +++ b/crates/registry-breg/src/postgres/roles.rs @@ -12,8 +12,10 @@ use super::catalog::MANAGED_SCHEMAS; use super::schema::verify_postgres_version; use super::{PostgresKernelError, Result}; -const MIN_POSTGIS_MAJOR: u32 = 3; -const MIN_POSTGIS_MINOR: u32 = 5; +/// The major version of the oldest PostGIS the runtime accepts. +pub const MIN_POSTGIS_MAJOR: u32 = 3; +/// The minor version of the oldest PostGIS the runtime accepts. +pub const MIN_POSTGIS_MINOR: u32 = 5; /// A validated PostgreSQL identifier used only for governed provisioning. #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index c48ee1951d..21537ce20f 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -2059,6 +2059,18 @@ impl DatabaseConfig { pub fn ca_bundle_ref(&self) -> Option<&SecretReference> { self.ca_bundle_ref.as_ref() } + + /// The secret reference to the runtime role's PostgreSQL URL, which + /// `bregctl provision` reads for the role, database and password. + pub fn runtime_url_ref(&self) -> &SecretReference { + &self.runtime_url_ref + } + + /// The secret reference to the migration role's PostgreSQL URL, which + /// `bregctl provision` reads for the role, database and password. + pub fn migration_url_ref(&self) -> &SecretReference { + &self.migration_url_ref + } } impl fmt::Debug for DatabaseConfig { diff --git a/crates/registry-bregctl/Cargo.toml b/crates/registry-bregctl/Cargo.toml index d71fceb5d3..f1b2c8bd3d 100644 --- a/crates/registry-bregctl/Cargo.toml +++ b/crates/registry-bregctl/Cargo.toml @@ -21,6 +21,11 @@ required-features = ["schema"] name = "wasm_test_lifecycle" required-features = ["wasm"] +[[test]] +name = "provision_postgres" +path = "tests/provision_postgres.rs" +required-features = ["postgres-test"] + [lints] workspace = true @@ -29,6 +34,9 @@ default = ["wasm"] # Forwarded so a `wasm`-feature build of the compiler can also run through # bregctl; bregctl itself adds no WASM surface of its own. wasm = ["registry-breg/wasm"] +# Builds the PostgreSQL provisioning proof, which needs a TLS server named by +# `PROVISION_TEST_DATABASE_URL` and `PROVISION_TEST_DATABASE_CA`. +postgres-test = [] # Derives the JSON Schemas of the tool files bregctl reads, for the # `tool-schema` generator and its drift check. schema = [ @@ -58,6 +66,7 @@ registry-platform-config.workspace = true registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-platform-hooks.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-httputil.workspace = true registry-platform-httpsec = { workspace = true, default-features = false } registry-thunderid-tooling = { workspace = true, features = ["session"] } @@ -88,7 +97,8 @@ url.workspace = true [dev-dependencies] registry-breg.workspace = true -registry-platform-testing = { workspace = true, features = ["test-utils"] } +registry-platform-provision = { workspace = true, features = ["test-support"] } +registry-platform-testing = { workspace = true, features = ["test-utils", "test-authorization-server"] } rustls.workspace = true tokio-postgres.workspace = true tokio-postgres-rustls.workspace = true diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 227251dd71..d4f359fdb7 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -63,6 +63,7 @@ mod module_lock_patch; mod package_inspection; mod package_lifecycle; mod proposal_retention; +mod provision; mod reconcile_lifecycle; mod report; mod review_recovery; @@ -252,6 +253,14 @@ enum Command { /// Status reads as the migration role in one read-only transaction and takes no apply lock, /// so it answers while an apply runs. Status(StatusArgs), + /// Create the PostgreSQL roles, database and schemas a Registry needs, from its runtime file. + /// + /// The runtime file's two database URLs name both roles, the database and both passwords. + /// The administrator URL comes from a file or an environment variable, never from the command + /// line. The command grants the runtime role CONNECT and nothing else: apply grants the rest. + /// With --package, a package that needs PostGIS also gets its schema, extension and + /// bounding-box role, which CREATE EXTENSION postgis needs a superuser for. + Provision(ProvisionCommand), /// Inspect and operate native Record timers through bounded audited commands. Timer(timer_operator_lifecycle::TimerArgs), /// Verify configured startup dependencies without binding a listener. @@ -894,6 +903,16 @@ struct PlanArgs { expected_digest: Option, } +#[derive(Debug, Args)] +struct ProvisionCommand { + #[command(flatten)] + shared: registry_platform_provision::ProvisionArgs, + + /// Absolute target package directory; a package that needs PostGIS adds the PostGIS steps. + #[arg(long, value_name = "ABSOLUTE_DIRECTORY")] + package: Option, +} + #[derive(Debug, Args)] struct StatusArgs { /// Runtime configuration file. @@ -3069,6 +3088,7 @@ where Err(refusal) => write_refusal(&refusal, format, stdout, stderr), }; } + Command::Provision(args) => return provision(&args, format), Command::Status(args) => { return match status(&args) { Ok(report) => write_status_success(&report, format, stdout, stderr), @@ -6475,6 +6495,23 @@ fn apply(args: &ApplyArgs) -> Result { }) } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: &ProvisionCommand, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "bregctl", + registry_platform_buildinfo::DISPLAY_VERSION, + &args.shared, + shared, + |runtime_config| provision::load(runtime_config, args.package.as_deref()), + ) +} + fn plan(args: &PlanArgs) -> Result { let outcome = apply_lifecycle::plan(PlanLifecycleRequest { runtime_config: &args.runtime_config, @@ -17176,6 +17213,7 @@ mod tests { "apply", "plan", "status", + "provision", "timer", "doctor", "verify", diff --git a/crates/registry-bregctl/src/provision.rs b/crates/registry-bregctl/src/provision.rs new file mode 100644 index 0000000000..ad7783ffde --- /dev/null +++ b/crates/registry-bregctl/src/provision.rs @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `bregctl provision`: the shared command over the Registry runtime file. +//! The file's two database URLs name the roles, the database and both +//! passwords, so nothing is written twice. With `--package` the command also +//! plans the PostGIS steps a spatial package needs. + +use std::path::Path; + +use registry_breg::generated_ddl::POSTGIS_EXTENSION_SCHEMA; +use registry_breg::package::load_package; +use registry_breg::postgres::{ + spatial_bbox_role, MANAGED_SCHEMAS, MIN_POSTGIS_MAJOR, MIN_POSTGIS_MINOR, +}; +use registry_breg::runtime_config::{ + load_runtime_config, RuntimeConfig, RuntimeConfigError, RUNTIME_CONFIG_KIND, +}; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout, Spatial}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(RUNTIME_CONFIG_KIND.to_owned()); + Box::new(diagnostic) +} + +fn runtime_file_refused(file: &Path, error: &RuntimeConfigError) -> Box { + match error.diagnostics(Some(file)).into_iter().next() { + Some(diagnostic) => Box::new(diagnostic), + None => refused( + "config.refused", + "", + error.to_string(), + "Correct the runtime file, then run provision again.", + ), + } +} + +/// The database a package needs from the server beyond the managed schemas: +/// PostGIS and the bounding-box role when the package stores polygons or +/// answers bounding-box queries. The role is named after the runtime role, as +/// the Registry runtime and `rstack dev` name it. +fn spatial(config: &RuntimeConfig, package: &Path) -> Result, Box> { + let verified = load_package(package, &config.package_load_context()).map_err(|error| { + refused( + "config.refused", + "arguments", + format!("the --package directory could not be loaded: {error}"), + "Pass --package as a package that bregctl package built, or run provision without it.", + ) + })?; + Ok(verified.registry().ddl().requires_postgis.then(|| Spatial { + schema: POSTGIS_EXTENSION_SCHEMA.to_owned(), + bbox_role: spatial_bbox_role(config.database().roles().runtime()) + .as_str() + .to_owned(), + minimum_postgis: (MIN_POSTGIS_MAJOR, MIN_POSTGIS_MINOR), + })) +} + +/// Reads the runtime file exactly as `apply` does and resolves the two +/// database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path, package: Option<&Path>) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be resolved against the working directory" + .to_owned(), + "Pass --runtime-config as a path that exists.", + ) + })?; + let config = + load_runtime_config(&absolute).map_err(|error| runtime_file_refused(&absolute, &error))?; + // The same checks `apply` makes: each URL parses and logs in as the role + // the file names for it. + config + .migration_database_connection_config() + .and_then(|_| config.runtime_database_connection_config()) + .map_err(|error| runtime_file_refused(&absolute, &error))?; + let secrets = config + .secret_resolver() + .map_err(|error| runtime_file_refused(&absolute, &error))?; + let resolve = |member: &str, reference| { + secrets.resolve_reference(reference).map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} could not be read from its secret provider"), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let database = config.database(); + let migration_url = url("migrationUrlRef", database.migration_url_ref())?; + let runtime_url = url("runtimeUrlRef", database.runtime_url_ref())?; + let ca_pem = database + .ca_bundle_ref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + let spatial = package + .map(|package| spatial(&config, package)) + .transpose()? + .flatten(); + Ok(ProvisionInput { + product: ProductDatabase { + product: "breg", + layout: SchemaLayout::Owned(MANAGED_SCHEMAS.iter().map(|s| (*s).to_owned()).collect()), + btree_gist: true, + spatial, + }, + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-bregctl/tests/provision_cli.rs b/crates/registry-bregctl/tests/provision_cli.rs new file mode 100644 index 0000000000..c2d26130e3 --- /dev/null +++ b/crates/registry-bregctl/tests/provision_cli.rs @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `bregctl provision` without a database: print mode reads the runtime file +//! and writes the script without connecting or printing a password, and the +//! administrator flags refuse the combinations the shared command refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file whose secret files name a migration and a runtime login on +/// one server that does not exist, so a connection attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!("postgresql://breg_migration:{MIGRATION_PASSWORD}@db.invalid:5432/registry"), + ), + ( + "runtime-database-url", + format!("postgresql://breg_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/registry"), + ), + ( + "audit-key", + "synthetic-audit-key-of-at-least-32-bytes".to_owned(), + ), + ( + "cursor-key", + "synthetic-cursor-key-of-at-least-32-bytes".to_owned(), + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + // The runtime file's loader requires the package root to be a readable + // directory, though provision reads nothing from it. + std::fs::create_dir(directory.join("package")).unwrap(); + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/breg/runtime/v1alpha1 +kind: BRegRuntimeConfig +listener: + bind: 127.0.0.1:0 +identity: + environment: test + instanceId: provision-cli-test + databaseId: provision-cli-test-db + databaseInitializationEnvironment: test +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + pool: + maximumConnections: 4 + roles: + migration: breg_migration + runtime: breg_runtime +package: + root: {package} +authentication: + oidc: + issuer: https://issuer.example.test + audience: urn:breg:provision-cli-test + allowedAlgorithm: EdDSA + accessTokenType: JWT + scopeClaim: scope + scopeSeparator: \" \" + allowedClients: [directory-client] + maximumTokenLifetimeSeconds: 3600 + leewayMilliseconds: 60000 + authorityClaims: + principal: registry_principal + purpose: registry_purpose +audit: + hashKeyRef: secret:file/audit-key + path: {audit} +cursor: + secretRef: secret:file/cursor-key +", + package = directory.join("package").display(), + secrets = secrets.display(), + audit = directory.join("audit.jsonl").display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in [ + "breg_migration", + "breg_runtime", + "registry", + "registry_internal", + "registry_data", + "registry_source", + "registry_derived", + "registry_context", + "btree_gist", + ] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + assert!( + !stdout.contains("postgis"), + "no package, so no PostGIS step: {stdout}" + ); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "breg"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "registry"); + assert_eq!(report["migrationRole"], "breg_migration"); + assert_eq!(report["runtimeRole"], "breg_runtime"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for arguments in [ + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "BREG_ADMIN_URL", + ], + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "BREG_ADMIN_URL", + ], + vec!["provision", "--runtime-config", &runtime], + ] { + let output = ctl(&arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty(), "{arguments:?}"); + } +} + +#[test] +fn a_package_that_is_not_a_package_is_refused_before_any_connection() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let missing = directory.path().join("no-such-package"); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--package", + missing.to_str().unwrap(), + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(1), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["ok"], false, "{stdout}"); + assert_eq!(report["executed"], false, "{stdout}"); +} diff --git a/crates/registry-bregctl/tests/provision_postgres.rs b/crates/registry-bregctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..bd94d943cd --- /dev/null +++ b/crates/registry-bregctl/tests/provision_postgres.rs @@ -0,0 +1,522 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `bregctl provision` against a real server, then `test`, `package`, +//! `apply` and the runtime on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. A spatial package needs a server with +//! PostGIS (`products/breg/scripts/local-postgres-tls.sh` starts one). The +//! administrator sessions of this suite use verified TLS, so the server must +//! offer it. Without the variables the tests fail on the spot: a skipped +//! database test is not database verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use registry_platform_testing::{TestActorKind, TestAuthorizationServer, TestClient}; +use serde_json::{json, Value}; +use uuid::Uuid; + +const AUDIENCE: &str = "urn:example:applications"; + +fn private_file(path: &Path, contents: &[u8]) { + std::fs::write(path, contents).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&std::ffi::OsStr]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + let report = serde_json::from_slice(&output.stdout).unwrap_or_else(|error| { + panic!( + "{error}: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) + }); + (output.status.code().unwrap(), report) +} + +fn ctl_ok(arguments: &[&std::ffi::OsStr]) -> Value { + let (code, report) = ctl(arguments); + assert_eq!(code, 0, "{report:#}"); + report +} + +/// A project with one record type. A spatial project adds a polygon field, +/// which makes the generated schema need PostGIS. +fn project(root: &Path, spatial: bool) { + let mut fields = vec![json!({ + "id": "owner", "type": "string", "required": true, + "maximumLength": 80, "classification": "internal" + })]; + let mut readable = vec!["owner"]; + if spatial { + fields.push(json!({ + "id": "boundary", "type": "crs84-polygon", "precision": 9, "maximumPositions": 100, + "bbox": {"west": "100.450000000", "south": "13.600000000", + "east": "100.700000000", "north": "13.900000000"}, + "required": true, "classification": "internal" + })); + readable.push("boundary"); + } + let registry = json!({ + "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", + "kind": "BRegProject", + "project": { + "id": "provision-proof", + "canonicalBaseIri": "https://synthetic.example.test/provision-proof", + "version": "1", + "defaultLanguage": "en" + }, + "package": {"sourceRevision": "provision-proof"}, + "datasets": {"notes": {}}, + "recordTypes": {"note": { + "primaryDataset": "notes", "route": "notes", "mutationMode": "mutable", + "classification": "internal", "fields": fields + }}, + "accessProfiles": {"writer": { + "default": true, + "principalClaim": "sub", + "requiredScopes": ["applications:read"], + "actorKind": "service", + "requesterClients": ["application-reader"], + "permissions": {"records": [{ + "recordType": "note", + "operations": ["list"], + "readableFields": readable, + "rowBoundaries": "unrestricted" + }]} + }} + }); + std::fs::create_dir_all(root.join("tests")).unwrap(); + std::fs::write( + root.join("registry.yaml"), + serde_norway::to_string(®istry).unwrap(), + ) + .unwrap(); + let journeys = json!({ + "apiVersion": "id.registrystack.org/formats/breg/journeys/v1", + "kind": "BRegJourneys", + "journeys": [{"id": "provision-proof", "steps": [{ + "id": "list", "recordType": "note", "accessProfile": "writer", + "claims": {"principal": "fixture-reader", "scopes": ["applications:read"], + "actorKind": "service", "requesterClient": "application-reader", + "directClaims": {}}, + "request": {"type": "list"}, + "expect": {"outcome": "success", "status": 200, "count": 0} + }]}] + }); + std::fs::write( + root.join("tests/journeys.yaml"), + serde_norway::to_string(&journeys).unwrap(), + ) + .unwrap(); +} + +/// One deployment directory, the issuer its tokens come from, and the +/// superuser session that creates the roles `provision` is run from. +struct Deployment { + directory: tempfile::TempDir, + admin: tokio_postgres::Client, + base_url: String, + ca: Vec, + issuer: TestAuthorizationServer, + suffix: String, + owner: String, + owner_password: String, + migration: String, + runtime_role: String, + passwords: [String; 2], + /// Databases to drop at the end, and roles to drop after them. + databases: Vec, +} + +impl Deployment { + async fn new() -> Self { + let (base_url, ca) = provision_test_env(); + let admin = connect_verified(&base_url, &ca, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::create_dir(directory.path().join("audit")).unwrap(); + private_file(&secrets.join("postgres-ca.pem"), &ca); + private_file( + &secrets.join("audit-key"), + b"synthetic-audit-key-of-at-least-32-bytes", + ); + private_file( + &secrets.join("cursor-key"), + b"synthetic-cursor-key-of-at-least-32-bytes", + ); + let issuer = TestAuthorizationServer::builder() + .with_signing_key(generate_private_jwk(GeneratedKeyAlgorithm::Es256).unwrap()) + .client( + TestClient::new("application-reader") + .with_resource(AUDIENCE) + .with_actor_kind(TestActorKind::Service), + ) + .start() + .await; + let jwks = reqwest::get(issuer.jwks_uri()) + .await + .unwrap() + .bytes() + .await + .unwrap(); + private_file(&secrets.join("jwks"), &jwks); + let token = issuer.issue_access_token( + "application-reader", + "fixture-reader", + AUDIENCE, + "applications:read", + chrono::Utc::now().timestamp() + 3600, + ); + private_file(&secrets.join("fixture-token"), token.as_bytes()); + let credentials = json!({ + "apiVersion": "id.registrystack.org/formats/breg/schema-test-credentials/v1", + "kind": "BRegSchemaTestCredentials", + "bindings": [{"journeyId": "provision-proof", "stepId": "list", + "credential": {"type": "bearer", "tokenRef": "secret:file/fixture-token"}}] + }); + std::fs::write( + directory.path().join("credentials.yaml"), + serde_norway::to_string(&credentials).unwrap(), + ) + .unwrap(); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let deployment = Self { + owner: format!("breg_owner_{suffix}"), + owner_password: password("owner"), + migration: format!("breg_mig_{suffix}"), + runtime_role: format!("breg_rt_{suffix}"), + passwords: [password("migration"), password("runtime")], + suffix, + directory, + admin, + base_url, + ca, + issuer, + databases: Vec::new(), + }; + deployment + .admin + .batch_execute(&format!( + "CREATE ROLE {} LOGIN PASSWORD '{}' NOSUPERUSER CREATEROLE CREATEDB", + deployment.owner, deployment.owner_password + )) + .await + .unwrap(); + deployment + } + + fn path(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + + /// A URL for `role` against this server and `database`. + fn url(&self, role: &str, password: &str, database: &str) -> String { + let base = registry_platform_provision::admin_config(&self.base_url, Some(&self.ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + format!( + "postgresql://{role}:{password}@{}:{}/{database}", + base.host(), + base.port() + ) + } + + /// Writes the runtime file `name` for `database` over `package`. The two + /// database URLs are the only place the roles, the database and the + /// passwords are written. + fn write_runtime(&self, name: &str, database: &str, package: &Path, bind: &str) -> String { + private_file( + &self.path("secrets").join(format!("{name}-migration-url")), + self.url(&self.migration, &self.passwords[0], database) + .as_bytes(), + ); + private_file( + &self.path("secrets").join(format!("{name}-runtime-url")), + self.url(&self.runtime_role, &self.passwords[1], database) + .as_bytes(), + ); + let runtime = json!({ + "apiVersion": "id.registrystack.org/formats/breg/runtime/v1alpha1", + "kind": "BRegRuntimeConfig", + "listener": {"bind": bind}, + "identity": {"environment": "test", "instanceId": "provision-proof", + "databaseId": "provision-proof", + "databaseInitializationEnvironment": "test"}, + "secretProviders": {"file": {"root": self.path("secrets")}}, + "database": { + "runtimeUrlRef": format!("secret:file/{name}-runtime-url"), + "migrationUrlRef": format!("secret:file/{name}-migration-url"), + "caBundleRef": "secret:file/postgres-ca.pem", + "pool": {"maximumConnections": 4}, + "roles": {"migration": self.migration, "runtime": self.runtime_role} + }, + "package": {"root": package}, + "authentication": { + "oidc": { + "issuer": self.issuer.issuer(), "audience": AUDIENCE, + "allowedAlgorithm": "ES256", "accessTokenType": "at+jwt", + "scopeClaim": "scope", "scopeSeparator": " ", + "allowedClients": ["application-reader"], + "maximumTokenLifetimeSeconds": 3600, "leewayMilliseconds": 0, + "jwksSource": {"type": "static", "documentRef": "secret:file/jwks"} + }, + "authorityClaims": {"principal": "sub"} + }, + "audit": {"hashKeyRef": "secret:file/audit-key", "path": self.path("audit/breg.jsonl")}, + "cursor": {"secretRef": "secret:file/cursor-key"} + }); + let file = self.path(&format!("{name}.yaml")); + std::fs::write(&file, serde_norway::to_string(&runtime).unwrap()).unwrap(); + file.display().to_string() + } + + fn admin_url_file(&self) -> String { + let file = self.path("admin-url"); + private_file( + &file, + self.url(&self.owner, &self.owner_password, "postgres") + .as_bytes(), + ); + file.display().to_string() + } + + /// `provision` as the operate page runs it, from the non-superuser owner. + fn provision(&self, runtime: &str, package: Option<&Path>) -> (i32, Value) { + let admin_file = self.admin_url_file(); + let fixed = [ + "provision", + "--runtime-config", + runtime, + "--admin-url-file", + &admin_file, + ]; + let mut arguments: Vec<&std::ffi::OsStr> = fixed.iter().map(std::ffi::OsStr::new).collect(); + if let Some(package) = package { + arguments.push("--package".as_ref()); + arguments.push(package.as_os_str()); + } + let (code, report) = ctl(&arguments); + for password in self.passwords.iter().chain([&self.owner_password]) { + assert!( + !report.to_string().contains(password.as_str()), + "the report holds no password" + ); + } + (code, report) + } + + /// The PostGIS objects a spatial `test` needs in an already provisioned + /// rehearsal database: the operate page's statements, run by the + /// superuser, because `provision` cannot plan them before a package + /// exists to ask. + async fn add_postgis(&self, database: &str) { + let bbox = format!("{}__spatial_bbox", self.runtime_role); + let (migration, runtime) = (&self.migration, &self.runtime_role); + let setup = connect_verified(&self.base_url, &self.ca, Some(database)).await; + setup + .batch_execute(&format!( + "CREATE SCHEMA registry_spatial_ext;\n\ + REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC;\n\ + CREATE EXTENSION postgis WITH SCHEMA registry_spatial_ext;\n\ + DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{bbox}') THEN \ + CREATE ROLE {bbox} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \ + END IF; END $$;\n\ + GRANT {bbox} TO {migration} WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO {migration}, {runtime}, {bbox};" + )) + .await + .unwrap(); + } + + /// `test` then `package` over a rehearsal database, returning the + /// package directory. + fn build_package(&self, rehearsal_runtime: &str) -> PathBuf { + let project = self.path("project"); + let receipt = self.path("receipt.json"); + let build = self.path("build"); + ctl_ok(&[ + "test".as_ref(), + project.as_os_str(), + "--runtime-config".as_ref(), + rehearsal_runtime.as_ref(), + "--credentials".as_ref(), + self.path("credentials.yaml").as_os_str(), + "--output".as_ref(), + receipt.as_os_str(), + ]); + ctl_ok(&[ + "package".as_ref(), + project.as_os_str(), + "--test-receipt".as_ref(), + receipt.as_os_str(), + "--output".as_ref(), + build.as_os_str(), + ]); + build.join("package") + } + + async fn finish(self) { + // Dropping a database waits for its sessions to end, which the + // administrator session's statement timeout would cut short. + let mut statements: Vec = vec!["SET statement_timeout = 0".to_owned()]; + statements.extend( + self.databases + .iter() + .map(|database| format!("DROP DATABASE IF EXISTS {database} WITH (FORCE)")), + ); + statements.push(format!( + "DROP ROLE IF EXISTS {}__spatial_bbox", + self.runtime_role + )); + for role in [&self.runtime_role, &self.migration, &self.owner] { + statements.push(format!("DROP ROLE IF EXISTS {role}")); + } + for statement in statements { + self.admin.batch_execute(&statement).await.unwrap(); + } + } +} + +fn free_address() -> String { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().to_string() +} + +/// `provision` over the rehearsal and the serving database, `test` and +/// `package` over the first, `apply` over the second, and the runtime +/// started over the runtime credential answers its readiness route. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn provision_then_apply_then_serve_with_split_roles() { + let mut deployment = Deployment::new().await; + project(&deployment.path("project"), false); + let (rehearsal, live) = ( + format!("breg_rehearsal_{}", deployment.suffix), + format!("breg_live_{}", deployment.suffix), + ); + deployment.databases = vec![rehearsal.clone(), live.clone()]; + let empty_package = deployment.path("empty-package"); + std::fs::create_dir(&empty_package).unwrap(); + + let rehearsal_runtime = + deployment.write_runtime("rehearsal", &rehearsal, &empty_package, "127.0.0.1:0"); + let (code, provisioned) = deployment.provision(&rehearsal_runtime, None); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], rehearsal.as_str()); + let package = deployment.build_package(&rehearsal_runtime); + + let address = free_address(); + let live_runtime = deployment.write_runtime("live", &live, &package, &address); + let (code, provisioned) = deployment.provision(&live_runtime, None); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], live.as_str()); + let (code, again) = deployment.provision(&live_runtime, None); + assert_eq!(code, 0, "a second run converges: {again:#}"); + for statement in again["statements"].as_array().unwrap() { + assert_ne!( + statement["outcome"], "created", + "a second run creates nothing: {statement}" + ); + } + + let applied = ctl_ok(&[ + "apply".as_ref(), + "--runtime-config".as_ref(), + live_runtime.as_ref(), + "--package".as_ref(), + package.as_os_str(), + "--initial".as_ref(), + ]); + assert_eq!(applied["activation"], "initial", "{applied:#}"); + + let config = registry_breg::runtime_config::load_runtime_config(Path::new(&live_runtime)) + .expect("the live runtime file loads"); + let prepared = registry_breg::startup::prepare_loaded(config) + .await + .expect("the runtime prepares over the runtime role"); + assert_eq!( + format!("{:?}", prepared.role_mode()).to_lowercase(), + "split", + "the runtime serves on separate roles" + ); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(registry_breg::startup::serve_until_shutdown( + prepared, + async move { + stopped.await.ok(); + Ok(()) + }, + )); + let http = reqwest::Client::builder().no_proxy().build().unwrap(); + let mut ready = false; + for _ in 0..100 { + if let Ok(response) = http.get(format!("http://{address}/ready")).send().await { + if response.status().is_success() { + ready = true; + break; + } + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + assert!(ready, "the readiness route answers"); + stop.send(()).unwrap(); + server.await.unwrap().expect("the server stops cleanly"); + deployment.finish().await; +} + +/// A package with a polygon field needs PostGIS, and `CREATE EXTENSION +/// postgis` needs a superuser, so a non-superuser owner is told which +/// statement needs more. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn spatial_package_as_a_non_superuser_owner_names_the_postgis_statement() { + let mut deployment = Deployment::new().await; + project(&deployment.path("project"), true); + let (rehearsal, live) = ( + format!("breg_rehearsal_{}", deployment.suffix), + format!("breg_live_{}", deployment.suffix), + ); + deployment.databases = vec![rehearsal.clone(), live.clone()]; + let empty_package = deployment.path("empty-package"); + std::fs::create_dir(&empty_package).unwrap(); + + // The owner provisions the rehearsal database, then the superuser adds + // the PostGIS objects `test` needs. + let rehearsal_runtime = + deployment.write_runtime("rehearsal", &rehearsal, &empty_package, "127.0.0.1:0"); + let (code, provisioned) = deployment.provision(&rehearsal_runtime, None); + assert_eq!(code, 0, "{provisioned:#}"); + deployment.add_postgis(&rehearsal).await; + let package = deployment.build_package(&rehearsal_runtime); + + let live_runtime = deployment.write_runtime("live", &live, &package, "127.0.0.1:0"); + let (code, refused) = deployment.provision(&live_runtime, Some(&package)); + assert_eq!(code, 1, "{refused:#}"); + assert_eq!(refused["status"], "domain-refusal", "{refused:#}"); + let diagnostic = &refused["diagnostics"][0]; + assert_eq!( + diagnostic["code"], "platform.provision.statement-needs-privilege", + "{refused:#}" + ); + assert_eq!(diagnostic["path"], "extension.postgis", "{refused:#}"); + deployment.finish().await; +} diff --git a/docs/site/src/content/docs/operate/breg.mdx b/docs/site/src/content/docs/operate/breg.mdx index b195f68b15..d0f996de4c 100644 --- a/docs/site/src/content/docs/operate/breg.mdx +++ b/docs/site/src/content/docs/operate/breg.mdx @@ -46,8 +46,9 @@ occupied by the link; choose another unused, non-symbolic-link name under the re - **PostgreSQL 17 or newer**, reached over TLS, with two login roles: a migration role that owns the schema and applies packages, and a runtime role the serving process uses. A project with a `crs84-polygon` field always needs PostGIS 3.5 or newer. A `crs84-point` field needs PostGIS only - when an access profile grants bbox queries. Your administrator creates the roles, schemas, and - extensions. The product never creates any of them. SQLite is not a target. + when an access profile grants bbox queries. `bregctl provision` creates the roles, the database, the + schemas, and the extensions from an administrator's credentials. `breg` and `apply` create none + of them. SQLite is not a target. Ubuntu 24.04 ships PostgreSQL 16 and Debian 12 ships PostgreSQL 15, both too old: install 17 from the PostgreSQL project's apt repository (PGDG), or run the `postgres:17` image (`postgis/postgis` at PostgreSQL 17 when the project requires PostGIS). @@ -138,81 +139,6 @@ the tag. [Serve the container image](#serve-the-container-image) shows how to ru {/* Evidence: crates/registry-breg/install.sh; release/docker/Dockerfile.breg; release/scripts/release_candidate.py, BREG_RUNTIME_IMAGE_NAMES; release/VERIFY.md. */} -## Provision PostgreSQL - -As a PostgreSQL administrator, create the two roles: - -```sql -CREATE ROLE registry_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS PASSWORD ''; -CREATE ROLE registry_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS PASSWORD ''; -``` - -Two separate roles are the split role mode, which production uses. The serving process then cannot -write the activation ledger or registry state, and `apply` and startup both refuse a runtime role -that could, naming the grant, ownership, membership, or trigger to remove. Keep the migration -credential off the serving host when no activation is in progress. - -Create two databases with the same shape: the serving database and the schema-test database. In -each, as the administrator (this is the serving database, `registry`): - -```sql -CREATE DATABASE registry; -REVOKE ALL ON DATABASE registry FROM PUBLIC; -REVOKE CREATE ON DATABASE registry FROM registry_migration, registry_runtime; -GRANT CONNECT ON DATABASE registry TO registry_migration, registry_runtime; -\connect registry -CREATE EXTENSION IF NOT EXISTS btree_gist; -CREATE SCHEMA registry_internal AUTHORIZATION registry_migration; -CREATE SCHEMA registry_data AUTHORIZATION registry_migration; -CREATE SCHEMA registry_source AUTHORIZATION registry_migration; -CREATE SCHEMA registry_derived AUTHORIZATION registry_migration; -CREATE SCHEMA registry_context AUTHORIZATION registry_migration; -REVOKE ALL ON SCHEMA registry_internal, registry_data, registry_source, - registry_derived, registry_context FROM PUBLIC; -``` - -The package creates every table, function, and policy inside those five schemas. A missing -prerequisite surfaces at `test` or `apply`, never at runtime. - -The migration role owns only those five schemas. It must not own the database (for example through -`CREATE DATABASE registry OWNER registry_migration`) and must not hold `CREATE` on it, because an -owner holds `CREATE` implicitly. `test` and `apply` check this before changing anything and refuse -with `migration role has database-level administrative authority`, which is also the refusal for a -role that is a superuser or has `BYPASSRLS`, `CREATEDB`, or `CREATEROLE`. If a managed PostgreSQL -service created the database for you, check its owner and its grants first. - -For a project with polygon storage or bbox queries, install PostGIS in a schema neither registry -role owns. If the project grants bbox queries, also add a bounding-box role named after the runtime -role with the suffix `__spatial_bbox`: - -```sql -CREATE ROLE registry_runtime__spatial_bbox NOLOGIN NOSUPERUSER NOCREATEDB - NOCREATEROLE NOINHERIT NOBYPASSRLS; -GRANT registry_runtime__spatial_bbox TO registry_migration - WITH INHERIT FALSE, SET TRUE, ADMIN FALSE; --- in each database -CREATE SCHEMA registry_spatial_ext AUTHORIZATION postgres; -CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA registry_spatial_ext; -REVOKE CREATE ON DATABASE registry FROM PUBLIC, registry_migration, registry_runtime; -REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC; -GRANT USAGE ON SCHEMA registry_spatial_ext - TO registry_migration, registry_runtime, registry_runtime__spatial_bbox; -``` - -A package that stores polygons and grants no bbox queries omits the bbox role, its membership, and -its name from the final `GRANT USAGE`. Keep the PostGIS schema, extension, and grants to the -migration and runtime roles. - -Size connections, timeouts, and statement statistics once the registry serves; see -[Set a PostgreSQL baseline](../breg-monitor/#set-a-postgresql-baseline). - -{/* Evidence: crates/registry-breg/src/postgres/migration_ledger.rs, RoleMode; - crates/registry-breg/src/postgres/roles.rs, verify_migration_role, - find_runtime_write_authority and the __spatial_bbox role; crates/registry-breg/src/postgres/schema.rs, - refuse_existing_managed_objects(); crates/registry-breg/src/startup.rs, RuntimeWriteAuthority. */} - ## Write the runtime configuration The runtime file binds one package to one database, one token issuer, and one listener. It is a @@ -334,6 +260,128 @@ In a container platform that injects secrets as environment variables, declare crates/registry-breg/src/cursor.rs, ROOT_SECRET_MIN_BYTES; crates/registry-breg/src/runtime_config.rs, database_connection_config_for(). */} +## Provision PostgreSQL + +Your runtime file already names the roles, their passwords, and the database. They are the URLs +in `database.migrationUrlRef` and `database.runtimeUrlRef`, and the roles under `database.roles`. +With the secret files in place, run `bregctl provision` once as a PostgreSQL role that can create +roles and databases. The runtime file's `package.root` must be a readable directory, though +`provision` reads nothing from it: create an empty one if the package does not exist yet. + +```sh +bregctl provision --runtime-config /etc/breg/runtime.yaml --admin-url-file /etc/breg/admin-url +``` + +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` +and `CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable +instead, use `--admin-url-env NAME`. The connection requires TLS and verifies the server +certificate. Set `database.caBundleRef` in the runtime file to trust a private CA. The command +never prints the administrator URL or a password. + +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Installs `btree_gist`. +- Creates the five schemas the package fills, `registry_internal`, `registry_data`, + `registry_source`, `registry_derived`, and `registry_context`, each owned by the migration role + and closed to `PUBLIC`. + +Run it again at any time. It creates only what is missing. It refuses a role that exists with +other attributes, and a role whose URL does not open a session, and tells you which. + +Two roles are the split role mode, which production uses. The serving process then cannot write +the activation ledger or registry state, and `apply` and startup both refuse a runtime role that +could, naming the grant, ownership, membership, or trigger to remove. Keep the migration +credential off the serving host when no activation is in progress. + +The schema-test database that `test` needs has the same shape. Point a copy of the runtime file +at it, as [Check, test, package](#check-test-package) describes, and run `provision` over that +copy too. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a +`\password` line that prompts for the password in `psql`, so the script holds no password: + +```sql +SET createrole_self_grant = 'set,inherit'; +CREATE ROLE "registry_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "registry_migration" +CREATE ROLE "registry_runtime" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "registry_runtime" +CREATE DATABASE "registry" WITH ALLOW_CONNECTIONS false; +REVOKE ALL ON DATABASE "registry" FROM PUBLIC; +GRANT CONNECT ON DATABASE "registry" TO "registry_migration", "registry_runtime"; +ALTER DATABASE "registry" ALLOW_CONNECTIONS true; +\connect "registry" +CREATE EXTENSION btree_gist; +CREATE SCHEMA "registry_internal" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_internal" FROM PUBLIC; +-- the same two statements for registry_data, registry_source, registry_derived, registry_context +``` + +The names come from your URLs. Add `--format json` for a report of each statement and its outcome. + +The migration role owns only those five schemas. It must not own the database (for example through +`CREATE DATABASE registry OWNER registry_migration`) and must not hold `CREATE` on it, because an +owner holds `CREATE` implicitly. `test` and `apply` check this before changing anything and refuse +with `migration role has database-level administrative authority`, which is also the refusal for a +role that is a superuser or has `BYPASSRLS`, `CREATEDB`, or `CREATEROLE`. If a managed PostgreSQL +service created the database for you, check its owner and its grants first. + +`provision` grants the runtime role nothing beyond `CONNECT`. `apply` grants it what serving +needs. The package creates every table, function, and policy inside the five schemas. A missing +prerequisite surfaces at `test` or `apply`, never at runtime. + +### Install PostGIS + +For a project with polygon storage or bbox queries, PostGIS lives in a schema neither registry +role owns, and `CREATE EXTENSION postgis` needs a superuser. Pass the built package, and the +command adds the PostGIS steps for a package that needs them: + +```sh +bregctl provision --runtime-config /etc/breg/runtime.yaml \ + --admin-url-file /etc/breg/superuser-url --package /var/lib/breg/build-1/package +``` + +Without `--package`, no PostGIS step is planned. As a role that is not a superuser, the command +stops at that statement with `platform.provision.statement-needs-privilege` at `extension.postgis`. +Run it with `--print-sql` and give the script to a superuser, or run it with a superuser URL, then +run `provision` again. + +A package exists only after `test`, and `test` needs PostGIS in the schema-test database. For that +one database, a superuser runs the PostGIS statements by hand once. If the project grants bbox +queries, the statements also add a bounding-box role named after the runtime role with the suffix +`__spatial_bbox`: + +```sql +CREATE ROLE registry_runtime__spatial_bbox NOLOGIN NOSUPERUSER NOCREATEDB + NOCREATEROLE NOINHERIT NOBYPASSRLS; +GRANT registry_runtime__spatial_bbox TO registry_migration + WITH INHERIT FALSE, SET TRUE, ADMIN FALSE; +-- in each database +CREATE SCHEMA registry_spatial_ext AUTHORIZATION postgres; +CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA registry_spatial_ext; +REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC; +GRANT USAGE ON SCHEMA registry_spatial_ext + TO registry_migration, registry_runtime, registry_runtime__spatial_bbox; +``` + +A package that stores polygons and grants no bbox queries omits the bbox role, its membership, and +its name from the final `GRANT USAGE`. Keep the PostGIS schema, extension, and grants to the +migration and runtime roles. + +Size connections, timeouts, and statement statistics once the registry serves; see +[Set a PostgreSQL baseline](../breg-monitor/#set-a-postgresql-baseline). + +{/* Evidence: crates/registry-bregctl/src/provision.rs; crates/registry-platform-provision/src/plan.rs; + crates/registry-breg/src/postgres/migration_ledger.rs, RoleMode; + crates/registry-breg/src/postgres/roles.rs, verify_migration_role, + find_runtime_write_authority and the __spatial_bbox role; crates/registry-breg/src/postgres/schema.rs, + refuse_existing_managed_objects(); crates/registry-breg/src/startup.rs, RuntimeWriteAuthority; + crates/registry-bregctl/tests/provision_postgres.rs. */} + ## What a token must carry The registry verifies a bearer access token before it reads any claim. Configure the issuer so diff --git a/products/breg/AGENTS.md b/products/breg/AGENTS.md index 9f0c2ba363..bb8c230db2 100644 --- a/products/breg/AGENTS.md +++ b/products/breg/AGENTS.md @@ -160,6 +160,12 @@ each time: the container ID must be the full hex ID, the CA copy cannot sit directly in `/tmp`, the URL host must be `localhost` (the certificate's name), and the PostGIS image starts PostgreSQL twice before it is really ready. +`crates/registry-bregctl/tests/provision_postgres.rs` (`cargo test -p registry-bregctl --features +postgres-test --test provision_postgres`) provisions as a non-superuser owner against that same TLS +PostGIS container. It reads `PROVISION_TEST_DATABASE_URL` (the superuser URL with +`sslmode=verify-full`) and `PROVISION_TEST_DATABASE_CA` (the `BREG_TEST_TLS_CA_PEM_PATH` file) and +fails when either is missing. + Native development lifecycle change. The test owns a PostgreSQL container, so it needs Docker: From 7aa83f6eba17e9f8ba75a94d8ab655a5c25206d4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:07:18 +0100 Subject: [PATCH 023/136] fix(platform): keep loopback in a crate with no HTTP server dependency config and httputil reached httpsec only for the loopback rule, and httpsec's default server feature carries axum, so the Adapter engine reached axum through them. The rule now lives in registry-platform-loopback, which depends on nothing; httpsec re-exports it under the same path. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 1 + .github/workflows/render-golden.yml | 2 ++ Cargo.lock | 9 +++++++-- Cargo.toml | 2 ++ crates/registry-platform-config/Cargo.toml | 2 +- crates/registry-platform-config/src/blocks.rs | 2 +- crates/registry-platform-httpsec/Cargo.toml | 1 + crates/registry-platform-httpsec/README.md | 6 +++--- crates/registry-platform-httpsec/src/lib.rs | 2 +- crates/registry-platform-httputil/Cargo.toml | 2 +- crates/registry-platform-httputil/src/lib.rs | 2 +- crates/registry-platform-loopback/Cargo.toml | 13 +++++++++++++ crates/registry-platform-loopback/README.md | 8 ++++++++ .../src/lib.rs} | 0 products/platform/CHANGELOG.md | 3 ++- products/platform/README.md | 1 + 16 files changed, 45 insertions(+), 11 deletions(-) create mode 100644 crates/registry-platform-loopback/Cargo.toml create mode 100644 crates/registry-platform-loopback/README.md rename crates/{registry-platform-httpsec/src/loopback.rs => registry-platform-loopback/src/lib.rs} (100%) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 979b387f7a..5088854d90 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -36,6 +36,7 @@ "registry-platform-hooks", "registry-platform-httpsec", "registry-platform-httputil", + "registry-platform-loopback", "registry-platform-metrics", "registry-platform-objectstore", "registry-platform-oidc", diff --git a/.github/workflows/render-golden.yml b/.github/workflows/render-golden.yml index 1bba2b026e..c6b727b841 100644 --- a/.github/workflows/render-golden.yml +++ b/.github/workflows/render-golden.yml @@ -25,6 +25,7 @@ on: - "crates/registry-platform-config/**" - "crates/registry-platform-crypto/**" - "crates/registry-platform-httpsec/**" + - "crates/registry-platform-loopback/**" - "crates/registry-platform-testing/**" - "crates/registry-platform-yaml/**" - "products/render/**" @@ -50,6 +51,7 @@ on: - "crates/registry-platform-config/**" - "crates/registry-platform-crypto/**" - "crates/registry-platform-httpsec/**" + - "crates/registry-platform-loopback/**" - "crates/registry-platform-testing/**" - "crates/registry-platform-yaml/**" - "products/render/**" diff --git a/Cargo.lock b/Cargo.lock index f28870e4ed..29cf16ff86 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7849,7 +7849,7 @@ name = "registry-platform-config" version = "0.49.0" dependencies = [ "registry-platform-canonical-json", - "registry-platform-httpsec", + "registry-platform-loopback", "registry-platform-yaml", "rustix 1.1.6", "schemars", @@ -7944,6 +7944,7 @@ dependencies = [ "axum", "http", "registry-platform-authcommon", + "registry-platform-loopback", "serde", "serde_json", "thiserror 2.0.21", @@ -7975,7 +7976,7 @@ dependencies = [ "registry-platform-authcommon", "registry-platform-canonical-json", "registry-platform-crypto", - "registry-platform-httpsec", + "registry-platform-loopback", "reqwest 0.12.28", "rustls-native-certs", "serde", @@ -7991,6 +7992,10 @@ dependencies = [ "zeroize", ] +[[package]] +name = "registry-platform-loopback" +version = "0.49.0" + [[package]] name = "registry-platform-metrics" version = "0.49.0" diff --git a/Cargo.toml b/Cargo.toml index f24ac1733a..01600e8e4c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ members = [ "crates/registry-platform-hooks", "crates/registry-platform-httpsec", "crates/registry-platform-httputil", + "crates/registry-platform-loopback", "crates/registry-platform-metrics", "crates/registry-platform-objectstore", "crates/registry-platform-oidc", @@ -204,6 +205,7 @@ registry-platform-dispatch = { path = "crates/registry-platform-dispatch", versi registry-platform-hooks = { path = "crates/registry-platform-hooks", version = "0.49.0" } registry-platform-httpsec = { path = "crates/registry-platform-httpsec", version = "0.49.0", default-features = false } registry-platform-httputil = { path = "crates/registry-platform-httputil", version = "0.49.0" } +registry-platform-loopback = { path = "crates/registry-platform-loopback", version = "0.49.0" } registry-platform-metrics = { path = "crates/registry-platform-metrics", version = "0.49.0" } registry-platform-objectstore = { path = "crates/registry-platform-objectstore", version = "0.49.0" } registry-platform-oidc = { path = "crates/registry-platform-oidc", version = "0.49.0" } diff --git a/crates/registry-platform-config/Cargo.toml b/crates/registry-platform-config/Cargo.toml index 968c0fb52c..98def715ee 100644 --- a/crates/registry-platform-config/Cargo.toml +++ b/crates/registry-platform-config/Cargo.toml @@ -15,7 +15,7 @@ schema = ["dep:schemars", "registry-platform-yaml/schema"] [dependencies] registry-platform-canonical-json = { workspace = true } -registry-platform-httpsec.workspace = true +registry-platform-loopback.workspace = true registry-platform-yaml.workspace = true rustix.workspace = true schemars = { workspace = true, optional = true } diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index be9739f581..b27745cf34 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -428,7 +428,7 @@ fn valid_jwks_uri(value: &Url, allow_loopback_http: bool, allow_insecure_http: b || (allow_loopback_http && parsed .host_str() - .and_then(registry_platform_httpsec::loopback::loopback_host) + .and_then(registry_platform_loopback::loopback_host) .is_some()) } _ => false, diff --git a/crates/registry-platform-httpsec/Cargo.toml b/crates/registry-platform-httpsec/Cargo.toml index 49212d38f3..0d57340dba 100644 --- a/crates/registry-platform-httpsec/Cargo.toml +++ b/crates/registry-platform-httpsec/Cargo.toml @@ -32,6 +32,7 @@ required-features = ["server"] axum = { workspace = true, optional = true } http.workspace = true registry-platform-authcommon = { workspace = true, optional = true } +registry-platform-loopback.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/crates/registry-platform-httpsec/README.md b/crates/registry-platform-httpsec/README.md index c41f58ec35..9120a34c8b 100644 --- a/crates/registry-platform-httpsec/README.md +++ b/crates/registry-platform-httpsec/README.md @@ -25,9 +25,9 @@ Client-safe HTTP validation plus Axum and Tower helpers for HTTP security. primitives for Registry service responses. With the `server` feature, `TraceId` implements `registry_platform_authcommon::RefusalTraceId`, so a service passes its request trace id to `record_refusal!`. -- `loopback`, the one definition of loopback for outbound destinations and - loopback origins: `loopback_address`, `loopback_host` and - `loopback_literal`. A literal in `127.0.0.0/8`, `::1` or the IPv4-mapped +- `loopback`, a re-export of `registry-platform-loopback`, the one definition + of loopback for outbound destinations and loopback origins: + `loopback_address`, `loopback_host` and `loopback_literal`. A literal in `127.0.0.0/8`, `::1` or the IPv4-mapped form of `127.0.0.0/8` is loopback, and so is the exact name `localhost` once the connection is pinned to loopback addresses (`LoopbackHost::pinned_by`). A site that accepts the name must pin the diff --git a/crates/registry-platform-httpsec/src/lib.rs b/crates/registry-platform-httpsec/src/lib.rs index 4ce09c66f5..d913d8b3e8 100644 --- a/crates/registry-platform-httpsec/src/lib.rs +++ b/crates/registry-platform-httpsec/src/lib.rs @@ -1,7 +1,7 @@ //! HTTP security primitives shared by Registry Stack servers and clients. mod client; -pub mod loopback; +pub use registry_platform_loopback as loopback; pub use client::{ response_trace_id, ProblemDocument, ProblemDocumentError, ResponseTraceError, TraceId, diff --git a/crates/registry-platform-httputil/Cargo.toml b/crates/registry-platform-httputil/Cargo.toml index 0d07d717c8..2f9776a85f 100644 --- a/crates/registry-platform-httputil/Cargo.toml +++ b/crates/registry-platform-httputil/Cargo.toml @@ -27,7 +27,7 @@ ipnet.workspace = true registry-platform-authcommon.workspace = true registry-platform-canonical-json.workspace = true registry-platform-crypto.workspace = true -registry-platform-httpsec.workspace = true +registry-platform-loopback.workspace = true reqwest.workspace = true rustls-native-certs.workspace = true serde.workspace = true diff --git a/crates/registry-platform-httputil/src/lib.rs b/crates/registry-platform-httputil/src/lib.rs index 10d0c02e10..912c39b4e3 100644 --- a/crates/registry-platform-httputil/src/lib.rs +++ b/crates/registry-platform-httputil/src/lib.rs @@ -9,7 +9,7 @@ use thiserror::Error; pub mod client; pub mod destination; pub mod probe; -pub use registry_platform_httpsec::loopback; +pub use registry_platform_loopback as loopback; pub use client::{ exchange_authorization_from_json, valid_resource_uri, valid_scope_token, diff --git a/crates/registry-platform-loopback/Cargo.toml b/crates/registry-platform-loopback/Cargo.toml new file mode 100644 index 0000000000..71260a935e --- /dev/null +++ b/crates/registry-platform-loopback/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "registry-platform-loopback" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The one definition of loopback for outbound destinations and loopback origins." +repository.workspace = true +readme = "README.md" +publish = false + +[lints] +workspace = true diff --git a/crates/registry-platform-loopback/README.md b/crates/registry-platform-loopback/README.md new file mode 100644 index 0000000000..6c2ab577e0 --- /dev/null +++ b/crates/registry-platform-loopback/README.md @@ -0,0 +1,8 @@ +# Registry Platform Loopback + +`registry-platform-loopback` is the one definition of "loopback" for outbound destinations and loopback origins. It depends on nothing outside `std`, so a crate that only needs the rule does not pull in an HTTP server stack. + +- `loopback_address`, `loopback_host` and `loopback_literal`. A literal in `127.0.0.0/8`, `::1` or the IPv4-mapped form of `127.0.0.0/8` is loopback, and so is the exact name `localhost` once the connection is pinned to loopback addresses (`LoopbackHost::pinned_by`). `*.localhost`, `localhost.` and a bracketed IPv4 literal such as `[127.0.0.1]` are never loopback. +- A site that accepts the name `localhost` must pin the connection; a site that cannot pin uses `loopback_literal`. Bind sites keep their own, stricter rule. + +`registry-platform-httpsec` and `registry-platform-httputil` re-export this crate as `loopback`. diff --git a/crates/registry-platform-httpsec/src/loopback.rs b/crates/registry-platform-loopback/src/lib.rs similarity index 100% rename from crates/registry-platform-httpsec/src/loopback.rs rename to crates/registry-platform-loopback/src/lib.rs diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 5bacd85ada..906dab4af3 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -20,7 +20,8 @@ `StaticJwksError::OctetKeyPair`, which names the key position and says to use an RSA or EC key. -- One definition of loopback, `registry_platform_httpsec::loopback` (also +- One definition of loopback, the std-only `registry-platform-loopback` crate + (re-exported as `registry_platform_httpsec::loopback` and `registry_platform_httputil::loopback`), for outbound destinations and loopback origins. A host is loopback when it is an address literal in `127.0.0.0/8`, `::1` or an IPv4-mapped form of `127.0.0.0/8`, or the exact diff --git a/products/platform/README.md b/products/platform/README.md index 99ea9b08b3..716aa81a2a 100644 --- a/products/platform/README.md +++ b/products/platform/README.md @@ -29,6 +29,7 @@ integration-test fixtures. | [`registry-platform-hooks`](../../crates/registry-platform-hooks/README.md) | Shared hook contract: declarations, envelope, handler messages, compile-time rules, and the delivery core behind the `postgres` feature. | | [`registry-platform-httpsec`](../../crates/registry-platform-httpsec/README.md) | Axum/Tower HTTP security middleware, CORS policy validation, body limits, and RFC 9457 Problem Details responses. | | [`registry-platform-httputil`](../../crates/registry-platform-httputil/README.md) | Outbound HTTP clients, bounded response reads, URL construction, and SSRF-resistant fetch validation. | +| [`registry-platform-loopback`](../../crates/registry-platform-loopback/README.md) | The one definition of loopback for outbound destinations and loopback origins; `std` only. | | [`registry-platform-metrics`](../../crates/registry-platform-metrics/README.md) | Prometheus text exposition (format 0.0.4) writer and counter and histogram state with bounded, value-free label sets. | | [`registry-platform-objectstore`](../../crates/registry-platform-objectstore/README.md) | S3-compatible object storage and HTTP content verification transports, bound to a caller-supplied namespace, with fixed refusals and no retries. | | [`registry-platform-oidc`](../../crates/registry-platform-oidc/README.md) | OIDC discovery, JWKS caching, and JWT verifier configuration shared by registry services. | From 0e0376c86132cceeded04c0803b61acf037f972f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:10:51 +0100 Subject: [PATCH 024/136] feat(platform): add the posture crate that reads --posture and REGISTRY_STACK_POSTURE A process declares development or production once, through the flag or the variable; unset means production. A value that is not a posture, or a flag and variable that disagree, is refused with a value-free message before any file is read. No product reads it yet. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 1 + Cargo.lock | 4 + Cargo.toml | 2 + crates/registry-platform-posture/Cargo.toml | 13 + crates/registry-platform-posture/README.md | 8 + crates/registry-platform-posture/src/lib.rs | 350 ++++++++++++++++++++ products/platform/README.md | 1 + 7 files changed, 379 insertions(+) create mode 100644 crates/registry-platform-posture/Cargo.toml create mode 100644 crates/registry-platform-posture/README.md create mode 100644 crates/registry-platform-posture/src/lib.rs diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 5088854d90..b0dbcefc7f 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -40,6 +40,7 @@ "registry-platform-metrics", "registry-platform-objectstore", "registry-platform-oidc", + "registry-platform-posture", "registry-platform-provision", "registry-platform-ratelimit", "registry-platform-resilience", diff --git a/Cargo.lock b/Cargo.lock index 29cf16ff86..ed4ce79161 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8048,6 +8048,10 @@ dependencies = [ "uuid", ] +[[package]] +name = "registry-platform-posture" +version = "0.49.0" + [[package]] name = "registry-platform-provision" version = "0.49.0" diff --git a/Cargo.toml b/Cargo.toml index 01600e8e4c..cc1a9f906f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,7 @@ members = [ "crates/registry-platform-metrics", "crates/registry-platform-objectstore", "crates/registry-platform-oidc", + "crates/registry-platform-posture", "crates/registry-platform-provision", "crates/registry-platform-ratelimit", "crates/registry-platform-resilience", @@ -209,6 +210,7 @@ registry-platform-loopback = { path = "crates/registry-platform-loopback", versi registry-platform-metrics = { path = "crates/registry-platform-metrics", version = "0.49.0" } registry-platform-objectstore = { path = "crates/registry-platform-objectstore", version = "0.49.0" } registry-platform-oidc = { path = "crates/registry-platform-oidc", version = "0.49.0" } +registry-platform-posture = { path = "crates/registry-platform-posture", version = "0.49.0" } registry-platform-provision = { path = "crates/registry-platform-provision", version = "0.49.0" } registry-platform-ratelimit = { path = "crates/registry-platform-ratelimit", version = "0.49.0" } registry-platform-resilience = { path = "crates/registry-platform-resilience", version = "0.49.0" } diff --git a/crates/registry-platform-posture/Cargo.toml b/crates/registry-platform-posture/Cargo.toml new file mode 100644 index 0000000000..0cd55218c5 --- /dev/null +++ b/crates/registry-platform-posture/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "registry-platform-posture" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The declared posture (development or production) and how a process reads it." +repository.workspace = true +readme = "README.md" +publish = false + +[lints] +workspace = true diff --git a/crates/registry-platform-posture/README.md b/crates/registry-platform-posture/README.md new file mode 100644 index 0000000000..6da66f01dc --- /dev/null +++ b/crates/registry-platform-posture/README.md @@ -0,0 +1,8 @@ +# Registry Platform Posture + +`registry-platform-posture` holds the declared posture of a process, `development` or `production`, and the rules for reading it. It depends on nothing outside `std`, so any platform crate can name the type. + +- `Posture`, `PostureSource` and `DeclaredPosture`. The accepted values are exactly `development` and `production`, case-sensitive, with no trimming. Neither the `--posture` flag nor the `REGISTRY_STACK_POSTURE` variable present means `production` with source `default`. +- `declared_from(flag, environment)` is pure and decides from the two inputs. A flag and a variable that are both present and equal give source `flag`. Different values are refused. +- `declared(flag)` reads the variable once. Call it only from `main` or a command dispatcher, and pass the result down as a value. +- `PostureError` has three cases with stable codes (`platform.posture.invalid-value`, `platform.posture.conflict`), value-free messages and a suggested action. The refusals happen before any file is read. diff --git a/crates/registry-platform-posture/src/lib.rs b/crates/registry-platform-posture/src/lib.rs new file mode 100644 index 0000000000..23a6a261e2 --- /dev/null +++ b/crates/registry-platform-posture/src/lib.rs @@ -0,0 +1,350 @@ +//! The declared posture of a process, `development` or `production`, and the +//! rules for reading it from the `--posture` flag and `REGISTRY_STACK_POSTURE`. +//! +//! The crate depends on nothing outside `std`, so any platform crate can name +//! the type. Reading the declaration performs no file access and never echoes +//! the value it was given. + +use std::ffi::OsStr; +use std::fmt; + +/// The environment variable that declares the posture of a process. +pub const POSTURE_ENV: &str = "REGISTRY_STACK_POSTURE"; +/// The long name of the command-line flag that declares the posture. +pub const POSTURE_FLAG: &str = "posture"; +/// The HTTP field name that marks a response with its posture. +pub const POSTURE_HEADER: &str = "registry-posture"; +/// The accepted spelling of [`Posture::Development`]. +pub const DEVELOPMENT: &str = "development"; +/// The accepted spelling of [`Posture::Production`]. +pub const PRODUCTION: &str = "production"; + +/// A posture a process declares for itself. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Posture { + Development, + Production, +} + +impl Posture { + /// The accepted spelling of this posture. + pub const fn as_str(self) -> &'static str { + match self { + Posture::Development => DEVELOPMENT, + Posture::Production => PRODUCTION, + } + } + + /// Parses an exact, case-sensitive spelling. No trimming. + pub fn parse(value: &str) -> Option { + match value { + DEVELOPMENT => Some(Posture::Development), + PRODUCTION => Some(Posture::Production), + _ => None, + } + } +} + +/// Where a declared posture came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PostureSource { + Flag, + Environment, + Default, +} + +/// A posture together with the source that declared it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DeclaredPosture { + pub posture: Posture, + pub source: PostureSource, +} + +/// A refusal made before any file is read. Messages never contain the value given. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PostureError { + /// The variable is set to an empty, non-UTF-8 or unknown value. + InvalidEnvironment, + /// The flag was given an unknown value. + InvalidFlag, + /// Two declarations disagree. + Conflict, +} + +impl PostureError { + /// The stable diagnostic code. + pub const fn code(self) -> &'static str { + match self { + PostureError::InvalidEnvironment | PostureError::InvalidFlag => { + "platform.posture.invalid-value" + } + PostureError::Conflict => "platform.posture.conflict", + } + } + + /// A value-free description of the refusal. + pub const fn message(self) -> &'static str { + match self { + PostureError::InvalidEnvironment => { + "REGISTRY_STACK_POSTURE is set to a value that is not a posture" + } + PostureError::InvalidFlag => "--posture was given a value that is not a posture", + PostureError::Conflict => { + "--posture and REGISTRY_STACK_POSTURE declare different postures" + } + } + } + + /// What the operator can do about it. + pub const fn suggested_action(self) -> &'static str { + match self { + PostureError::InvalidEnvironment => { + "Set it to development or production, or unset it for production." + } + PostureError::InvalidFlag => "Pass --posture development or --posture production.", + PostureError::Conflict => "Declare the posture once, or give both the same value.", + } + } +} + +impl fmt::Display for PostureError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.message()) + } +} + +impl std::error::Error for PostureError {} + +/// Decides the posture from the two inputs. Pure. +/// +/// A set variable is validated even when the flag is also present. When both +/// are invalid the variable is reported first. Neither input present gives +/// production with source [`PostureSource::Default`]. Both present and equal +/// gives source [`PostureSource::Flag`]. +pub fn declared_from( + flag: Option<&str>, + environment: Option<&OsStr>, +) -> Result { + let from_environment = match environment { + None => None, + Some(value) => Some( + value + .to_str() + .and_then(Posture::parse) + .ok_or(PostureError::InvalidEnvironment)?, + ), + }; + let from_flag = match flag { + None => None, + Some(value) => Some(Posture::parse(value).ok_or(PostureError::InvalidFlag)?), + }; + match (from_flag, from_environment) { + (Some(flag), Some(environment)) if flag != environment => Err(PostureError::Conflict), + (Some(posture), _) => Ok(DeclaredPosture { + posture, + source: PostureSource::Flag, + }), + (None, Some(posture)) => Ok(DeclaredPosture { + posture, + source: PostureSource::Environment, + }), + (None, None) => Ok(DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Default, + }), + } +} + +/// Reads [`POSTURE_ENV`] once and calls [`declared_from`]. Call it only from `main` +/// or a command dispatcher, so the process-global variable is read in one place. +pub fn declared(flag: Option<&str>) -> Result { + declared_from(flag, std::env::var_os(POSTURE_ENV).as_deref()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env(value: &str) -> Option<&OsStr> { + Some(OsStr::new(value)) + } + + fn ok(posture: Posture, source: PostureSource) -> Result { + Ok(DeclaredPosture { posture, source }) + } + + #[test] + fn flag_only() { + assert_eq!( + declared_from(Some("development"), None), + ok(Posture::Development, PostureSource::Flag) + ); + assert_eq!( + declared_from(Some("production"), None), + ok(Posture::Production, PostureSource::Flag) + ); + } + + #[test] + fn variable_only() { + assert_eq!( + declared_from(None, env("development")), + ok(Posture::Development, PostureSource::Environment) + ); + assert_eq!( + declared_from(None, env("production")), + ok(Posture::Production, PostureSource::Environment) + ); + } + + #[test] + fn both_equal_report_the_flag() { + assert_eq!( + declared_from(Some("development"), env("development")), + ok(Posture::Development, PostureSource::Flag) + ); + assert_eq!( + declared_from(Some("production"), env("production")), + ok(Posture::Production, PostureSource::Flag) + ); + } + + #[test] + fn both_different_conflict() { + assert_eq!( + declared_from(Some("development"), env("production")), + Err(PostureError::Conflict) + ); + assert_eq!( + declared_from(Some("production"), env("development")), + Err(PostureError::Conflict) + ); + } + + #[test] + fn neither_is_production_by_default() { + assert_eq!( + declared_from(None, None), + ok(Posture::Production, PostureSource::Default) + ); + } + + #[test] + fn empty_variable_is_refused() { + assert_eq!( + declared_from(None, env("")), + Err(PostureError::InvalidEnvironment) + ); + } + + #[test] + fn variable_is_exact_and_case_sensitive() { + for value in [ + "Development", + "PRODUCTION", + " production", + "production ", + "dev", + "prod", + ] { + assert_eq!( + declared_from(None, env(value)), + Err(PostureError::InvalidEnvironment), + "{value:?}" + ); + } + } + + #[cfg(unix)] + #[test] + fn non_utf8_variable_is_refused() { + use std::os::unix::ffi::OsStrExt; + let value = OsStr::from_bytes(b"production\xff"); + assert_eq!( + declared_from(None, Some(value)), + Err(PostureError::InvalidEnvironment) + ); + } + + #[test] + fn bad_flag_is_refused() { + for value in ["", "Development", " production", "staging"] { + assert_eq!( + declared_from(Some(value), None), + Err(PostureError::InvalidFlag), + "{value:?}" + ); + } + } + + #[test] + fn bad_flag_is_refused_beside_a_valid_variable() { + assert_eq!( + declared_from(Some("staging"), env("production")), + Err(PostureError::InvalidFlag) + ); + } + + #[test] + fn bad_variable_is_refused_beside_a_valid_flag() { + assert_eq!( + declared_from(Some("production"), env("staging")), + Err(PostureError::InvalidEnvironment) + ); + } + + #[test] + fn bad_variable_is_reported_before_a_bad_flag() { + assert_eq!( + declared_from(Some("staging"), env("staging")), + Err(PostureError::InvalidEnvironment) + ); + } + + #[test] + fn error_codes_are_stable() { + assert_eq!( + PostureError::InvalidEnvironment.code(), + "platform.posture.invalid-value" + ); + assert_eq!( + PostureError::InvalidFlag.code(), + "platform.posture.invalid-value" + ); + assert_eq!(PostureError::Conflict.code(), "platform.posture.conflict"); + } + + #[test] + fn error_text_is_value_free_and_displayed() { + for error in [ + PostureError::InvalidEnvironment, + PostureError::InvalidFlag, + PostureError::Conflict, + ] { + assert_eq!(error.to_string(), error.message()); + assert!(!error.suggested_action().is_empty()); + } + assert_eq!( + PostureError::InvalidEnvironment.message(), + "REGISTRY_STACK_POSTURE is set to a value that is not a posture" + ); + assert_eq!( + PostureError::InvalidFlag.message(), + "--posture was given a value that is not a posture" + ); + assert_eq!( + PostureError::Conflict.message(), + "--posture and REGISTRY_STACK_POSTURE declare different postures" + ); + } + + #[test] + fn posture_spellings_round_trip() { + for posture in [Posture::Development, Posture::Production] { + assert_eq!(Posture::parse(posture.as_str()), Some(posture)); + } + assert_eq!(POSTURE_ENV, "REGISTRY_STACK_POSTURE"); + assert_eq!(POSTURE_FLAG, "posture"); + assert_eq!(POSTURE_HEADER, "registry-posture"); + } +} diff --git a/products/platform/README.md b/products/platform/README.md index 716aa81a2a..8a330b6e45 100644 --- a/products/platform/README.md +++ b/products/platform/README.md @@ -33,6 +33,7 @@ integration-test fixtures. | [`registry-platform-metrics`](../../crates/registry-platform-metrics/README.md) | Prometheus text exposition (format 0.0.4) writer and counter and histogram state with bounded, value-free label sets. | | [`registry-platform-objectstore`](../../crates/registry-platform-objectstore/README.md) | S3-compatible object storage and HTTP content verification transports, bound to a caller-supplied namespace, with fixed refusals and no retries. | | [`registry-platform-oidc`](../../crates/registry-platform-oidc/README.md) | OIDC discovery, JWKS caching, and JWT verifier configuration shared by registry services. | +| [`registry-platform-posture`](../../crates/registry-platform-posture/README.md) | The declared posture (development or production), the `REGISTRY_STACK_POSTURE` variable and `--posture` flag rules, and the refusals before any file is read; `std` only. | | [`registry-platform-ratelimit`](../../crates/registry-platform-ratelimit/README.md) | Bounded in-memory keyed rate limiting: a token bucket and a fixed window counter over opaque caller keys. | | [`registry-platform-resilience`](../../crates/registry-platform-resilience/README.md) | Bounded in-process resilience: the retry delay computation and a process-local circuit breaker state machine. | | [`registry-platform-sdjwt`](../../crates/registry-platform-sdjwt/README.md) | SD-JWT VC issuance, RFC 9901 presentation handling, and key-binding validation helpers. | From 28560fbeaacb6959436d4cac6c9390cb48b1b785 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:20:40 +0100 Subject: [PATCH 025/136] fix(platform): keep the crypto stack out of HTTP-only services and name each refused key httpsec's refusal trace id impl moves behind an opt-in refusal-trace-id feature, so a service that only serves HTTP, such as Discovery, no longer links authcommon and the crypto stack; CI runs that feature's test on the platform shard. A static key set refusal for a key of the wrong shape names its position, and an OKP refusal also names the key's kid and crv. The token corpus lists every private JWK member, a drift test holds the ThunderID tooling copy to the shared list, and adapterctl verify keeps the platform's remedy for an empty private range list. Signed-off-by: Jeremi Joslin --- .github/scripts/test_ci_changes.py | 25 ++++++ .github/workflows/ci.yml | 6 ++ crates/registry-adapter-core/src/checks.rs | 6 +- crates/registry-adapterctl/src/verify/mod.rs | 27 ++++++- crates/registry-platform-httpsec/Cargo.toml | 8 +- crates/registry-platform-httpsec/README.md | 5 +- .../registry-platform-httpsec/src/server.rs | 3 + crates/registry-platform-oidc/src/lib.rs | 76 +++++++++++++++++-- .../registry-platform-oidc/src/static_jwks.rs | 39 +++++++++- .../src/token_fixtures.rs | 19 ++++- .../tests/token_fixtures.rs | 12 ++- .../src/description.rs | 14 ++++ products/platform/CHANGELOG.md | 13 +++- 13 files changed, 226 insertions(+), 27 deletions(-) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 3771f79418..cb41dab10b 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -4271,6 +4271,31 @@ def test_platform_shard_runs_the_feature_gated_token_corpus_test(self) -> None: steps[0]["run"], ) + def test_platform_shard_runs_the_feature_gated_refusal_trace_id_test(self) -> None: + # No platform crate enables refusal-trace-id, so the shard's own run + # compiles httpsec without the impl and skips its test; this step runs it. + self.assertIn("registry-platform-httpsec", SHARDS["platform"]) + manifest = Path("crates/registry-platform-httpsec/Cargo.toml").read_text( + encoding="utf-8" + ) + self.assertIn('refusal-trace-id = ["server", "dep:registry-platform-authcommon"]', manifest) + steps = [ + step + for step in self.workflow_jobs["rust-tests"]["steps"] + if step.get("name") == "Test the refusal trace id implementation" + ] + self.assertEqual(1, len(steps)) + self.assertEqual( + "matrix.name == 'platform' && " + "contains(matrix.packages, 'registry-platform-httpsec')", + steps[0]["if"], + ) + self.assertEqual( + "cargo test --locked -p registry-platform-httpsec " + "--features refusal-trace-id --lib", + steps[0]["run"], + ) + def test_provisioning_changes_select_the_tls_postgres_lane(self) -> None: # The suite runs in the contracts-journeys lane, which review keeps. self.assertIn(PROVISION_POSTGRES_LANE, BREG_CONTRACTS_LANES[:2]) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ce555a0533..a8a19c89da 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -862,6 +862,12 @@ jobs: if: matrix.name == 'platform' && contains(matrix.packages, 'registry-platform-testing') run: cargo test --locked -p registry-platform-testing --features token-fixtures --test token_fixtures + # The refusal trace id impl sits behind refusal-trace-id, which no + # platform crate enables, so the shard's own run skips its test. + - name: Test the refusal trace id implementation + if: matrix.name == 'platform' && contains(matrix.packages, 'registry-platform-httpsec') + run: cargo test --locked -p registry-platform-httpsec --features refusal-trace-id --lib + - name: Check Casework schemas against their generators if: matrix.name == 'casework' run: products/casework/scripts/check-schemas.sh diff --git a/crates/registry-adapter-core/src/checks.rs b/crates/registry-adapter-core/src/checks.rs index 59b04b5691..9ad56c0bdc 100644 --- a/crates/registry-adapter-core/src/checks.rs +++ b/crates/registry-adapter-core/src/checks.rs @@ -7046,8 +7046,10 @@ pub fn plain_http_origin_admitted( .iter() .any(|cidr| cidr.contains(address)), // A named host resolves at send, where the same containment rule - // runs on the answers; the check cannot resolve, so it defers - // instead of refusing what the send admits. + // runs on the answers; the check cannot resolve, so it defers to the + // send. With an empty `allowedPrivateCidrs` the send admits no + // private address, and the destination policy refuses the origin + // when the runtime freezes it, naming the missing range. None => true, } } diff --git a/crates/registry-adapterctl/src/verify/mod.rs b/crates/registry-adapterctl/src/verify/mod.rs index 26349c968f..5cd983d52a 100644 --- a/crates/registry-adapterctl/src/verify/mod.rs +++ b/crates/registry-adapterctl/src/verify/mod.rs @@ -45,7 +45,7 @@ use registry_adapter_core::{ }; use registry_platform_config::{SecretProvider, SecretResolver}; use registry_platform_httputil::destination::{ - DataDestinationPolicy, DestinationProfile, DestinationTlsMaterial, + DataDestinationPolicy, DestinationPolicyError, DestinationProfile, DestinationTlsMaterial, MAX_DESTINATION_CA_BUNDLE_BYTES, }; use registry_platform_yaml::{Diagnostic, Report, SecretReference, Url}; @@ -833,9 +833,7 @@ fn destination_policy( profile, &networks, ) - .map_err(|_| { - EgressFault::Refused("the destination is not admitted by the frozen policy".to_owned()) - })?; + .map_err(|error| EgressFault::Refused(destination_refusal(&error)))?; if let Some(profile) = &binding.tls_trust_profile { let bundle = resolve_ca_bundle(runtime, profile.as_str()).map_err(|_| { EgressFault::Refused( @@ -856,6 +854,16 @@ fn destination_policy( Ok(policy) } +/// The report text for a refused destination. An empty private range list +/// keeps the platform's own text, which says how to fix it. Any other refusal +/// is a fixed sentence, so the report never repeats an origin. +fn destination_refusal(error: &DestinationPolicyError) -> String { + match error { + DestinationPolicyError::PrivateServiceRequiresPrivateCidr => error.to_string(), + _ => "the destination is not admitted by the frozen policy".to_owned(), + } +} + fn destination_profile(base: &Url) -> DestinationProfile { let parsed = base.to_url(); #[cfg(feature = "tls-test")] @@ -1173,6 +1181,17 @@ mod tests { ); } + #[test] + fn an_empty_private_range_list_keeps_the_platform_remedy() { + let message = + destination_refusal(&DestinationPolicyError::PrivateServiceRequiresPrivateCidr); + assert!(message.contains("name the range"), "{message}"); + assert_eq!( + destination_refusal(&DestinationPolicyError::OriginMissingPort), + "the destination is not admitted by the frozen policy" + ); + } + #[test] fn live_facade_probe_does_not_drive_evidence_extract_sends() { let pack: AdapterPack = serde_json::from_value( diff --git a/crates/registry-platform-httpsec/Cargo.toml b/crates/registry-platform-httpsec/Cargo.toml index 0d57340dba..9bbc8d0cb0 100644 --- a/crates/registry-platform-httpsec/Cargo.toml +++ b/crates/registry-platform-httpsec/Cargo.toml @@ -12,11 +12,8 @@ workspace = true [features] default = ["server"] -# `server` also implements authcommon's `RefusalTraceId` for `TraceId`, so a -# service passes its request trace id to `record_refusal!`. server = [ "dep:axum", - "dep:registry-platform-authcommon", "dep:tokio", "dep:tower", "dep:tower-http", @@ -24,6 +21,11 @@ server = [ "dep:url", ] +# Implements authcommon's `RefusalTraceId` for `TraceId`, so a service passes +# its request trace id to `record_refusal!`. Opt-in because authcommon reaches +# the crypto stack, which a service that only serves HTTP does not carry. +refusal-trace-id = ["server", "dep:registry-platform-authcommon"] + [[test]] name = "integration" required-features = ["server"] diff --git a/crates/registry-platform-httpsec/README.md b/crates/registry-platform-httpsec/README.md index 9120a34c8b..928febe62e 100644 --- a/crates/registry-platform-httpsec/README.md +++ b/crates/registry-platform-httpsec/README.md @@ -22,8 +22,9 @@ Client-safe HTTP validation plus Axum and Tower helpers for HTTP security. 422 framework bodies in the service's own problem vocabulary through a caller-supplied mapping from `FrameworkRejection`. - `TraceId` and `TraceContext`, the shared strict W3C `traceparent` transport - primitives for Registry service responses. With the `server` feature, - `TraceId` implements `registry_platform_authcommon::RefusalTraceId`, so a + primitives for Registry service responses. With the `refusal-trace-id` + feature, which pulls in `registry-platform-authcommon` and so the crypto + stack, `TraceId` implements `registry_platform_authcommon::RefusalTraceId`, so a service passes its request trace id to `record_refusal!`. - `loopback`, a re-export of `registry-platform-loopback`, the one definition of loopback for outbound destinations and loopback origins: diff --git a/crates/registry-platform-httpsec/src/server.rs b/crates/registry-platform-httpsec/src/server.rs index 9fc730bbd2..d4292bd0b3 100644 --- a/crates/registry-platform-httpsec/src/server.rs +++ b/crates/registry-platform-httpsec/src/server.rs @@ -105,7 +105,9 @@ fn parse_traceparent(value: &str) -> Option { // The request trace id is the one value `record_refusal!` takes from a request: // it is a validated W3C trace id, so it carries no other caller text. +#[cfg(feature = "refusal-trace-id")] impl registry_platform_authcommon::__refusal_trace_id_seal::Sealed for TraceId {} +#[cfg(feature = "refusal-trace-id")] impl registry_platform_authcommon::RefusalTraceId for TraceId {} fn fresh_span_id() -> String { @@ -809,6 +811,7 @@ mod tests { assert!(TraceId::parse("not-a-trace").is_err()); } + #[cfg(feature = "refusal-trace-id")] #[test] fn the_request_trace_id_is_the_one_a_refusal_line_takes() { use registry_platform_authcommon::{ diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index 235ff26efe..0c940a3b5b 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -472,14 +472,27 @@ impl fmt::Debug for JwksFetcher { /// A symmetric key, a private-key member or an unnamed key is refused here, /// at startup, rather than when a token first selects it. The rule on members /// is [`public_jwks_document`]. An OKP key passes that rule and is refused -/// here with [`StaticJwksError::OctetKeyPair`], which names its position. +/// here with [`StaticJwksError::OctetKeyPair`], which names its position, `kid` +/// and `crv`. A key with a member of the wrong shape is refused with +/// [`StaticJwksError::KeyShape`], which names its position. pub fn parse_static_jwks(bytes: &[u8]) -> Result { let document = public_jwks_document(bytes)?; - let okp = document["keys"] - .as_array() - .and_then(|keys| keys.iter().position(|key| key["kty"] == "OKP")); - if let Some(key) = okp { - return Err(StaticJwksError::OctetKeyPair { key }.into()); + let keys = document["keys"].as_array().into_iter().flatten(); + for (key, member) in keys.enumerate() { + if member["kty"] == "OKP" { + let label = |name: &str| member[name].as_str().map(str::to_owned); + return Err(StaticJwksError::OctetKeyPair { + key, + kid: label("kid"), + crv: label("crv"), + } + .into()); + } + // Parsing each key alone names the one a member of the wrong shape + // broke, which the whole-set parse below cannot. + if serde_json::from_value::(member.clone()).is_err() { + return Err(StaticJwksError::KeyShape { key }.into()); + } } let jwks: JwkSet = serde_json::from_value(document).map_err(|_| OidcError::Parse)?; let all_asymmetric = jwks.keys.iter().all(|key| { @@ -4923,13 +4936,60 @@ mod tests { assert!( matches!( error, - OidcError::StaticKeySet(StaticJwksError::OctetKeyPair { key: 1 }) + OidcError::StaticKeySet(StaticJwksError::OctetKeyPair { key: 1, .. }) ), "{error:?}" ); let text = error.to_string(); - assert!(text.contains("key 1 "), "{text}"); + assert!( + text.contains(r#"key 1 (kid "two", crv "Ed25519") is an OKP key"#), + "{text}" + ); assert!(text.contains("use an RSA or EC key"), "{text}"); assert!(error.is_key_source_unavailable()); } + + #[test] + fn an_okp_key_without_a_crv_is_named_by_kid_alone() { + let text = parse_static_jwks(br#"{"keys":[{"kty":"OKP","kid":"only","x":"AA"}]}"#) + .expect_err("an OKP key is refused") + .to_string(); + assert!( + text.contains(r#"key 0 (kid "only") is an OKP key"#), + "{text}" + ); + assert!(!text.contains("crv"), "{text}"); + } + + #[test] + fn an_okp_key_names_are_bounded_and_quoted() { + let long = "k".repeat(500); + let document = + format!(r#"{{"keys":[{{"kty":"OKP","kid":"{long}","crv":"a\nb","x":"AA"}}]}}"#); + let text = parse_static_jwks(document.as_bytes()) + .expect_err("an OKP key is refused") + .to_string(); + assert!(!text.contains(&long), "{text}"); + assert!(text.contains(r#"crv "a\nb""#), "{text}"); + assert!(text.len() < 400, "{}", text.len()); + } + + #[test] + fn a_key_of_the_wrong_shape_is_named_by_position() { + let error = parse_static_jwks( + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"RSA","kid":"two","n":5,"e":"AQAB"}]}"#, + ) + .expect_err("a key with a numeric modulus is refused"); + assert!( + matches!( + error, + OidcError::StaticKeySet(StaticJwksError::KeyShape { key: 1 }) + ), + "{error:?}" + ); + let text = error.to_string(); + assert!(text.contains("key 1 "), "{text}"); + assert!(!text.contains("two"), "{text}"); + assert!(error.is_key_source_unavailable()); + } } diff --git a/crates/registry-platform-oidc/src/static_jwks.rs b/crates/registry-platform-oidc/src/static_jwks.rs index 0efef00e7b..3eb3e87b5c 100644 --- a/crates/registry-platform-oidc/src/static_jwks.rs +++ b/crates/registry-platform-oidc/src/static_jwks.rs @@ -5,7 +5,9 @@ //! apart from the strict JSON rule that applies to the whole document: no //! repeated member name, and no integer a binary64 number cannot hold //! exactly. A refusal names the position of the key and the rule it broke, -//! never a `kid` or a member value. +//! never a member value. The one refusal that also names a key's `kid` and +//! `crv` is [`StaticJwksError::OctetKeyPair`], for a key the verifier would +//! otherwise load: both are public labels, quoted and bounded. use std::collections::BTreeSet; @@ -13,7 +15,7 @@ use registry_platform_crypto::{parse_json_strict, PRIVATE_JWK_MEMBERS}; use serde_json::Value; /// Why a static key set was refused. -#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] pub enum StaticJwksError { #[error("the document is not JSON, repeats a member name, or holds an integer that a 64-bit floating-point number cannot represent exactly")] @@ -36,8 +38,37 @@ pub enum StaticJwksError { MissingKeyId { key: usize }, #[error("key {key} repeats the \"kid\" of an earlier key; give every key its own \"kid\"")] RepeatedKeyId { key: usize }, - #[error("key {key} is an OKP key (\"kty\": \"OKP\"), which the token verifier does not load; use an RSA or EC key")] - OctetKeyPair { key: usize }, + #[error("key {key}{} is an OKP key (\"kty\": \"OKP\"), which the token verifier does not load; use an RSA or EC key", okp_labels(.kid, .crv))] + OctetKeyPair { + key: usize, + kid: Option, + crv: Option, + }, + #[error( + "key {key} is not a valid JSON Web Key: a member it needs is missing or has the wrong type" + )] + KeyShape { key: usize }, +} + +/// The longest `kid` or `crv` an OKP refusal repeats. +const MAX_LABEL_CHARS: usize = 64; + +/// ` (kid "...", crv "...")` for the labels a key has, quoted and cut to +/// [`MAX_LABEL_CHARS`], or nothing when it has neither. +fn okp_labels(kid: &Option, crv: &Option) -> String { + let labels: Vec = [("kid", kid), ("crv", crv)] + .into_iter() + .filter_map(|(name, value)| { + let value = value.as_deref()?; + let bounded: String = value.chars().take(MAX_LABEL_CHARS).collect(); + Some(format!("{name} {bounded:?}")) + }) + .collect(); + if labels.is_empty() { + String::new() + } else { + format!(" ({})", labels.join(", ")) + } } /// Check that `bytes` is a JSON Web Key Set that holds public keys only. diff --git a/crates/registry-platform-testing/src/token_fixtures.rs b/crates/registry-platform-testing/src/token_fixtures.rs index a452e8b64a..e1f90c6cb8 100644 --- a/crates/registry-platform-testing/src/token_fixtures.rs +++ b/crates/registry-platform-testing/src/token_fixtures.rs @@ -46,7 +46,7 @@ const EXPECTATIONS_FORMAT: FormatSpec<'static> = FormatSpec { }, removed_keys: &[], }; -const PRIVATE_JWK_MEMBERS: [&str; 7] = ["d", "p", "q", "dp", "dq", "qi", "k"]; +const PRIVATE_JWK_MEMBERS: [&str; 8] = ["d", "p", "q", "dp", "dq", "qi", "k", "oth"]; const SIGNING_ALGORITHMS: [&str; 5] = ["RS256", "ES256", "EdDSA", "HS256", "HS512"]; /// Why a corpus file did not load, validate, sign or run. @@ -1235,3 +1235,20 @@ fn finish(mut report: RowReport, observed: Option) -> RowReport { } report } + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + + #[test] + fn the_private_member_list_is_the_platform_list() { + assert_eq!( + super::PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>(), + registry_platform_crypto::PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>() + ); + } +} diff --git a/crates/registry-platform-testing/tests/token_fixtures.rs b/crates/registry-platform-testing/tests/token_fixtures.rs index 4e03790d8c..43e840dc79 100644 --- a/crates/registry-platform-testing/tests/token_fixtures.rs +++ b/crates/registry-platform-testing/tests/token_fixtures.rs @@ -15,7 +15,17 @@ use serde_json::{json, Value}; const ISSUER: &str = "https://issuer.example.test/realms/journey"; const AUDIENCE: &str = "https://api.example.test"; -const PRIVATE_JWK_MEMBERS: [&str; 7] = ["d", "p", "q", "dp", "dq", "qi", "k"]; +const PRIVATE_JWK_MEMBERS: [&str; 8] = ["d", "p", "q", "dp", "dq", "qi", "k", "oth"]; + +#[test] +fn the_private_member_list_is_the_platform_list() { + assert_eq!( + PRIVATE_JWK_MEMBERS.into_iter().collect::>(), + registry_platform_crypto::PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>() + ); +} fn corpus() -> TokenCorpus { TokenCorpus::load().expect("the corpus loads and validates") diff --git a/crates/registry-thunderid-tooling/src/description.rs b/crates/registry-thunderid-tooling/src/description.rs index 5a6ddb0ef5..718bb284b5 100644 --- a/crates/registry-thunderid-tooling/src/description.rs +++ b/crates/registry-thunderid-tooling/src/description.rs @@ -984,6 +984,20 @@ mod tests { description } + /// This crate keeps its own member list so the checks-only build links no + /// signing library. It must stay the platform's list. + #[test] + fn the_private_member_list_is_the_platform_list() { + assert_eq!( + PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>(), + registry_platform_crypto::PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>() + ); + } + #[test] fn a_machine_clients_jwks_may_carry_no_private_key_material() { for member in PRIVATE_JWK_MEMBERS { diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 906dab4af3..a04900e4ab 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- `registry-platform-httpsec` implements authcommon's `RefusalTraceId` for + `TraceId` behind the opt-in `refusal-trace-id` feature, not `server`. A + service that only serves HTTP no longer links `registry-platform-authcommon` + and the crypto stack. A service that passes its trace id to `record_refusal!` + enables the feature. + - A `test-support` feature in `registry-platform-provision` gives the product provision tests one verified-TLS superuser session, so they run against a TLS-only PostgreSQL server. It is enabled only by dev-dependencies. @@ -17,8 +23,11 @@ follows the strict JSON rule: an integer that a 64-bit floating-point number cannot hold exactly is refused as `StaticJwksError::NotJson`. `parse_static_jwks` refuses an OKP key with - `StaticJwksError::OctetKeyPair`, which names the key position and says to - use an RSA or EC key. + `StaticJwksError::OctetKeyPair`, which names the key position and its + `kid` and `crv` when it has them, and says to use an RSA or EC key. A key + with a member of the wrong shape is refused with + `StaticJwksError::KeyShape`, which names the key position. + `StaticJwksError` is no longer `Copy`. - One definition of loopback, the std-only `registry-platform-loopback` crate (re-exported as `registry_platform_httpsec::loopback` and From 11cd4a36e5df97c820fd422c0a9a0d902dad5e43 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:21:11 +0100 Subject: [PATCH 026/136] feat(platform): let a development-only value learn where it sits while it decodes registry-platform-yaml answers a DEVELOPMENT_ONLY newtype with the value's pointer and position through gated_site(), exactly for a node and as the holding mapping when serde decodes it from buffered content. The guards restore the previous site, so nested decodes and errors leave nothing behind. The changelog also records the posture crate. Signed-off-by: Jeremi Joslin --- crates/registry-platform-yaml/src/de.rs | 90 ++++++++++ crates/registry-platform-yaml/src/lib.rs | 2 +- .../tests/gated_site.rs | 168 ++++++++++++++++++ products/platform/CHANGELOG.md | 12 ++ 4 files changed, 271 insertions(+), 1 deletion(-) create mode 100644 crates/registry-platform-yaml/tests/gated_site.rs diff --git a/crates/registry-platform-yaml/src/de.rs b/crates/registry-platform-yaml/src/de.rs index 01007ad9f3..d09814ff13 100644 --- a/crates/registry-platform-yaml/src/de.rs +++ b/crates/registry-platform-yaml/src/de.rs @@ -36,6 +36,65 @@ pub(crate) const DATA_LITERAL: &str = "\0registry-platform-yaml/data-literal"; /// `expecting` text carries the bounds. pub(crate) const BOUNDED: &str = "\0registry-platform-yaml/bounded"; pub(crate) const BOUNDED_EXPECTING: &str = "a whole number from "; +/// The newtype name a development-only setting asks for. A deserializer +/// that handles it records where the value sits for [`gated_site`] while the +/// value decodes. +pub const DEVELOPMENT_ONLY: &str = "\0registry-platform-yaml/development-only"; + +/// Where a development-only value sits in the document. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GatedSite { + /// The RFC 6901 pointer from the document root. + pub pointer: String, + /// Where the value starts in the file. + pub position: Option, + /// True when the pointer names the value itself. False when the value + /// was decoded from buffered content (under `#[serde(flatten)]` or an + /// untagged enum): the pointer then names the mapping that holds it, and + /// the caller appends the member's own key. + pub exact: bool, +} + +thread_local! { + static EXACT_SITE: RefCell> = const { RefCell::new(None) }; + static MAPPING_SITE: RefCell> = const { RefCell::new(None) }; +} + +/// Restores the previous value of a site cell when dropped, so nested +/// decodes and panics leave the cell as they found it. +struct SiteGuard { + cell: &'static std::thread::LocalKey>>, + previous: Option, +} + +impl SiteGuard { + fn set( + cell: &'static std::thread::LocalKey>>, + site: Option, + ) -> SiteGuard { + let previous = cell.with(|current| current.replace(site)); + SiteGuard { cell, previous } + } +} + +impl Drop for SiteGuard { + fn drop(&mut self) { + let previous = self.previous.take(); + self.cell.with(|current| *current.borrow_mut() = previous); + } +} + +/// The site of the development-only value being decoded, read by the +/// `Deserialize` code that asked for [`DEVELOPMENT_ONLY`]. `None` outside a +/// reader decode. +/// +/// When the value decodes from buffered content the reader never sees it as +/// a node, so the site is the innermost mapping with `exact: false`. +pub fn gated_site() -> Option { + EXACT_SITE + .with(|site| site.borrow().clone()) + .or_else(|| MAPPING_SITE.with(|site| site.borrow().clone())) +} /// A field renamed to a name starting with this prefix holds a platform /// shared block: the block's members sit beside the host's own, in the same @@ -514,6 +573,21 @@ impl<'a> NodeDe<'a> { item } + /// Record this mapping as the innermost one for [`gated_site`], and hide + /// the enclosing value's exact site: a value decoded from buffered + /// content inside this mapping is not that value. + fn enter_mapping(&self) -> (SiteGuard, SiteGuard) { + let mapping = SiteGuard::set( + &MAPPING_SITE, + Some(GatedSite { + pointer: self.site.path.clone(), + position: self.site.value_at(), + exact: false, + }), + ); + (mapping, SiteGuard::set(&EXACT_SITE, None)) + } + /// Run one deserializer method, placing any error that has no position /// yet at this node. fn run( @@ -1159,6 +1233,7 @@ impl<'de, 'a> de::Deserializer<'de> for NodeDe<'a> { if let Some(tag) = name.strip_prefix(TAGGED_PREFIX) { return self.run(false, |de| { de.mapping()?; + let _mapping = de.enter_mapping(); visitor.visit_enum(TaggedAccess { de: de.clone(), tag, @@ -1209,6 +1284,19 @@ impl<'de, 'a> de::Deserializer<'de> for NodeDe<'a> { } }); } + if name == DEVELOPMENT_ONLY { + return self.run(false, |de| { + let _site = SiteGuard::set( + &EXACT_SITE, + Some(GatedSite { + pointer: de.site.path.clone(), + position: de.site.value_at(), + exact: true, + }), + ); + visitor.visit_newtype_struct(de.clone()) + }); + } if name == BOUNDED { let expecting = Expecting(&visitor).to_string(); let bounds = parse_bounds(&expecting); @@ -1254,6 +1342,7 @@ impl<'de, 'a> de::Deserializer<'de> for NodeDe<'a> { )); } let entries = de.mapping()?; + let _mapping = de.enter_mapping(); visitor.visit_map(MapAccess::new(de, entries)) }) } @@ -1266,6 +1355,7 @@ impl<'de, 'a> de::Deserializer<'de> for NodeDe<'a> { ) -> Result { self.run(true, |de| { let entries = de.mapping()?; + let _mapping = de.enter_mapping(); let mut access = StructAccess::new(de, entries, fields); let result = visitor.visit_map(&mut access); access.finish(); diff --git a/crates/registry-platform-yaml/src/lib.rs b/crates/registry-platform-yaml/src/lib.rs index f07438ddd4..7eb29fa819 100644 --- a/crates/registry-platform-yaml/src/lib.rs +++ b/crates/registry-platform-yaml/src/lib.rs @@ -127,7 +127,7 @@ pub use check_acceptances::{ CHECK_ACCEPTANCES_API_VERSION, CHECK_ACCEPTANCES_FILE, CHECK_ACCEPTANCES_FORMAT, CHECK_ACCEPTANCES_KIND, CHECK_ACCEPTANCES_SCHEMA_ID, }; -pub use de::{Invalid, SHARED_BLOCK_PREFIX}; +pub use de::{gated_site, GatedSite, Invalid, DEVELOPMENT_ONLY, SHARED_BLOCK_PREFIX}; pub use diagnostic::{Diagnostic, Related, Report, Severity, Source}; pub use document::{ decode_document, read_document, Decoded, Document, Reader, MAXIMUM_DIAGNOSTICS_PER_FILE, diff --git a/crates/registry-platform-yaml/tests/gated_site.rs b/crates/registry-platform-yaml/tests/gated_site.rs new file mode 100644 index 0000000000..fd892238c7 --- /dev/null +++ b/crates/registry-platform-yaml/tests/gated_site.rs @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: Apache-2.0 +//! A development-only newtype learns where it sits in the document. +mod common; + +use common::{codes, decode, refusal}; +use registry_platform_yaml::{gated_site, tagged_union, GatedSite, DEVELOPMENT_ONLY}; +use serde::de::{Deserializer, Visitor}; +use serde::Deserialize; + +/// A stand-in for a gate type: it asks for `DEVELOPMENT_ONLY`, reads the site +/// before it decodes the value, and keeps it. +#[derive(Debug)] +struct Probe { + site: Option, +} + +impl<'de> Deserialize<'de> for Probe { + fn deserialize>(deserializer: D) -> Result { + struct Reads; + impl<'de> Visitor<'de> for Reads { + type Value = Probe; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a probed value") + } + fn visit_newtype_struct>( + self, + inner: D, + ) -> Result { + let site = gated_site(); + bool::deserialize(inner)?; + Ok(Probe { site }) + } + } + deserializer.deserialize_newtype_struct(DEVELOPMENT_ONLY, Reads) + } +} + +fn site(pointer: &str, exact: bool) -> (String, bool) { + (pointer.to_string(), exact) +} + +fn seen(probe: &Probe) -> (String, bool) { + let site = probe.site.as_ref().expect("the reader sets the site"); + assert!(site.position.is_some(), "the site carries a position"); + (site.pointer.clone(), site.exact) +} + +#[derive(Debug, Deserialize)] +struct Inner { + b: Probe, +} + +#[derive(Debug, Deserialize)] +struct Outer { + a: Inner, +} + +#[derive(Debug, Deserialize)] +struct Listed { + a: Vec, +} + +#[test] +fn a_member_has_an_exact_pointer() { + let read: Outer = decode("a:\n b: true\n").unwrap(); + assert_eq!(seen(&read.a.b), site("/a/b", true)); +} + +#[test] +fn a_list_item_has_an_exact_pointer() { + let read: Listed = decode("a:\n - b: true\n").unwrap(); + assert_eq!(seen(&read.a[0].b), site("/a/0/b", true)); +} + +#[derive(Debug, Deserialize)] +#[serde( + remote = "Self", + rename_all = "kebab-case", + rename_all_fields = "camelCase" +)] +enum Source { + Http { gate: Probe }, + None {}, +} +tagged_union!(Source); + +#[derive(Debug, Deserialize)] +struct Sourced { + source: Source, +} + +#[test] +fn a_member_of_a_tagged_union_variant_has_an_exact_pointer() { + let read: Sourced = decode("source:\n type: http\n gate: true\n").unwrap(); + let Source::Http { gate } = read.source else { + panic!("an http source"); + }; + assert_eq!(seen(&gate), site("/source/gate", true)); +} + +#[derive(Debug, Deserialize)] +struct Flattened { + #[serde(flatten)] + shared: Shared, +} + +#[derive(Debug, Deserialize)] +struct Shared { + allow: Probe, +} + +#[derive(Debug, Deserialize)] +struct Host { + issuer: Flattened, +} + +#[test] +fn under_flatten_the_site_is_the_parent_mapping_and_inexact() { + let read: Host = decode("issuer:\n allow: true\n").unwrap(); + assert_eq!(seen(&read.issuer.shared.allow), site("/issuer", false)); +} + +#[test] +fn the_site_is_cleared_after_a_decode_and_after_a_decode_error() { + assert_eq!(gated_site(), None); + let _: Outer = decode("a:\n b: true\n").unwrap(); + assert_eq!(gated_site(), None); + let _: Host = decode("issuer:\n allow: true\n").unwrap(); + assert_eq!(gated_site(), None); + let report = refusal::("a:\n b: true\n extra: 1\n"); + assert_eq!(codes(&report), ["config.unknown-key"]); + assert_eq!(gated_site(), None); + let report = refusal::("a:\n b: 7\n"); + assert_eq!(codes(&report), ["config.expected-boolean"]); + assert_eq!(gated_site(), None); +} + +#[test] +fn a_panic_while_the_site_is_set_restores_the_previous_site() { + #[derive(Debug)] + struct Boom; + impl<'de> Deserialize<'de> for Boom { + fn deserialize>(deserializer: D) -> Result { + struct Panics; + impl<'de> Visitor<'de> for Panics { + type Value = Boom; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a value") + } + fn visit_newtype_struct>( + self, + _: D, + ) -> Result { + assert!(gated_site().is_some()); + panic!("a decoder bug"); + } + } + deserializer.deserialize_newtype_struct(DEVELOPMENT_ONLY, Panics) + } + } + #[derive(Debug, Deserialize)] + struct Wrapper { + _a: Boom, + } + let result = std::panic::catch_unwind(|| decode::("_a: true\n")); + assert!(result.is_err()); + assert_eq!(gated_site(), None); +} diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index a04900e4ab..2eeaca5b38 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- `registry-platform-posture`, a `std`-only crate, holds `Posture`, + `PostureSource`, `DeclaredPosture`, `PostureError` and + `declared_from`/`declared`, which read the `--posture` flag and the + `REGISTRY_STACK_POSTURE` variable. Unset means production. A value that is + not a posture, or a flag and variable that disagree, is refused before any + file is read. No product reads it yet. + +- `registry-platform-yaml` exports `DEVELOPMENT_ONLY`, `GatedSite` and + `gated_site()`, which let a development-only value learn its pointer and + position while the reader decodes it: exact for a node, and the holding + mapping with `exact: false` under `#[serde(flatten)]`. + - `registry-platform-httpsec` implements authcommon's `RefusalTraceId` for `TraceId` behind the opt-in `refusal-trace-id` feature, not `server`. A service that only serves HTTP no longer links `registry-platform-authcommon` From 9f1b89a61f8e93bf0ab829ec268eae1f9e67676e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:24:36 +0100 Subject: [PATCH 027/136] feat(adapter): grant the runtime role its table privileges at startup When the runtime and migration sessions run as different roles, adapter serve migrates, connects as the runtime role, and grants that session's role the table privileges its deployment needs, in one transaction under an advisory lock, then checks them before it listens. The grantee is the role the runtime session proves, never a URL's text. It grants only what is missing, never revokes, and makes no grant to a role whose privileges other members would inherit, apart from a leaf administrator holding ADMIN OPTION. Configuration refusals run before any grant. Payment and G2P tables stay hand-granted, and the operate page lists them. Signed-off-by: Jeremi Joslin --- crates/registry-adapter/src/serve.rs | 414 ++++++++-- .../postgres_journal_retention_served.rs | 721 +++++++++++++++--- .../site/src/content/docs/operate/adapter.mdx | 76 +- products/adapter/CHANGELOG.md | 17 + 4 files changed, 1071 insertions(+), 157 deletions(-) diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index f03ec46a64..b2abda2a61 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -672,6 +672,251 @@ pub async fn run_configured( } } +/// The table privileges the runtime role needs for a deployment, by table: +/// the journal and the migration ledger always, idempotency state when it +/// serves a write, the artifact fence when it declares an asynchronous or +/// resumable write, and the checkpoint bindings when it declares a resumable +/// write. Startup grants those the runtime role lacks and then checks them all. +fn runtime_requirements( + serves_write: bool, + declares_recovery: bool, + declares_resume: bool, +) -> Vec<(&'static str, &'static [&'static str])> { + let mut required: Vec<(&'static str, &'static [&'static str])> = vec![ + ("adapter_journal_events", &journal::RUNTIME_PRIVILEGES), + ("adapter_schema_migrations", &["SELECT"]), + ]; + if serves_write { + required.extend(idempotent::WRITE_RUNTIME_GRANTS); + } + if declares_recovery { + required.push(idempotent::RECOVERY_RUNTIME_GRANTS); + } + if declares_resume { + required.push(idempotent::RESUME_RUNTIME_GRANTS); + } + required +} + +/// The advisory-lock key the grant step holds for its transaction, so +/// replicas starting together do not rewrite the same catalog rows at once. +/// Its ASCII bytes spell `adap_gnt`. +const GRANT_LOCK_KEY: i64 = 0x6164_6170_5f67_6e74; + +/// A PostgreSQL identifier, quoted. +fn quote_identifier(identifier: &str) -> String { + format!("\"{}\"", identifier.replace('"', "\"\"")) +} + +/// The server's own message for a failed statement, without its position or +/// the statement text. +fn database_message(error: &tokio_postgres::Error) -> String { + error + .as_db_error() + .map_or_else(|| error.to_string(), |db| db.message().to_owned()) +} + +fn grant_error(error: &tokio_postgres::Error) -> ServeError { + ServeError::Configuration(format!("database grants: {}", database_message(error))) +} + +/// The `privileges` that `grantee` lacks on `relation` (an already-quoted, +/// schema-qualified name), in the given order; all of them when the relation +/// does not exist. +async fn missing_for( + transaction: &tokio_postgres::Transaction<'_>, + grantee: &str, + relation: &str, + privileges: &[&'static str], +) -> Result, tokio_postgres::Error> { + let names = privileges.to_vec(); + let held = transaction + .query( + "SELECT coalesce(has_table_privilege($1, to_regclass($2), privilege), false) \ + FROM unnest($3::text[]) WITH ORDINALITY AS wanted(privilege, position) \ + ORDER BY position", + &[&grantee, &relation, &names], + ) + .await?; + Ok(privileges + .iter() + .zip(held.iter()) + .filter(|(_, row)| !row.get::<_, bool>(0)) + .map(|(privilege, _)| *privilege) + .collect()) +} + +/// Everything `grantee` still lacks of `required` and of `USAGE` on `schema`, +/// as "PRIVILEGES on object" phrases. +async fn lacking( + transaction: &tokio_postgres::Transaction<'_>, + grantee: &str, + schema: &str, + required: &[(&'static str, &'static [&'static str])], +) -> Result, tokio_postgres::Error> { + let mut lacking = Vec::new(); + for (table, privileges) in required { + let missing = missing_for( + transaction, + grantee, + &format!("{schema}.{table}"), + privileges, + ) + .await?; + if !missing.is_empty() { + lacking.push(format!("{} on {table}", missing.join(", "))); + } + } + let usage: bool = transaction + .query_one( + "SELECT has_schema_privilege($1, current_schema(), 'USAGE')", + &[&grantee], + ) + .await? + .get(0); + if !usage { + lacking.push(format!("USAGE on schema {schema}")); + } + Ok(lacking) +} + +/// Grant `grantee`, the runtime session's own role, each privilege in +/// `required` it lacks and `USAGE` on the schema the migrations ran in, from +/// the migration session in one transaction under an advisory lock. A start +/// that finds everything in place issues no GRANT. Nothing beyond `required` +/// is granted: no default privileges, no grant on the idempotency migration +/// ledger. +/// +/// When something is missing and the role has members, no grant is made, +/// because they would inherit it: the privilege check that follows then +/// decides, as it does for a hand-granted deployment. A member that holds +/// ADMIN OPTION on the role and has no members of its own does not count. It +/// already controls the role, as the role that created it does when +/// `adapterctl provision` runs. PostgreSQL ignores or refuses a GRANT the +/// migration role has no right to make, so each privilege is checked again +/// before the commit, and a shortfall rolls everything back. +/// +/// Returns whether `grantee` ends holding everything `required` names: false +/// when the members rule made no grant. +async fn grant_runtime_privileges( + client: &mut deadpool_postgres::Client, + grantee: &str, + required: &[(&'static str, &'static [&'static str])], +) -> Result { + let transaction = client.transaction().await.map_err(|e| grant_error(&e))?; + transaction + .query_one("SELECT pg_advisory_xact_lock($1)", &[&GRANT_LOCK_KEY]) + .await + .map_err(|e| grant_error(&e))?; + let schema: Option = transaction + .query_one("SELECT quote_ident(current_schema())", &[]) + .await + .map_err(|e| grant_error(&e))? + .get(0); + let schema = schema.ok_or_else(|| { + ServeError::Configuration( + "database: the migration role's search path names no schema to grant USAGE on" + .to_owned(), + ) + })?; + let missing = lacking(&transaction, grantee, &schema, required) + .await + .map_err(|e| grant_error(&e))?; + if missing.is_empty() { + transaction.rollback().await.map_err(|e| grant_error(&e))?; + return Ok(true); + } + let has_members: bool = transaction + .query_one( + "SELECT EXISTS (SELECT 1 FROM pg_auth_members m \ + JOIN pg_roles r ON r.oid = m.roleid \ + WHERE r.rolname = $1 \ + AND m.member NOT IN (SELECT a.member FROM pg_auth_members a \ + WHERE a.roleid = r.oid AND a.admin_option \ + AND NOT EXISTS (SELECT 1 FROM pg_auth_members g \ + WHERE g.roleid = a.member)))", + &[&grantee], + ) + .await + .map_err(|e| grant_error(&e))? + .get(0); + if has_members { + tracing::warn!( + role = grantee, + "the runtime role has members, so no privilege is granted to it automatically" + ); + transaction.rollback().await.map_err(|e| grant_error(&e))?; + return Ok(false); + } + let mut granted = 0_usize; + let quoted_grantee = quote_identifier(grantee); + for (table, privileges) in required { + let missing = missing_for( + &transaction, + grantee, + &format!("{schema}.{table}"), + privileges, + ) + .await + .map_err(|e| grant_error(&e))?; + if missing.is_empty() { + continue; + } + granted += missing.len(); + let missing = missing.join(", "); + transaction + .batch_execute(&format!( + "GRANT {missing} ON TABLE {schema}.{table} TO {quoted_grantee}" + )) + .await + .map_err(|error| { + ServeError::Configuration(format!( + "database: could not grant {missing} on {table} to the runtime role: {}", + database_message(&error) + )) + })?; + } + let usage: bool = transaction + .query_one( + "SELECT has_schema_privilege($1, current_schema(), 'USAGE')", + &[&grantee], + ) + .await + .map_err(|e| grant_error(&e))? + .get(0); + if !usage { + granted += 1; + transaction + .batch_execute(&format!( + "GRANT USAGE ON SCHEMA {schema} TO {quoted_grantee}" + )) + .await + .map_err(|error| { + ServeError::Configuration(format!( + "database: could not grant USAGE on schema {schema} to the runtime role: {}", + database_message(&error) + )) + })?; + } + let still_lacking = lacking(&transaction, grantee, &schema, required) + .await + .map_err(|e| grant_error(&e))?; + if !still_lacking.is_empty() { + transaction.rollback().await.map_err(|e| grant_error(&e))?; + return Err(ServeError::Configuration(format!( + "database: after its grants the runtime role still lacks {}; PostgreSQL ignores or refuses a grant the migration role has no right to make, most likely because the migration role does not own the object, so the grants were rolled back (https://docs.registrystack.org/operate/adapter/#grant-the-runtime-database-role says what to grant by hand)", + still_lacking.join("; lacks ") + ))); + } + transaction.commit().await.map_err(|e| grant_error(&e))?; + tracing::info!( + role = grantee, + privileges = granted, + "granted the runtime role the privileges it lacked" + ); + Ok(true) +} + async fn run_facade( project_directory: &std::path::Path, profile_path: Option<&std::path::Path>, @@ -738,8 +983,42 @@ async fn run_facade( .to_owned(), )); } + let declares_recovery = loaded + .served + .iter() + .any(|served| served.async_completion.is_some() || served.resume.is_some()); + let declares_resume = loaded.served.iter().any(|served| served.resume.is_some()); + // A configuration this refuses grants nothing: it settles before any + // database work. + let response_retention_seconds = if serves_write { + let retention = loaded.runtime.idempotency.ok_or_else(|| { + ServeError::Configuration( + "idempotency.responseRetentionSeconds is required when a write is served" + .to_owned(), + ) + })?; + let seconds = retention.response_retention_seconds.get(); + if loaded.served.iter().any(|served| { + served + .write_support + .as_ref() + .is_some_and(|support| source_replay_window_seconds(support) < seconds) + }) { + return Err(ServeError::Configuration( + "a source write replay window is shorter than idempotency.responseRetentionSeconds; increase the source replayWindowSeconds or reduce response retention" + .to_owned(), + )); + } + Some(seconds) + } else { + None + }; let shutdown = shutdown_signal()?; let migration = pool(&loaded.runtime.database, &loaded.resolver, true)?; + let journal = pool(&loaded.runtime.database, &loaded.resolver, false)?; + // Whether the grant step found the runtime role holding everything the + // deployment requires in the schema the migrations ran in. + let mut grants_verified = false; { let mut client = migration .get() @@ -751,13 +1030,32 @@ async fn run_facade( idempotent::migrate(&mut client).await.map_err(|error| { ServeError::Configuration(format!("idempotency migration: {error}")) })?; + // The grantee is the role the runtime session proves it holds, read + // before any grant: a runtime URL naming `public`, a role that cannot + // log in or a wrong password fails here, and the URL's text never + // chooses who receives privileges. + let runtime_role: String = journal + .get() + .await + .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))? + .query_one("SELECT current_user::text", &[]) + .await + .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))? + .get(0); + let migration_role: String = client + .query_one("SELECT current_user::text", &[]) + .await + .map_err(|error| ServeError::Configuration(format!("database: {error}")))? + .get(0); + if runtime_role != migration_role { + grants_verified = grant_runtime_privileges( + &mut client, + &runtime_role, + &runtime_requirements(serves_write, declares_recovery, declares_resume), + ) + .await?; + } } - let journal = pool(&loaded.runtime.database, &loaded.resolver, false)?; - let declares_recovery = loaded - .served - .iter() - .any(|served| served.async_completion.is_some() || served.resume.is_some()); - let declares_resume = loaded.served.iter().any(|served| served.resume.is_some()); { // A runtime role that lacks a grant this deployment uses is refused // here, not at its first journal write, write claim or retention tick. @@ -765,19 +1063,7 @@ async fn run_facade( .get() .await .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))?; - let mut required: Vec<(&str, &[&'static str])> = vec![ - ("adapter_journal_events", &journal::RUNTIME_PRIVILEGES), - ("adapter_schema_migrations", &["SELECT"]), - ]; - if serves_write { - required.extend(idempotent::WRITE_RUNTIME_GRANTS); - } - if declares_recovery { - required.push(idempotent::RECOVERY_RUNTIME_GRANTS); - } - if declares_resume { - required.push(idempotent::RESUME_RUNTIME_GRANTS); - } + let required = runtime_requirements(serves_write, declares_recovery, declares_resume); let mut lacking = Vec::new(); for (table, privileges) in required { let missing = journal::missing_table_privileges(&client, table, privileges) @@ -790,44 +1076,26 @@ async fn run_facade( } } if !lacking.is_empty() { + let remedy = if grants_verified { + "the role holds them in the schema the migrations ran in, so the runtime session's search path most likely resolves a different schema; point the runtime database URL's search path at the migration schema" + } else { + "grant them to the runtime role" + }; return Err(ServeError::Configuration(format!( - "database: the runtime role lacks {}; grant them to the runtime role (https://docs.registrystack.org/operate/adapter/#grant-the-runtime-database-role lists every grant)", + "database: the runtime role lacks {}; {remedy} (https://docs.registrystack.org/operate/adapter/#grant-the-runtime-database-role lists every grant)", lacking.join("; lacks "), ))); } } let journal_window = journal_retention(loaded.runtime.audit.retention_days.get()); let journal_sweep_pool = journal.clone(); - let idempotency = match (serves_write, loaded.runtime.idempotency) { - (true, Some(retention)) => { - let response_retention_seconds = retention.response_retention_seconds.get(); - if loaded.served.iter().any(|served| { - served.write_support.as_ref().is_some_and(|support| { - source_replay_window_seconds(support) < response_retention_seconds - }) - }) { - return Err(ServeError::Configuration( - "a source write replay window is shorter than idempotency.responseRetentionSeconds; increase the source replayWindowSeconds or reduce response retention" - .to_owned(), - )); - } - Some(( - PostgresIdempotencyStore::new( - journal.clone(), - Duration::from_secs(response_retention_seconds), - ) - .map_err(|error| ServeError::Configuration(format!("idempotency: {error}")))?, - Duration::from_secs(response_retention_seconds), - )) - } - (true, None) => { - return Err(ServeError::Configuration( - "idempotency.responseRetentionSeconds is required when a write is served" - .to_owned(), - )); - } - (false, _) => None, - }; + let idempotency = response_retention_seconds + .map(|seconds| { + PostgresIdempotencyStore::new(journal.clone(), Duration::from_secs(seconds)) + .map(|store| (store, Duration::from_secs(seconds))) + .map_err(|error| ServeError::Configuration(format!("idempotency: {error}"))) + }) + .transpose()?; let artifact_digest = loaded_artifact_digest(&loaded.deployment)?; // Only a deployment that declares an asynchronous or resumable write // touches the durable artifact fence. Activation advances it and is @@ -1005,6 +1273,52 @@ mod token_characterisation; mod tests { use super::*; + #[test] + fn runtime_requirements_follow_the_deployment_feature_set() { + const JOURNAL: (&str, &[&str]) = + ("adapter_journal_events", &["INSERT", "SELECT", "DELETE"]); + const LEDGER: (&str, &[&str]) = ("adapter_schema_migrations", &["SELECT"]); + const ENTRIES: (&str, &[&str]) = ( + "adapter_idempotency_entries", + &["SELECT", "INSERT", "UPDATE", "DELETE"], + ); + const RESUMES: (&str, &[&str]) = ( + "adapter_idempotency_resumes", + &["SELECT", "INSERT", "UPDATE", "DELETE"], + ); + const ARTIFACTS: (&str, &[&str]) = ( + "adapter_idempotency_async_artifacts", + &["SELECT", "INSERT", "UPDATE"], + ); + const BINDINGS: (&str, &[&str]) = + ("adapter_idempotency_resume_bindings", &["SELECT", "INSERT"]); + assert_eq!(runtime_requirements(false, false, false), [JOURNAL, LEDGER]); + assert_eq!( + runtime_requirements(true, false, false), + [JOURNAL, LEDGER, ENTRIES, RESUMES] + ); + assert_eq!( + runtime_requirements(true, true, false), + [JOURNAL, LEDGER, ENTRIES, RESUMES, ARTIFACTS] + ); + assert_eq!( + runtime_requirements(true, true, true), + [JOURNAL, LEDGER, ENTRIES, RESUMES, ARTIFACTS, BINDINGS] + ); + assert!(runtime_requirements(true, true, true) + .iter() + .all(|(table, _)| *table != "adapter_idempotency_schema_migrations")); + } + + #[test] + fn a_role_name_is_quoted_as_one_identifier() { + assert_eq!(quote_identifier("runtime"), "\"runtime\""); + assert_eq!( + quote_identifier("a\"; DROP ROLE x; --"), + "\"a\"\"; DROP ROLE x; --\"" + ); + } + #[test] fn a_metrics_shutdown_timeout_is_not_fatal_but_other_faults_are() { let timed_out = std::io::Error::new(std::io::ErrorKind::TimedOut, "stalled client"); diff --git a/crates/registry-adapter/tests/postgres_journal_retention_served.rs b/crates/registry-adapter/tests/postgres_journal_retention_served.rs index a5778e1e92..019466bd3c 100644 --- a/crates/registry-adapter/tests/postgres_journal_retention_served.rs +++ b/crates/registry-adapter/tests/postgres_journal_retention_served.rs @@ -2,8 +2,11 @@ //! Journal retention through the real Adapter binary: a served deployment, //! read-only or write, deletes journal events older than -//! `audit.retentionDays` and keeps the ones inside the window, and a -//! runtime role that cannot run those deletes is refused at startup. +//! `audit.retentionDays` and keeps the ones inside the window. The same +//! suite covers the runtime role's grants: a split role starts with none and +//! ends with exactly the privileges its deployment requires, a single role +//! issues no grant, a runtime URL that does not connect stops startup before +//! any grant, and a grant the migration role cannot make stops it with the cause. //! Absence of `ADAPTER_TEST_DATABASE_URL` is a failure, never a skip. #![cfg(feature = "postgres-test")] @@ -308,169 +311,693 @@ fn as_role(database: &str, role: &str) -> String { format!("{scheme}://{role}:{RUNTIME_PASSWORD}@{host}") } +/// A login role the test creates in the shared database, dropped with its +/// owned objects when the test ends. +async fn create_login_role(database: &str, role: &str) { + execute( + database, + &format!("CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}';"), + ) + .await; +} + +async fn drop_role(database: &str, role: &str) { + execute( + database, + &format!("DROP OWNED BY {role}; DROP ROLE {role};"), + ) + .await; +} + +async fn current_schema(database: &str) -> String { + connect(database) + .await + .query_one("SELECT current_schema()", &[]) + .await + .expect("read the migrated schema") + .get(0) +} + #[tokio::test] -async fn a_runtime_role_without_delete_is_refused_and_insert_select_delete_serves() { +async fn a_split_runtime_role_with_no_grants_is_granted_what_it_needs_and_runs_retention() { let upstream = UpstreamDouble::start(); let database = migrated_schema(&upstream, &Served::govstack_project(), "govstack-grants").await; - let schema: String = connect(&database) + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; + seed(&database).await; + let runtime_url = as_role(&database, &role); + + let mut serving = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + serving.wait_until_listening(); + await_retention(&database).await; + drop(serving); + drop_role(&database, &role).await; +} + +/// The privileges `role` holds on every table of `schema`, by table, for the +/// seven table privileges PostgreSQL defines. Tables with none are omitted. +async fn table_privileges( + database: &str, + schema: &str, + role: &str, +) -> std::collections::BTreeMap> { + let rows = connect(database) .await - .query_one("SELECT current_schema()", &[]) + .query( + "SELECT c.relname, p.privilege \ + FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + CROSS JOIN unnest(ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', \ + 'REFERENCES', 'TRIGGER']) AS p(privilege) \ + WHERE n.nspname = $1 AND c.relkind IN ('r', 'p') \ + AND has_table_privilege($2, c.oid, p.privilege) \ + ORDER BY c.relname, p.privilege", + &[&schema, &role], + ) .await - .expect("read the migrated schema") - .get(0); + .expect("read the role's table privileges"); + let mut held = std::collections::BTreeMap::>::new(); + for row in rows { + held.entry(row.get(0)).or_default().push(row.get(1)); + } + held +} + +/// Every role that holds a privilege on a table or sequence of `schema` or on +/// the schema itself without owning it, by name, with `PUBLIC` for the +/// pseudo-role. A grantee that may pass the privilege on reads +/// ` WITH GRANT OPTION`. Unlike `has_table_privilege`, this reads the +/// ACLs, so a grant to `PUBLIC` is not mistaken for a grant to one role. +async fn acl_grantees(database: &str, schema: &str) -> std::collections::BTreeSet { + connect(database) + .await + .query( + "SELECT (CASE a.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END) \ + || (CASE WHEN a.is_grantable THEN ' WITH GRANT OPTION' ELSE '' END) \ + FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + CROSS JOIN LATERAL aclexplode(c.relacl) a \ + WHERE n.nspname = $1 AND c.relkind IN ('r', 'p', 'S') AND a.grantee <> c.relowner \ + UNION \ + SELECT (CASE a.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END) \ + || (CASE WHEN a.is_grantable THEN ' WITH GRANT OPTION' ELSE '' END) \ + FROM pg_namespace n \ + CROSS JOIN LATERAL aclexplode(n.nspacl) a \ + WHERE n.nspname = $1 AND a.grantee <> n.nspowner", + &[&schema], + ) + .await + .expect("read the ACL grantees") + .iter() + .map(|row| row.get::<_, String>(0)) + .collect() +} + +fn expected(grants: &[(&str, &[&str])]) -> std::collections::BTreeMap> { + grants + .iter() + .map(|(table, privileges)| { + let mut privileges: Vec = privileges.iter().map(|p| (*p).to_owned()).collect(); + privileges.sort(); + ((*table).to_owned(), privileges) + }) + .collect() +} + +/// Serve `project` with a split runtime role that starts with no grants, and +/// assert the role ends with exactly `grants` and `USAGE` (not `CREATE`) on +/// the schema. +async fn assert_serve_grants_exactly( + project: &Path, + profile: Option<&Path>, + endpoint: &str, + deployment: &str, + grants: &[(&str, &[&str])], +) { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), deployment).await; + let schema = current_schema(&database).await; let role = format!("{schema}_runtime"); - execute( + create_login_role(&database, &role).await; + assert!( + table_privileges(&database, &schema, &role).await.is_empty(), + "the role starts with no table privilege" + ); + let runtime_url = as_role(&database, &role); + let mut serving = SplitRoles::spawn_project( + &upstream.url(""), &database, - &format!( - "CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}'; \ - GRANT USAGE ON SCHEMA {schema} TO {role}; \ - GRANT SELECT ON adapter_schema_migrations TO {role}; \ - GRANT INSERT, SELECT ON adapter_journal_events TO {role};" - ), + &runtime_url, + project, + profile, + endpoint, + ); + serving.wait_until_listening(); + assert_eq!( + table_privileges(&database, &schema, &role).await, + expected(grants), + "the runtime role holds exactly the privileges the deployment requires" + ); + let schema_privileges = connect(&database) + .await + .query_one( + "SELECT has_schema_privilege($1, $2, 'USAGE'), has_schema_privilege($1, $2, 'CREATE')", + &[&role, &schema], + ) + .await + .expect("read the schema privileges"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::from([role.clone()]), + "the runtime role is the only grantee, and PUBLIC gained nothing" + ); + assert!(schema_privileges.get::<_, bool>(0), "USAGE on the schema"); + assert!( + !schema_privileges.get::<_, bool>(1), + "no CREATE on the schema" + ); + drop(serving); + drop_role(&database, &role).await; +} + +const EVERY_DEPLOYMENT: [(&str, &[&str]); 2] = [ + ("adapter_journal_events", &["INSERT", "SELECT", "DELETE"]), + ("adapter_schema_migrations", &["SELECT"]), +]; +const WRITE: [(&str, &[&str]); 2] = [ + ( + "adapter_idempotency_entries", + &["SELECT", "INSERT", "UPDATE", "DELETE"], + ), + ( + "adapter_idempotency_resumes", + &["SELECT", "INSERT", "UPDATE", "DELETE"], + ), +]; +const RECOVERY: [(&str, &[&str]); 2] = [ + ( + "adapter_idempotency_async_artifacts", + &["SELECT", "INSERT", "UPDATE"], + ), + ("adapter_idempotency_resume_bindings", &["SELECT", "INSERT"]), +]; + +#[tokio::test] +async fn serve_grants_exactly_the_required_privileges() { + // A read-only deployment: the journal and the migration ledger only. + assert_serve_grants_exactly( + &Served::govstack_project(), + None, + "tracker", + "grants-read", + &EVERY_DEPLOYMENT, ) .await; - seed(&database).await; - let runtime_url = as_role(&database, &role); + + // A synchronous write adds idempotent claims and response custody, and + // no artifact fence. + let write: Vec<_> = EVERY_DEPLOYMENT.iter().chain(&WRITE).copied().collect(); + assert_serve_grants_exactly( + &Served::example_project(), + Some(&Served::example_profile()), + "tracker", + "grants-write", + &write, + ) + .await; + + // A resumable write adds the artifact fence and the resume bindings. + let resumable: Vec<_> = EVERY_DEPLOYMENT + .iter() + .chain(&WRITE) + .chain(&RECOVERY) + .copied() + .collect(); + let recovery_project = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/adapter/examples/facade-recovery"); + assert_serve_grants_exactly( + &recovery_project, + Some(&Served::example_profile()), + "reference", + "grants-resume", + &resumable, + ) + .await; +} + +#[tokio::test] +async fn a_runtime_url_that_cannot_connect_fails_startup_before_any_grant() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-ghost").await; + let schema = current_schema(&database).await; + // The runtime URL names a role that does not exist. + let runtime_url = as_role(&database, &format!("{schema}_absent")); let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); - assert!( - stderr.contains("the runtime role lacks DELETE on adapter_journal_events"), - "{stderr}" + assert!(stderr.contains("database runtime"), "{stderr}"); + assert!(!stderr.contains(RUNTIME_PASSWORD), "{stderr}"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "no grant is made before the runtime credential works: {stderr}" ); +} + +#[tokio::test] +async fn a_runtime_url_naming_public_is_refused_and_grants_nothing() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-public").await; + let schema = current_schema(&database).await; + let runtime_url = as_role(&database, "public"); + + let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); + assert!(!stderr.contains(RUNTIME_PASSWORD), "{stderr}"); assert_eq!( - seeded_exchange_ids(&database).await.len(), - usize::try_from(MAX_RETENTION_BATCH).expect("the batch fits usize") + 2, - "a refused deployment deletes nothing" + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "no grant reached PUBLIC or any other role: {stderr}" ); +} + +#[tokio::test] +async fn a_runtime_role_with_members_is_granted_nothing_and_refused() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-members").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let member = format!("{schema}_member"); + create_login_role(&database, &role).await; + create_login_role(&database, &member).await; + execute(&database, &format!("GRANT {role} TO {member};")).await; + let runtime_url = as_role(&database, &role); + let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); + assert!(stderr.contains("the runtime role lacks"), "{stderr}"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "an automatic grant is never made to a role others inherit from: {stderr}" + ); + drop_role(&database, &member).await; + drop_role(&database, &role).await; +} + +/// The role that created the runtime role administers it, as in a database +/// built by `adapterctl provision`, so its membership does not stop the grant. +#[tokio::test] +async fn a_runtime_role_whose_only_member_administers_it_is_granted_its_privileges() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-admin").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let administrator = format!("{schema}_admin"); + create_login_role(&database, &role).await; + create_login_role(&database, &administrator).await; execute( &database, - &format!("GRANT DELETE ON adapter_journal_events TO {role};"), + &format!("GRANT {role} TO {administrator} WITH ADMIN OPTION;"), ) .await; + let runtime_url = as_role(&database, &role); + let mut serving = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); serving.wait_until_listening(); - await_retention(&database).await; + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::from([role.clone()]), + "the runtime role received the grants" + ); drop(serving); + drop_role(&database, &administrator).await; + drop_role(&database, &role).await; +} + +/// Create the runtime role the way `adapterctl provision` does: a +/// `LOGIN CREATEROLE` administrator creates it with `createrole_self_grant` +/// set to `set,inherit`. PostgreSQL then records two membership rows for the +/// administrator in the runtime role, one that carries ADMIN OPTION and one +/// that carries SET and INHERIT. +async fn create_provisioned_runtime_role(database: &str, runtime: &str, administrator: &str) { execute( - &database, - &format!("DROP OWNED BY {role}; DROP ROLE {role};"), + database, + &format!("CREATE ROLE {administrator} LOGIN CREATEROLE PASSWORD '{RUNTIME_PASSWORD}';"), ) .await; -} - -/// A fresh migrated schema and a runtime role holding only the journal -/// grants every deployment needs. -async fn journal_only_runtime_role( - upstream: &UpstreamDouble, - deployment: &str, -) -> (String, String) { - let database = migrated_schema(upstream, &Served::govstack_project(), deployment).await; - let schema: String = connect(&database) + execute( + &as_role(database, administrator), + &format!( + "SET createrole_self_grant = 'set,inherit'; \ + CREATE ROLE {runtime} LOGIN PASSWORD '{RUNTIME_PASSWORD}';" + ), + ) + .await; + let rows = connect(database) .await - .query_one("SELECT current_schema()", &[]) + .query( + "SELECT m.admin_option FROM pg_auth_members m \ + JOIN pg_roles r ON r.oid = m.roleid \ + JOIN pg_roles a ON a.oid = m.member \ + WHERE r.rolname = $1 AND a.rolname = $2 ORDER BY m.admin_option", + &[&runtime, &administrator], + ) .await - .expect("read the migrated schema") - .get(0); + .expect("read the administrator's memberships"); + assert_eq!( + rows.iter() + .map(|row| row.get::<_, bool>(0)) + .collect::>(), + [false, true], + "the administrator holds one ADMIN row and one plain row in the runtime role" + ); +} + +/// The layout `adapterctl provision` builds, with the CREATEROLE administrator +/// as the runtime role's only member, still receives its grants. Pinned on +/// the two-row layout: a per-row test of ADMIN OPTION would count the +/// administrator's plain row and refuse every provisioned database. +#[tokio::test] +async fn a_provisioned_runtime_role_is_granted_its_privileges() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-provisioned").await; + let schema = current_schema(&database).await; let role = format!("{schema}_runtime"); + let administrator = format!("{schema}_admin"); + create_provisioned_runtime_role(&database, &role, &administrator).await; + let runtime_url = as_role(&database, &role); + + let mut serving = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + serving.wait_until_listening(); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::from([role.clone()]), + "the runtime role received the grants" + ); + drop(serving); + drop_role(&database, &role).await; + drop_role(&database, &administrator).await; +} + +/// The provisioned layout plus one member that does not administer the role: +/// that member would inherit the grants, so none is made. +#[tokio::test] +async fn a_provisioned_runtime_role_with_a_plain_member_is_granted_nothing_and_refused() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-mixed").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let administrator = format!("{schema}_admin"); + let member = format!("{schema}_member"); + create_provisioned_runtime_role(&database, &role, &administrator).await; + create_login_role(&database, &member).await; + execute(&database, &format!("GRANT {role} TO {member};")).await; + let runtime_url = as_role(&database, &role); + + let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); + assert!(stderr.contains("the runtime role lacks"), "{stderr}"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "a plain member blocks the grant even beside an administrator: {stderr}" + ); + drop_role(&database, &member).await; + drop_role(&database, &role).await; + drop_role(&database, &administrator).await; +} + +/// A member that holds ADMIN OPTION but has members of its own reaches the +/// runtime role through them, so it does not make the grant safe. +#[tokio::test] +async fn an_administrator_with_members_of_its_own_blocks_the_grant() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-admin-chain").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let administrator = format!("{schema}_admin"); + let behind = format!("{schema}_behind"); + create_login_role(&database, &role).await; + create_login_role(&database, &administrator).await; + create_login_role(&database, &behind).await; execute( &database, &format!( - "CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}'; \ - GRANT USAGE ON SCHEMA {schema} TO {role}; \ - GRANT SELECT ON adapter_schema_migrations TO {role}; \ - GRANT INSERT, SELECT, DELETE ON adapter_journal_events TO {role};" + "GRANT {role} TO {administrator} WITH ADMIN OPTION; \ + GRANT {administrator} TO {behind};" ), ) .await; - (database, role) -} + let runtime_url = as_role(&database, &role); -const WRITE_GRANTS: &str = "GRANT SELECT, INSERT, UPDATE, DELETE \ - ON adapter_idempotency_entries, adapter_idempotency_resumes TO {role};"; -const RECOVERY_GRANTS: &str = - "GRANT SELECT, INSERT, UPDATE ON adapter_idempotency_async_artifacts TO {role}; \ - GRANT SELECT, INSERT ON adapter_idempotency_resume_bindings TO {role};"; + let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); + assert!(stderr.contains("the runtime role lacks"), "{stderr}"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "an administrator that others inherit from blocks the grant: {stderr}" + ); + drop_role(&database, &behind).await; + drop_role(&database, &administrator).await; + drop_role(&database, &role).await; +} #[tokio::test] -async fn a_write_runtime_role_without_idempotency_grants_is_refused_by_name() { +async fn a_migration_role_that_does_not_own_the_tables_fails_startup_and_grants_nothing() { let upstream = UpstreamDouble::start(); - let (database, role) = journal_only_runtime_role(&upstream, "tracker-grants").await; + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-nonowner").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let migrator = format!("{schema}_migrator"); + create_login_role(&database, &role).await; + create_login_role(&database, &migrator).await; + // The migrator can use and read the schema but owns nothing and holds no + // grant option, so PostgreSQL turns each of its GRANTs into a warning. + execute( + &database, + &format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL TABLES IN SCHEMA {schema} TO {migrator};" + ), + ) + .await; + let migration_url = as_role(&database, &migrator); let runtime_url = as_role(&database, &role); - let spawn = || { - SplitRoles::spawn_project( - &upstream.url(""), - &database, - &runtime_url, - &Served::example_project(), - Some(&Served::example_profile()), - "tracker", - ) - }; - let stderr = spawn().refusal(); + let stderr = SplitRoles::spawn(&upstream.url(""), &migration_url, &runtime_url).refusal(); assert!( - stderr.contains( - "the runtime role lacks SELECT, INSERT, UPDATE, DELETE on adapter_idempotency_entries" - ), + stderr.contains("INSERT, SELECT, DELETE on adapter_journal_events"), "{stderr}" ); assert!( - stderr.contains("SELECT, INSERT, UPDATE, DELETE on adapter_idempotency_resumes"), + stderr.contains("the migration role does not own"), "{stderr}" ); + assert!(!stderr.contains(RUNTIME_PASSWORD), "{stderr}"); assert!( - !stderr.contains("adapter_idempotency_async_artifacts"), - "a synchronous write needs no artifact-fence grant: {stderr}" + !acl_grantees(&database, &schema).await.contains(&role), + "a failed grant leaves nothing behind: {stderr}" ); + drop_role(&database, &migrator).await; + drop_role(&database, &role).await; +} - execute(&database, &WRITE_GRANTS.replace("{role}", &role)).await; - let mut serving = spawn(); - serving.wait_until_listening(); - drop(serving); +/// The migration role owns the journal tables but not the idempotency ones, so +/// the grants on the first succeed and the check on the second fails: nothing +/// stays granted. +#[tokio::test] +async fn a_migration_role_that_owns_only_some_tables_grants_nothing() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-partial").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let migrator = format!("{schema}_migrator"); + create_login_role(&database, &role).await; + create_login_role(&database, &migrator).await; execute( &database, - &format!("DROP OWNED BY {role}; DROP ROLE {role};"), + &format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL TABLES IN SCHEMA {schema} TO {migrator}; \ + ALTER TABLE {schema}.adapter_journal_events OWNER TO {migrator}; \ + ALTER TABLE {schema}.adapter_schema_migrations OWNER TO {migrator};" + ), ) .await; + let migration_url = as_role(&database, &migrator); + let runtime_url = as_role(&database, &role); + + let stderr = SplitRoles::spawn_project( + &upstream.url(""), + &migration_url, + &runtime_url, + &Served::example_project(), + Some(&Served::example_profile()), + "tracker", + ) + .refusal(); + assert!( + stderr.contains("on adapter_idempotency_entries"), + "{stderr}" + ); + assert!( + !acl_grantees(&database, &schema).await.contains(&role), + "the grants on the tables the migration role owns were rolled back: {stderr}" + ); + drop_role(&database, &migrator).await; + drop_role(&database, &role).await; } +/// A start that finds every privilege in place writes no catalog row. #[tokio::test] -async fn a_resumable_write_runtime_role_needs_the_recovery_grants_and_serves_on_first_run() { +async fn a_restart_with_every_grant_in_place_writes_no_grant() { let upstream = UpstreamDouble::start(); - let (database, role) = journal_only_runtime_role(&upstream, "resume-grants").await; - execute(&database, &WRITE_GRANTS.replace("{role}", &role)).await; + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-restart").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; let runtime_url = as_role(&database, &role); - let project = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../products/adapter/examples/facade-recovery"); - let spawn = || { - SplitRoles::spawn_project( - &upstream.url(""), - &database, - &runtime_url, - &project, - Some(&Served::example_profile()), - "reference", - ) + let catalog_versions = || async { + connect(&database) + .await + .query( + "SELECT c.relname::text, c.xmin::text FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + WHERE n.nspname = $1 AND c.relkind IN ('r', 'p') \ + UNION ALL SELECT n.nspname::text, n.xmin::text FROM pg_namespace n \ + WHERE n.nspname = $1 \ + ORDER BY 1", + &[&schema], + ) + .await + .expect("read the catalog row versions") + .iter() + .map(|row| (row.get::<_, String>(0), row.get::<_, String>(1))) + .collect::>() }; - let stderr = spawn().refusal(); + let mut first = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + first.wait_until_listening(); + drop(first); + let granted = catalog_versions().await; + let mut second = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + second.wait_until_listening(); + drop(second); + assert_eq!( + catalog_versions().await, + granted, + "a restart rewrote a table or schema ACL" + ); + drop_role(&database, &role).await; +} + +/// The advisory-lock key the grant step takes, so two replicas starting +/// together do not rewrite the same catalog rows at once. +const GRANT_LOCK_KEY: i64 = 0x6164_6170_5f67_6e74; + +#[tokio::test] +async fn the_grant_step_waits_for_the_grant_lock() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-lock").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; + let runtime_url = as_role(&database, &role); + let holder = connect(&database).await; + holder + .query_one("SELECT pg_advisory_lock($1)", &[&GRANT_LOCK_KEY]) + .await + .expect("take the grant lock"); + + let mut serving = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + tokio::time::sleep(Duration::from_secs(3)).await; assert!( - stderr.contains("SELECT, INSERT, UPDATE on adapter_idempotency_async_artifacts"), - "{stderr}" + serving + .child + .try_wait() + .expect("poll the adapter") + .is_none(), + "the adapter exited while the grant lock was held" ); assert!( - stderr.contains("SELECT, INSERT on adapter_idempotency_resume_bindings"), - "{stderr}" + TcpStream::connect(("127.0.0.1", serving.port)).is_err(), + "the adapter served while the grant lock was held" ); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "the adapter granted before it held the grant lock" + ); + holder + .query_one("SELECT pg_advisory_unlock($1)", &[&GRANT_LOCK_KEY]) + .await + .expect("release the grant lock"); + serving.wait_until_listening(); + drop(serving); + drop_role(&database, &role).await; +} - execute(&database, &RECOVERY_GRANTS.replace("{role}", &role)).await; - let mut serving = spawn(); +#[tokio::test] +async fn single_role_serve_issues_no_grant() { + let upstream = UpstreamDouble::start(); + let base = std::env::var("ADAPTER_TEST_DATABASE_URL") + .expect("ADAPTER_TEST_DATABASE_URL names a disposable PostgreSQL test server"); + let suffix = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("the test clock is after the Unix epoch") + .as_nanos(); + let schema = format!("adapter_single_{suffix}"); + let role = format!("{schema}_solo"); + let log = format!("{schema}_log"); + // An event trigger records the session role of every GRANT in the + // database, so the test can observe a grant a single role issues to itself. + execute( + &base, + &format!( + "CREATE SCHEMA {schema}; CREATE SCHEMA {log}; \ + CREATE TABLE {log}.grants (session_role text NOT NULL); \ + CREATE FUNCTION {log}.record() RETURNS event_trigger \ + LANGUAGE plpgsql SECURITY DEFINER AS $$ \ + BEGIN INSERT INTO {log}.grants VALUES (session_user); END $$; \ + CREATE EVENT TRIGGER {log}_trigger ON ddl_command_end \ + WHEN TAG IN ('GRANT') EXECUTE FUNCTION {log}.record(); \ + CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}'; \ + GRANT USAGE, CREATE ON SCHEMA {schema} TO {role};" + ), + ) + .await; + let separator = if base.contains('?') { '&' } else { '?' }; + let scoped = format!("{base}{separator}options=-csearch_path%3D{schema}"); + let single_url = as_role(&scoped, &role); + let grants_by_role = || async { + connect(&base) + .await + .query( + &format!("SELECT count(*) FROM {log}.grants WHERE session_role = $1"), + &[&role], + ) + .await + .expect("read the grant log")[0] + .get::<_, i64>(0) + }; + + let mut serving = SplitRoles::spawn(&upstream.url(""), &single_url, &single_url); serving.wait_until_listening(); + assert_eq!(grants_by_role().await, 0, "a single role issues no grant"); + // Positive control: the trigger does see a grant the same role issues. + execute( + &single_url, + "GRANT SELECT ON adapter_schema_migrations TO PUBLIC;", + ) + .await; + assert_eq!(grants_by_role().await, 1, "the grant log records a grant"); drop(serving); execute( - &database, - &format!("DROP OWNED BY {role}; DROP ROLE {role};"), + &base, + &format!( + "DROP EVENT TRIGGER {log}_trigger; DROP OWNED BY {role}; DROP ROLE {role}; \ + DROP SCHEMA {schema} CASCADE; DROP SCHEMA {log} CASCADE;" + ), ) .await; } diff --git a/docs/site/src/content/docs/operate/adapter.mdx b/docs/site/src/content/docs/operate/adapter.mdx index e4152a6375..884fdc9e6a 100644 --- a/docs/site/src/content/docs/operate/adapter.mdx +++ b/docs/site/src/content/docs/operate/adapter.mdx @@ -75,11 +75,22 @@ When the certificate comes from a private CA, name that CA with `adapter serve` migrates through `database.migrationUrlRef` and serves through `database.runtimeUrlRef`. The migration role owns the tables. -Give the runtime role only the grants its deployment uses. -The Adapter refuses a runtime role at startup, naming each missing grant and table, before it -listens. -In the statements that follow, `adapter` stands for the schema on the runtime role's search path and -`runtime` for that role: +After it migrates and before it grants anything, `adapter serve` connects as the runtime role and reads +that session's role name. +When it differs from the migration session's role name, `adapter serve` grants the runtime session's +role the privileges its deployment uses. +The grants run in one transaction, then `adapter serve` checks them and refuses to listen if one is +missing. +A runtime connection that fails stops startup before any grant. +The runtime role must already exist, be able to log in and hold `CONNECT` on the database. +When both sessions run as the same role, `adapter serve` issues no grant and the single role keeps +every privilege it owns. +The runtime role's search path must reach the same schema as the migration role's. + +The statements below are equivalent to what `adapter serve` runs for the facade tables, with +`adapter` standing for the schema on the migration role's search path and `runtime` for the runtime +role. +`adapter serve` issues only the grants the role still lacks: ```sql -- Every deployment: append journal events, run audit.retentionDays, report readiness. @@ -98,16 +109,61 @@ GRANT SELECT, INSERT, UPDATE ON adapter_idempotency_async_artifacts TO runtime; GRANT SELECT, INSERT ON adapter_idempotency_resume_bindings TO runtime; ``` -The runtime role needs no grant on `adapter_idempotency_schema_migrations`; only the migration role -reads it. +The Adapter grants nothing else: no default privileges, and nothing on +`adapter_idempotency_schema_migrations`, which only the migration role reads. +It never revokes a grant, so a feature you remove from a deployment leaves its earlier grants in +place until you revoke them. -{/* Evidence: crates/registry-adapter/src/serve.rs required, missing_table_privileges; +You still grant the payment tables yourself when you start `adapter serve` with +`--payments-config`. +`adapter serve` refuses to start without these privileges, and it does not grant them: + +```sql +GRANT SELECT, INSERT, UPDATE ON adapter_payment_attempts TO runtime; +GRANT SELECT, INSERT ON adapter_payment_commands, adapter_payment_events TO runtime; +GRANT USAGE ON SEQUENCE adapter_payment_events_sequence_seq TO runtime; + +-- When payments.yaml declares disbursement connections. +GRANT SELECT, INSERT, UPDATE ON adapter_g2p_attempts TO runtime; +GRANT SELECT, INSERT ON adapter_g2p_commands, adapter_g2p_events TO runtime; +GRANT USAGE ON SEQUENCE adapter_g2p_events_sequence_seq TO runtime; + +-- When you serve payments without a project, so no facade grant step runs. +GRANT USAGE ON SCHEMA adapter TO runtime; +``` + +`adapter serve` makes no automatic grant in two cases: + +- The runtime role lacks a privilege and has members that would inherit it. + `adapter serve` leaves that decision to you: grant the privileges above to the runtime role + yourself, and startup then passes the check. + A member that holds `ADMIN OPTION` on the runtime role and has no members of its own does not + count, because it can already grant the role to itself. + A role with `CREATEROLE` that is not a superuser and created the runtime role is such a member. +- The migration role does not own an object it must grant on, for example a table that an earlier + role created. + PostgreSQL ignores or refuses a grant its issuer has no right to make, so `adapter serve` rolls + the grants back and refuses to start. + Run the statements above as the object's owner, or make the migration role the owner. + +When the runtime role holds every privilege in the migration schema and startup still reports one +missing, the runtime session's search path resolves a different schema. + +{/* Evidence: crates/registry-adapter/src/serve.rs runtime_requirements, grant_runtime_privileges; + crates/registry-adapter/src/payments/store.rs check_privileges; + crates/registry-adapter/src/payments/g2p_store.rs check_privileges; crates/registry-adapter/src/journal.rs RUNTIME_PRIVILEGES; crates/registry-adapter/src/idempotent.rs WRITE_RUNTIME_GRANTS, RECOVERY_RUNTIME_GRANTS, RESUME_RUNTIME_GRANTS; crates/registry-adapter/tests/postgres_journal_retention_served.rs - a_write_runtime_role_without_idempotency_grants_is_refused_by_name, - a_resumable_write_runtime_role_needs_the_recovery_grants_and_serves_on_first_run. */} + serve_grants_exactly_the_required_privileges, single_role_serve_issues_no_grant, + a_runtime_url_naming_public_is_refused_and_grants_nothing, + a_runtime_role_with_members_is_granted_nothing_and_refused, + a_runtime_role_whose_only_member_administers_it_is_granted_its_privileges, + a_provisioned_runtime_role_is_granted_its_privileges, + a_provisioned_runtime_role_with_a_plain_member_is_granted_nothing_and_refused, + an_administrator_with_members_of_its_own_blocks_the_grant, + a_migration_role_that_does_not_own_the_tables_fails_startup_and_grants_nothing. */} ## Operate an ingestion job diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index 2d29f41802..d1a93aa2fc 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +- `adapter serve` grants the runtime database role the table privileges its + deployment needs, after it migrates and before it listens, when the runtime + and migration sessions run as different roles. The grantee is the role the + runtime session reports as its `current_user`, read before any grant, never + the name in a URL. A runtime connection that fails stops startup before any + grant. The grants are the ones the startup check already required, plus + `USAGE` on the schema. Only privileges the role lacks are granted, in one + transaction under an advisory lock, and nothing more: no default privileges, + no revoke. A successful grant logs one line naming the role and the number + of privileges. No grant is made to a role that lacks a privilege and has + members that would inherit it. A member that holds `ADMIN OPTION` on the + role and has no members of its own does not count. A grant the migration + role has no right to make (it does not own the object) stops startup with + the missing privilege named and rolls everything back. With one role in both + sessions, no grant is issued. Payment and G2P tables under + `--payments-config` still need your own grants. The runtime role must exist, + and the migration role must own the tables. - `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 From bc5f0804339b6a0f783b14b873b3166adf1b6766 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:37:06 +0100 Subject: [PATCH 028/136] feat(platform): gate development-only values behind a declared posture feat(cli-report): report the declared posture and where it came from Report: :with_posture writes posture.value and posture.source into a CLI report body after the command members, as the report already writes its own version and outcome. A report built without it is unchanged byte for byte. feat(platform): gate development-only configuration values behind a declared posture A configuration value that only a development process may use is a Gated value, readable with the witness the loader issues to a process that declared development. Decoding records each such value with its pointer, and one report decides: production refuses every recorded setting and development accepts and lists it under the same code. The production refusal names both ways to run a laptop or test process. A check acceptance cannot hide a posture diagnostic. No runtime uses the gate yet. Signed-off-by: Jeremi Joslin --- .github/workflows/render-golden.yml | 2 + Cargo.lock | 3 + crates/registry-cli-report/Cargo.toml | 1 + crates/registry-cli-report/README.md | 4 + crates/registry-cli-report/src/lib.rs | 40 ++ crates/registry-cli-report/tests/envelope.rs | 78 +++ crates/registry-platform-config/Cargo.toml | 3 + .../src/check_acceptances.rs | 26 +- crates/registry-platform-config/src/lib.rs | 6 + crates/registry-platform-config/src/loader.rs | 5 + .../registry-platform-config/src/posture.rs | 519 +++++++++++++++ .../src/posture_tests.rs | 592 ++++++++++++++++++ .../tests/posture_acceptance.rs | 69 ++ products/platform/CHANGELOG.md | 19 + 14 files changed, 1365 insertions(+), 2 deletions(-) create mode 100644 crates/registry-platform-config/src/posture.rs create mode 100644 crates/registry-platform-config/src/posture_tests.rs create mode 100644 crates/registry-platform-config/tests/posture_acceptance.rs diff --git a/.github/workflows/render-golden.yml b/.github/workflows/render-golden.yml index c6b727b841..33f54e78aa 100644 --- a/.github/workflows/render-golden.yml +++ b/.github/workflows/render-golden.yml @@ -26,6 +26,7 @@ on: - "crates/registry-platform-crypto/**" - "crates/registry-platform-httpsec/**" - "crates/registry-platform-loopback/**" + - "crates/registry-platform-posture/**" - "crates/registry-platform-testing/**" - "crates/registry-platform-yaml/**" - "products/render/**" @@ -52,6 +53,7 @@ on: - "crates/registry-platform-crypto/**" - "crates/registry-platform-httpsec/**" - "crates/registry-platform-loopback/**" + - "crates/registry-platform-posture/**" - "crates/registry-platform-testing/**" - "crates/registry-platform-yaml/**" - "products/render/**" diff --git a/Cargo.lock b/Cargo.lock index ed4ce79161..f3f5c7d0f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6705,6 +6705,7 @@ dependencies = [ name = "registry-cli-report" version = "0.49.0" dependencies = [ + "registry-platform-posture", "serde", "serde_json", ] @@ -7850,6 +7851,7 @@ version = "0.49.0" dependencies = [ "registry-platform-canonical-json", "registry-platform-loopback", + "registry-platform-posture", "registry-platform-yaml", "rustix 1.1.6", "schemars", @@ -7858,6 +7860,7 @@ dependencies = [ "sha2 0.11.1", "tempfile", "thiserror 2.0.21", + "tracing", "url", "zeroize", ] diff --git a/crates/registry-cli-report/Cargo.toml b/crates/registry-cli-report/Cargo.toml index 3e4a6b58ae..1bb68b21a4 100644 --- a/crates/registry-cli-report/Cargo.toml +++ b/crates/registry-cli-report/Cargo.toml @@ -9,6 +9,7 @@ repository.workspace = true publish = false [dependencies] +registry-platform-posture.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/registry-cli-report/README.md b/crates/registry-cli-report/README.md index fa76bdf89b..27c347a5a4 100644 --- a/crates/registry-cli-report/README.md +++ b/crates/registry-cli-report/README.md @@ -6,6 +6,10 @@ array. Products retain their command payloads, diagnostic contracts, and exit decisions. The primitive adds no HTTP, runtime configuration, or authentication dependency. +`Report::with_posture` adds a `posture` member with `value` (`development` or +`production`) and `source` (`flag`, `environment` or `default`) after the +command members. Without it the body is unchanged. + `status` is `complete`, `domain-refusal`, `usage-error`, or `operational-failure`, corresponding to exit codes 0 through 3. A command's more specific result, such as `declined`, is an `outcome`. An invalid envelope diff --git a/crates/registry-cli-report/src/lib.rs b/crates/registry-cli-report/src/lib.rs index 12657c917f..bf7f7bc4c4 100644 --- a/crates/registry-cli-report/src/lib.rs +++ b/crates/registry-cli-report/src/lib.rs @@ -3,6 +3,7 @@ use std::io::{self, Write}; +use registry_platform_posture::{DeclaredPosture, PostureSource}; use serde::ser::{Serialize, SerializeMap as _, Serializer}; use serde_json::{json, Map, Value}; @@ -68,6 +69,7 @@ pub struct Report<'a> { version: &'a str, status: Status, outcome: Option<&'a Value>, + posture: Option, } impl<'a> Report<'a> { @@ -132,8 +134,21 @@ impl<'a> Report<'a> { version, status, outcome, + posture: None, }) } + + /// Report the declared posture as a `posture` member holding `value` and + /// `source`, placed after the command members. A command member named + /// `posture` is not written, so the key appears once. Without this call the + /// body is unchanged. + #[must_use] + pub fn with_posture(self, declared: DeclaredPosture) -> Self { + Self { + posture: Some(declared), + ..self + } + } } impl Serialize for Report<'_> { @@ -148,12 +163,17 @@ impl Serialize for Report<'_> { } map.serialize_entry("version", self.version)?; for (key, value) in self.members { + let replaced = self.posture.is_some() && key == "posture"; if !HEAD.contains(&key.as_str()) && !matches!(key.as_str(), "version" | "diagnostics" | "outcome") + && !replaced { map.serialize_entry(key, value)?; } } + if let Some(declared) = self.posture { + map.serialize_entry("posture", &PostureMember(declared))?; + } if let Some(outcome) = self.outcome { map.serialize_entry("outcome", outcome)?; } @@ -165,6 +185,26 @@ impl Serialize for Report<'_> { } } +/// The `posture` member, written with `value` before `source`. +struct PostureMember(DeclaredPosture); + +impl Serialize for PostureMember { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(Some(2))?; + map.serialize_entry("value", self.0.posture.as_str())?; + map.serialize_entry("source", source_word(self.0.source))?; + map.end() + } +} + +fn source_word(source: PostureSource) -> &'static str { + match source { + PostureSource::Flag => "flag", + PostureSource::Environment => "environment", + PostureSource::Default => "default", + } +} + /// Static binary identity used when a command cannot finish normally. #[derive(Clone, Copy)] pub struct Identity { diff --git a/crates/registry-cli-report/tests/envelope.rs b/crates/registry-cli-report/tests/envelope.rs index e579ce022c..d90bd0c434 100644 --- a/crates/registry-cli-report/tests/envelope.rs +++ b/crates/registry-cli-report/tests/envelope.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 use registry_cli_report::{json_requested, Report, Status}; +use registry_platform_posture::{DeclaredPosture, Posture, PostureSource}; use serde_json::{json, Value}; fn members() -> Value { @@ -89,3 +90,80 @@ fn panic_output_selection_understands_both_format_spellings_and_the_terminator() )); } } + +fn declared(posture: Posture, source: PostureSource) -> DeclaredPosture { + DeclaredPosture { posture, source } +} + +#[test] +fn a_report_without_posture_is_unchanged() { + let value = members(); + let rendered = serde_json::to_string(&Report::new(&value, "1.0.0-dev").unwrap()).unwrap(); + assert_eq!( + rendered, + concat!( + r#"{"ok":true,"command":"check","status":"complete","#, + r#""apiVersion":"format/v1","kind":"CtlReport","version":"1.0.0-dev","#, + r#""filesChecked":2,"diagnostics":[]}"# + ) + ); +} + +#[test] +fn with_posture_adds_value_and_source_after_the_command_members() { + let value = members(); + let report = Report::new(&value, "1.0.0-dev") + .unwrap() + .with_posture(declared(Posture::Production, PostureSource::Default)); + let rendered = serde_json::to_string(&report).unwrap(); + assert_eq!( + rendered, + concat!( + r#"{"ok":true,"command":"check","status":"complete","#, + r#""apiVersion":"format/v1","kind":"CtlReport","version":"1.0.0-dev","#, + r#""filesChecked":2,"posture":{"value":"production","source":"default"},"#, + r#""diagnostics":[]}"# + ) + ); +} + +#[test] +fn posture_value_and_source_use_the_documented_spellings() { + for (posture, value) in [ + (Posture::Development, "development"), + (Posture::Production, "production"), + ] { + for (source, word) in [ + (PostureSource::Flag, "flag"), + (PostureSource::Environment, "environment"), + (PostureSource::Default, "default"), + ] { + let envelope = members(); + let report = serde_json::to_value( + Report::new(&envelope, "1.0.0") + .unwrap() + .with_posture(declared(posture, source)), + ) + .unwrap(); + assert_eq!(report["posture"], json!({"value": value, "source": word})); + } + } +} + +#[test] +fn the_declared_posture_replaces_a_command_member_of_the_same_name() { + let mut envelope = members(); + envelope["posture"] = json!("free text"); + let rendered = serde_json::to_string( + &Report::new(&envelope, "1.0.0") + .unwrap() + .with_posture(declared(Posture::Development, PostureSource::Flag)), + ) + .unwrap(); + assert_eq!(rendered.matches("\"posture\"").count(), 1, "{rendered}"); + let report: Value = serde_json::from_str(&rendered).unwrap(); + assert_eq!( + report["posture"], + json!({"value": "development", "source": "flag"}) + ); +} diff --git a/crates/registry-platform-config/Cargo.toml b/crates/registry-platform-config/Cargo.toml index 98def715ee..53c29331aa 100644 --- a/crates/registry-platform-config/Cargo.toml +++ b/crates/registry-platform-config/Cargo.toml @@ -11,11 +11,13 @@ publish = false workspace = true [features] +test-support = [] schema = ["dep:schemars", "registry-platform-yaml/schema"] [dependencies] registry-platform-canonical-json = { workspace = true } registry-platform-loopback.workspace = true +registry-platform-posture.workspace = true registry-platform-yaml.workspace = true rustix.workspace = true schemars = { workspace = true, optional = true } @@ -23,6 +25,7 @@ serde.workspace = true serde_json.workspace = true sha2.workspace = true thiserror.workspace = true +tracing.workspace = true url.workspace = true zeroize.workspace = true diff --git a/crates/registry-platform-config/src/check_acceptances.rs b/crates/registry-platform-config/src/check_acceptances.rs index 560b94da1e..2469d53548 100644 --- a/crates/registry-platform-config/src/check_acceptances.rs +++ b/crates/registry-platform-config/src/check_acceptances.rs @@ -87,8 +87,30 @@ pub fn apply_check_acceptances(project_root: &Path, report: &mut Report) { Ok(bytes) => { match read_project_check_acceptances(&acceptance_path.display().to_string(), &bytes) { Ok(decoded) => { - report.extend(decoded.document.report_with(Vec::new())); - Some(decoded.value) + // A posture diagnostic says what production would refuse, + // so no acceptance may hide it. + let refused: Vec = decoded + .value + .acceptances + .iter() + .enumerate() + .filter(|(_, acceptance)| crate::posture::is_posture_code(&acceptance.code)) + .map(|(index, _)| { + decoded.document.diagnostic_at_value( + Severity::Error, + "config.check-acceptance-not-acceptable", + &format!("/acceptances/{index}/code"), + "a posture diagnostic cannot be accepted", + "Remove this acceptance. Declare production and fix the setting, or leave the development warning in place.", + ) + }) + .collect(); + report.extend(decoded.document.report_with(refused)); + let mut value = decoded.value; + value + .acceptances + .retain(|acceptance| !crate::posture::is_posture_code(&acceptance.code)); + Some(value) } Err(errors) => { report.extend(errors); diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index 2069dac1de..1339ad60bc 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -14,6 +14,7 @@ mod loader; mod metrics_bind; mod offline; pub mod package; +mod posture; #[cfg(feature = "schema")] pub mod schema; mod secrets; @@ -55,6 +56,11 @@ pub use package::{ plan_package, verify_package, write_package, write_sum_file, PackageError, PackageErrorKind, PackageLimits, VerifiedPackage, REVISION_FILE, SUM_FILE, }; +pub use posture::{ + collect_development_settings, DeclaredPosture, DevelopmentClass, DevelopmentOnlyRefused, + DevelopmentSetting, DevelopmentWitness, ExplicitProductionSetting, FoundExplicitSetting, + FoundSetting, Gated, Posture, PostureReport, PostureSource, SettingOrigin, +}; pub use secrets::{ ProtectedSecret, SecretError, SecretProvider, SecretReference, SecretResolver, MAX_SECRET_BYTES, }; diff --git a/crates/registry-platform-config/src/loader.rs b/crates/registry-platform-config/src/loader.rs index c34927e175..1bf1307e47 100644 --- a/crates/registry-platform-config/src/loader.rs +++ b/crates/registry-platform-config/src/loader.rs @@ -163,6 +163,11 @@ impl RuntimeConfigError { .in_file(file) } + /// A refusal that carries `diagnostics`, in `file`. + pub(crate) fn from_diagnostics(file: &Path, diagnostics: Vec) -> Self { + Self::from_report(Report::new(diagnostics)).in_file(file) + } + fn from_report(report: Report) -> Self { let diagnostics = report.into_diagnostics(); assert!( diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs new file mode 100644 index 0000000000..ce2d33ab71 --- /dev/null +++ b/crates/registry-platform-config/src/posture.rs @@ -0,0 +1,519 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Development-only configuration values and the one decision about them. +//! +//! A configuration type that has values only a development process may use +//! implements [`DevelopmentClass`], and the member that holds it is a +//! [`Gated`]. Decoding a `Gated` never fails because of the posture: it records +//! what it found, and [`PostureReport::decide`] is the single place where +//! production refuses and development accepts and lists. A development value +//! is readable only with the [`DevelopmentWitness`] the loader issues to a +//! process that declared development. +//! +//! # A witness cannot be made outside this crate +//! +//! ```compile_fail +//! use registry_platform_config::DevelopmentWitness; +//! let _ = DevelopmentWitness { _sealed: () }; +//! ``` +//! +//! The compiling twin names the type and nothing else: +//! +//! ``` +//! use registry_platform_config::DevelopmentWitness; +//! fn takes(_: Option<&DevelopmentWitness>) {} +//! takes(None); +//! ``` +//! +//! ```compile_fail +//! use registry_platform_config::DevelopmentWitness; +//! let _ = DevelopmentWitness::default(); +//! ``` +//! +//! ``` +//! use registry_platform_config::DevelopmentWitness; +//! let _: Option = None; +//! ``` +//! +//! ```compile_fail +//! use registry_platform_config::DevelopmentWitness; +//! let _ = serde_json::from_str::("null"); +//! ``` +//! +//! ``` +//! use registry_platform_config::DevelopmentWitness; +//! let _ = serde_json::from_str::>("null"); +//! let _: Option = None; +//! ``` +//! +//! # A gated value has no way out but `get` +//! +//! ```compile_fail +//! # use registry_platform_config::{DevelopmentClass, DevelopmentSetting, Gated}; +//! # enum Transport { Tls, Plaintext } +//! # static PLAINTEXT: DevelopmentSetting = DevelopmentSetting { +//! # code: "platform.posture.example", key: "transport", summary: "s", production: "p", +//! # }; +//! # impl DevelopmentClass for Transport { +//! # const SETTINGS: &'static [&'static DevelopmentSetting] = &[&PLAINTEXT]; +//! # fn development_setting(&self) -> Option<&'static DevelopmentSetting> { +//! # match self { Transport::Tls => None, Transport::Plaintext => Some(&PLAINTEXT) } +//! # } +//! # } +//! let g = Gated::everywhere(Transport::Tls).unwrap(); +//! let _ = g.0; +//! ``` +//! +//! ```compile_fail +//! # use registry_platform_config::{DevelopmentClass, DevelopmentSetting, Gated}; +//! # enum Transport { Tls, Plaintext } +//! # static PLAINTEXT: DevelopmentSetting = DevelopmentSetting { +//! # code: "platform.posture.example", key: "transport", summary: "s", production: "p", +//! # }; +//! # impl DevelopmentClass for Transport { +//! # const SETTINGS: &'static [&'static DevelopmentSetting] = &[&PLAINTEXT]; +//! # fn development_setting(&self) -> Option<&'static DevelopmentSetting> { +//! # match self { Transport::Tls => None, Transport::Plaintext => Some(&PLAINTEXT) } +//! # } +//! # } +//! let g = Gated::everywhere(Transport::Tls).unwrap(); +//! let _ = &*g; +//! ``` +//! +//! The compiling twin reads the same value through `get`: +//! +//! ``` +//! # use registry_platform_config::{DevelopmentClass, DevelopmentSetting, Gated}; +//! # enum Transport { Tls, Plaintext } +//! # static PLAINTEXT: DevelopmentSetting = DevelopmentSetting { +//! # code: "platform.posture.example", key: "transport", summary: "s", production: "p", +//! # }; +//! # impl DevelopmentClass for Transport { +//! # const SETTINGS: &'static [&'static DevelopmentSetting] = &[&PLAINTEXT]; +//! # fn development_setting(&self) -> Option<&'static DevelopmentSetting> { +//! # match self { Transport::Tls => None, Transport::Plaintext => Some(&PLAINTEXT) } +//! # } +//! # } +//! let g = Gated::everywhere(Transport::Tls).unwrap(); +//! assert!(matches!(g.get(None), Ok(Transport::Tls))); +//! let _ = Transport::Plaintext; +//! ``` + +use std::cell::RefCell; +use std::fmt; +use std::marker::PhantomData; +use std::path::Path; + +use registry_platform_posture::{DEVELOPMENT, POSTURE_ENV, POSTURE_FLAG}; +use registry_platform_yaml::{ + escape_pointer_segment, gated_site, Diagnostic, Position, Severity, Source, DEVELOPMENT_ONLY, +}; +use serde::de::{Deserializer, Visitor}; +use serde::{Deserialize, Serialize, Serializer}; +use serde_json::{Map, Value}; + +pub use registry_platform_posture::{DeclaredPosture, Posture, PostureSource}; + +use crate::RuntimeConfigError; + +/// Proof that this process declared development. Only the loader creates it. +#[derive(Clone, Copy, Debug)] +pub struct DevelopmentWitness { + _sealed: (), +} + +impl DevelopmentWitness { + /// The loader issues the witness to a process that declared development. + #[allow(dead_code)] + pub(crate) const fn issue() -> Self { + Self { _sealed: () } + } +} + +/// One development-only setting, described by the crate that owns it. +#[derive(Debug, PartialEq, Eq)] +pub struct DevelopmentSetting { + /// `.posture.` (CFG-DIAG-3). + pub code: &'static str, + /// The authored key that holds the value: the last pointer segment. + pub key: &'static str, + /// Value-free: what the setting weakens. + pub summary: &'static str, + /// What to write for production. + pub production: &'static str, +} + +/// A configuration type that has development-only values. +pub trait DevelopmentClass { + /// Every setting a value of this type can select. Docs, schemas and tests + /// read it. + const SETTINGS: &'static [&'static DevelopmentSetting]; + + /// The setting this value selects, or `None` when it is valid in every + /// posture. Implement it with an exhaustive `match`, so a new variant + /// forces a decision. + fn development_setting(&self) -> Option<&'static DevelopmentSetting>; +} + +/// The refusal to read a development-only value without a witness. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("the setting {} is accepted only when the process declares development", .setting.code)] +pub struct DevelopmentOnlyRefused { + pub setting: &'static DevelopmentSetting, +} + +/// A value that may select a development-only setting. Read it with +/// [`Gated::get`]. +/// +/// There is no `Deref` and no way to take the value out: a value that selects +/// a development-only setting is unreadable without a [`DevelopmentWitness`]. +#[derive(Clone, PartialEq)] +pub struct Gated(T); + +impl Gated { + /// The value, when it is valid in every posture or the caller holds the + /// witness. + pub fn get(&self, witness: Option<&DevelopmentWitness>) -> Result<&T, DevelopmentOnlyRefused> { + match (self.0.development_setting(), witness) { + (Some(setting), None) => Err(DevelopmentOnlyRefused { setting }), + _ => Ok(&self.0), + } + } + + /// The setting the value selects, or `None` when it is valid in every + /// posture. + pub fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + self.0.development_setting() + } + + /// A value that is valid in every posture, for code that writes + /// configuration. + pub fn everywhere(value: T) -> Result { + match value.development_setting() { + Some(setting) => Err(DevelopmentOnlyRefused { setting }), + None => Ok(Self(value)), + } + } + + /// A value of any kind, for tests that exercise a development path. + #[cfg(any(test, feature = "test-support"))] + pub fn for_tests(value: T) -> Self { + Self(value) + } +} + +impl fmt::Debug for Gated { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, formatter) + } +} + +impl Serialize for Gated { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } +} + +impl<'de, T: DevelopmentClass + Deserialize<'de>> Deserialize<'de> for Gated { + fn deserialize>(deserializer: D) -> Result { + struct Reads(PhantomData); + impl<'de, T: DevelopmentClass + Deserialize<'de>> Visitor<'de> for Reads { + type Value = Gated; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a configuration value") + } + + fn visit_newtype_struct>( + self, + inner: D, + ) -> Result, D::Error> { + let site = gated_site(); + let value = T::deserialize(inner)?; + if let Some(setting) = value.development_setting() { + let (pointer, position) = match site { + Some(site) if site.exact => (Some(site.pointer), site.position), + // A flattened member is one of the holding mapping's own keys. + Some(site) => ( + Some(format!( + "{}/{}", + site.pointer, + escape_pointer_segment(setting.key) + )), + site.position, + ), + None => (None, None), + }; + record(FoundSetting { + setting, + pointer, + position, + origin: SettingOrigin::RuntimeFile, + }); + } + Ok(Gated(value)) + } + } + deserializer.deserialize_newtype_struct(DEVELOPMENT_ONLY, Reads(PhantomData)) + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for Gated { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + T::schema_name() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let mut schema = generator.subschema_for::(); + let codes: Vec<&str> = T::SETTINGS.iter().map(|setting| setting.code).collect(); + schema.insert("x-registry-development-only".to_owned(), codes.into()); + schema + } +} + +/// Where a recorded setting was found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SettingOrigin { + RuntimeFile, + Package, + Combination, +} + +/// A development-only setting found in a process's configuration. +#[derive(Clone, Debug)] +pub struct FoundSetting { + pub setting: &'static DevelopmentSetting, + pub pointer: Option, + pub position: Option, + pub origin: SettingOrigin, +} + +/// A setting valid in every posture that an operator states deliberately and +/// that relaxes something. It never refuses and is never a diagnostic: the +/// startup log and `check` say it is in use, and `/ready`, which answers +/// without credentials, does not list it. +#[derive(Debug, PartialEq, Eq)] +pub struct ExplicitProductionSetting { + /// `.posture.` (CFG-DIAG-3), distinct from every + /// development code. + pub code: &'static str, + /// The authored key, the last pointer segment. + pub key: &'static str, + /// Value-free: what it relaxes and why the operator states it. + pub summary: &'static str, +} + +/// An [`ExplicitProductionSetting`] found in a process's configuration. +#[derive(Clone, Debug)] +pub struct FoundExplicitSetting { + pub setting: &'static ExplicitProductionSetting, + pub pointer: Option, + pub position: Option, + pub origin: SettingOrigin, +} + +/// Run `decode` and return what it returned with every development-only +/// setting a [`Gated`] recorded while it ran. Calls nest: an inner call keeps +/// its own findings and restores the outer collector, also on a panic. +pub fn collect_development_settings(decode: impl FnOnce() -> R) -> (R, Vec) { + let guard = CollectorGuard { + previous: COLLECTOR.with(|collector| collector.borrow_mut().replace(Vec::new())), + }; + let result = decode(); + let found = COLLECTOR + .with(|collector| collector.borrow_mut().take()) + .unwrap_or_default(); + drop(guard); + (result, found) +} + +thread_local! { + static COLLECTOR: RefCell>> = const { RefCell::new(None) }; +} + +/// Restores the collector that was installed before this one, also on a panic. +struct CollectorGuard { + previous: Option>, +} + +impl Drop for CollectorGuard { + fn drop(&mut self) { + COLLECTOR.with(|collector| *collector.borrow_mut() = self.previous.take()); + } +} + +/// Add `found` to the active collector. Outside a collector nothing is +/// recorded, and a development value stays unreadable without a witness. +fn record(found: FoundSetting) { + COLLECTOR.with(|collector| { + if let Some(found_so_far) = collector.borrow_mut().as_mut() { + found_so_far.push(found); + } + }); +} + +/// The posture a process declared and every setting found under it. +#[derive(Clone, Debug)] +pub struct PostureReport { + declared: DeclaredPosture, + settings: Vec, + explicit: Vec, +} + +impl PostureReport { + #[must_use] + pub fn new(declared: DeclaredPosture) -> Self { + Self { + declared, + settings: Vec::new(), + explicit: Vec::new(), + } + } + + pub fn record(&mut self, found: FoundSetting) { + self.settings.push(found); + } + + pub fn record_explicit(&mut self, found: FoundExplicitSetting) { + self.explicit.push(found); + } + + #[must_use] + pub fn posture(&self) -> Posture { + self.declared.posture + } + + #[must_use] + pub fn settings(&self) -> &[FoundSetting] { + &self.settings + } + + #[must_use] + pub fn explicit_settings(&self) -> &[FoundExplicitSetting] { + &self.explicit + } + + /// The one decision. Production refuses every recorded setting and + /// development accepts and lists them, under the same codes. + #[must_use] + pub fn diagnostics(&self, file: &Path) -> Vec { + let production = self.posture() == Posture::Production; + self.settings + .iter() + .map(|found| { + let setting = found.setting; + let pointer = found.pointer.as_deref().unwrap_or(""); + let (message, action) = if production { + ( + format!( + "{}; it is accepted only when the process declares development", + setting.summary + ), + format!( + "{} For a laptop or test run, start it with `rstack dev`, or declare development with {POSTURE_ENV}={DEVELOPMENT} or --{POSTURE_FLAG} {DEVELOPMENT}.", + setting.production + ), + ) + } else { + ( + format!("{}; production refuses it", setting.summary), + setting.production.to_owned(), + ) + }; + let mut diagnostic = if production { + Diagnostic::error(setting.code, pointer, message, action) + } else { + Diagnostic::warning(setting.code, pointer, message, action) + }; + diagnostic.source = Some(Source { + file: file.display().to_string(), + line: found.position.map(|position| position.line), + column: found.position.map(|position| position.column), + }); + diagnostic + }) + .collect() + } + + /// `Err` exactly when [`PostureReport::diagnostics`] holds an error. + pub fn decide(&self, file: &Path) -> Result<(), RuntimeConfigError> { + let diagnostics = self.diagnostics(file); + if diagnostics + .iter() + .any(|diagnostic| diagnostic.severity == Severity::Error) + { + return Err(RuntimeConfigError::from_diagnostics(file, diagnostics)); + } + Ok(()) + } + + /// The members a runtime adds to its `/ready` body: the posture and the + /// development settings. Explicit production settings are left out, since + /// `/ready` answers without credentials. + #[must_use] + pub fn ready_member(&self) -> Map { + let listed = |code: &str, pointer: &Option| { + let mut member = Map::new(); + member.insert("code".to_owned(), Value::from(code)); + if let Some(pointer) = pointer { + member.insert("pointer".to_owned(), Value::from(pointer.as_str())); + } + Value::Object(member) + }; + let mut members = Map::new(); + members.insert("posture".to_owned(), Value::from(self.posture().as_str())); + members.insert( + "developmentSettings".to_owned(), + self.settings + .iter() + .map(|found| listed(found.setting.code, &found.pointer)) + .collect(), + ); + members + } + + /// Log the declared posture and what is in use. + pub fn log_startup(&self) { + let source = match self.declared.source { + PostureSource::Flag => "flag", + PostureSource::Environment => "environment", + PostureSource::Default => "default", + }; + tracing::info!( + posture = self.posture().as_str(), + posture_source = source, + development_settings = self.settings.len(), + explicit_production_settings = self.explicit.len(), + "posture declared" + ); + if self.posture() == Posture::Development { + for found in &self.settings { + tracing::warn!( + error_code = found.setting.code, + pointer = found.pointer.as_deref().unwrap_or(""), + "development-only setting in use; production refuses it" + ); + } + } + for found in &self.explicit { + tracing::info!( + setting_code = found.setting.code, + pointer = found.pointer.as_deref().unwrap_or(""), + "explicit production setting in use" + ); + } + } +} + +/// Whether `code` is a posture code: `.posture.`. +pub(crate) fn is_posture_code(code: &str) -> bool { + code.split('.').nth(1) == Some("posture") +} + +#[cfg(test)] +#[path = "posture_tests.rs"] +mod tests; diff --git a/crates/registry-platform-config/src/posture_tests.rs b/crates/registry-platform-config/src/posture_tests.rs new file mode 100644 index 0000000000..7fa3e205a3 --- /dev/null +++ b/crates/registry-platform-config/src/posture_tests.rs @@ -0,0 +1,592 @@ +use super::*; +use crate::{RuntimeConfigLoader, RuntimeEnvelope}; +use registry_platform_yaml::Severity; +use std::collections::BTreeMap; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +const ENVELOPE: RuntimeEnvelope = RuntimeEnvelope { + api_version: "registry.registrystack.org/example-runtime/v1alpha1", + kind: "ExampleRuntimeConfig", +}; + +const HEAD: &str = + "apiVersion: registry.registrystack.org/example-runtime/v1alpha1\nkind: ExampleRuntimeConfig\n"; + +static PLAINTEXT: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.example-plaintext", + key: "transport", + summary: "The database connection is not encrypted", + production: "Write transport: tls.", +}; + +static INSECURE: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.example-insecure", + key: "allow", + summary: "The issuer is reached over plain HTTP", + production: "Write allow: false.", +}; + +static COMBINATION: DevelopmentSetting = DevelopmentSetting { + code: "evidence.posture.example-combination", + key: "assuranceProfile", + summary: "Development is declared with a production profile", + production: "Write assuranceProfile: local.", +}; + +static UNRESTRICTED: ExplicitProductionSetting = ExplicitProductionSetting { + code: "adapter.posture.example-unrestricted", + key: "allowedClients", + summary: "Every client is admitted, which the operator states deliberately", +}; + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +enum Transport { + Tls, + Plaintext, +} + +impl DevelopmentClass for Transport { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&PLAINTEXT]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + match self { + Transport::Tls => None, + Transport::Plaintext => Some(&PLAINTEXT), + } + } +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(transparent)] +struct Insecure(bool); + +impl DevelopmentClass for Insecure { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&INSECURE]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + self.0.then_some(&INSECURE) + } +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +struct Database { + transport: Gated, +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +struct Shared { + allow: Gated, +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +struct Issuer { + #[serde(flatten)] + shared: Shared, +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +#[serde(rename_all = "camelCase")] +struct Example { + database: Database, + #[serde(default)] + issuer: Option, + #[serde(default)] + replicas: Vec, +} + +fn declared(posture: Posture) -> DeclaredPosture { + DeclaredPosture { + posture, + source: PostureSource::Flag, + } +} + +fn load(body: &str) -> (Result<(), String>, Vec) { + let text = format!("{HEAD}{body}"); + let (result, found) = collect_development_settings(|| { + RuntimeConfigLoader::new(ENVELOPE).parse_str::(&text, |_| None) + }); + (result.map(|_| ()).map_err(|error| error.to_string()), found) +} + +fn found(setting: &'static DevelopmentSetting, pointer: Option<&str>) -> FoundSetting { + FoundSetting { + setting, + pointer: pointer.map(str::to_owned), + position: Some(Position { line: 7, column: 5 }), + origin: SettingOrigin::RuntimeFile, + } +} + +// Gated + +#[test] +fn get_without_a_witness_refuses_a_development_value_and_with_one_returns_it() { + let value = Gated::for_tests(Transport::Plaintext); + let witness = DevelopmentWitness::issue(); + assert_eq!( + value.get(None).unwrap_err(), + DevelopmentOnlyRefused { + setting: &PLAINTEXT + } + ); + assert_eq!(value.get(Some(&witness)).unwrap(), &Transport::Plaintext); +} + +#[test] +fn get_returns_a_value_valid_everywhere_with_or_without_a_witness() { + let value = Gated::everywhere(Transport::Tls).unwrap(); + let witness = DevelopmentWitness::issue(); + assert_eq!(value.get(None).unwrap(), &Transport::Tls); + assert_eq!(value.get(Some(&witness)).unwrap(), &Transport::Tls); + assert_eq!(value.development_setting(), None); +} + +#[test] +fn everywhere_refuses_a_development_value() { + let refused = Gated::everywhere(Transport::Plaintext).unwrap_err(); + assert_eq!(refused.setting.code, "platform.posture.example-plaintext"); + assert_eq!( + refused.to_string(), + "the setting platform.posture.example-plaintext is accepted only when the process declares development" + ); +} + +#[test] +fn a_gated_value_serializes_as_its_inner_value_and_debug_delegates() { + let value = Gated::for_tests(Transport::Plaintext); + assert_eq!(serde_json::to_string(&value).unwrap(), "\"plaintext\""); + assert_eq!(format!("{value:?}"), "Plaintext"); + assert_eq!(value.clone(), value); + assert_ne!(value, Gated::for_tests(Transport::Tls)); +} + +#[test] +fn the_development_setting_names_what_a_value_selects() { + assert_eq!( + Gated::for_tests(Transport::Plaintext).development_setting(), + Some(&PLAINTEXT) + ); +} + +// Collecting + +#[test] +fn a_decode_records_a_member_a_list_item_and_a_flattened_member() { + let (result, found) = load(concat!( + "database:\n transport: plaintext\n", + "issuer:\n allow: true\n", + "replicas:\n - transport: tls\n - transport: plaintext\n", + )); + assert_eq!(result, Ok(()), "a development value never fails the decode"); + let pointers: Vec<_> = found + .iter() + .map(|found| (found.setting.code, found.pointer.as_deref())) + .collect(); + assert_eq!( + pointers, + [ + ( + "platform.posture.example-plaintext", + Some("/database/transport") + ), + ("platform.posture.example-insecure", Some("/issuer/allow")), + ( + "platform.posture.example-plaintext", + Some("/replicas/1/transport") + ), + ] + ); + assert!(found.iter().all(|found| found.position.is_some())); + assert!(found + .iter() + .all(|found| found.origin == SettingOrigin::RuntimeFile)); +} + +#[test] +fn the_position_of_an_exact_site_is_the_value() { + let (_, found) = load("database:\n transport: plaintext\n"); + assert_eq!( + found[0].position, + Some(Position { + line: 4, + column: 14 + }) + ); +} + +#[test] +fn a_value_valid_in_every_posture_is_not_recorded() { + let (result, found) = load("database:\n transport: tls\nissuer:\n allow: false\n"); + assert_eq!(result, Ok(())); + assert!(found.is_empty()); +} + +#[test] +fn a_decode_that_fails_part_way_still_reports_what_it_found() { + let (result, found) = load("database:\n transport: plaintext\nunknown: 1\n"); + assert!(result.is_err()); + assert_eq!(found.len(), 1); +} + +#[test] +fn a_value_decoded_without_the_reader_is_recorded_without_a_pointer() { + let (value, found) = collect_development_settings(|| { + serde_json::from_str::>("\"plaintext\"").unwrap() + }); + assert_eq!(found.len(), 1); + assert_eq!(found[0].pointer, None); + assert_eq!(found[0].position, None); + assert!(value.get(None).is_err()); +} + +#[test] +fn a_decode_with_no_collector_records_nothing_and_still_gates_the_value() { + let value = serde_json::from_str::>("\"plaintext\"").unwrap(); + assert!(value.get(None).is_err()); + let (_, found) = collect_development_settings(|| ()); + assert!(found.is_empty()); +} + +#[test] +fn a_nested_collector_keeps_its_own_findings_and_restores_the_outer() { + let ((inner, after), outer) = collect_development_settings(|| { + let _ = serde_json::from_str::>("\"plaintext\"").unwrap(); + let (_, inner) = collect_development_settings(|| { + let _ = serde_json::from_str::>("true").unwrap(); + }); + let _ = serde_json::from_str::>("\"plaintext\"").unwrap(); + let (_, after) = collect_development_settings(|| ()); + (inner, after) + }); + assert_eq!( + inner.iter().map(|f| f.setting.code).collect::>(), + ["platform.posture.example-insecure"] + ); + assert!(after.is_empty()); + assert_eq!( + outer.iter().map(|f| f.setting.code).collect::>(), + [ + "platform.posture.example-plaintext", + "platform.posture.example-plaintext" + ] + ); +} + +#[test] +fn a_panic_inside_a_collector_restores_the_outer_collector() { + let (_, outer) = collect_development_settings(|| { + let panicked = + std::panic::catch_unwind(|| collect_development_settings(|| panic!("decode failed"))); + assert!(panicked.is_err()); + let _ = serde_json::from_str::>("\"plaintext\"").unwrap(); + }); + assert_eq!(outer.len(), 1); + let (_, none) = collect_development_settings(|| ()); + assert!(none.is_empty()); +} + +// F1 + +#[test] +fn production_refuses_each_setting_with_an_error_and_development_warns_under_the_same_code() { + let mut production = PostureReport::new(declared(Posture::Production)); + let mut development = PostureReport::new(declared(Posture::Development)); + for report in [&mut production, &mut development] { + report.record(found(&PLAINTEXT, Some("/database/transport"))); + report.record(found(&COMBINATION, None)); + } + let file = Path::new("/etc/example/runtime.yaml"); + let refused = production.diagnostics(file); + let accepted = development.diagnostics(file); + assert_eq!( + refused.iter().map(|d| d.code.as_str()).collect::>(), + accepted.iter().map(|d| d.code.as_str()).collect::>() + ); + assert!(refused.iter().all(|d| d.severity == Severity::Error)); + assert!(accepted.iter().all(|d| d.severity == Severity::Warning)); + + assert_eq!(refused[0].code, "platform.posture.example-plaintext"); + assert_eq!(refused[0].path, "/database/transport"); + assert_eq!( + refused[0].message, + "The database connection is not encrypted; it is accepted only when the process declares development" + ); + assert_eq!( + refused[0].suggested_action, + "Write transport: tls. For a laptop or test run, start it with `rstack dev`, or declare development with REGISTRY_STACK_POSTURE=development or --posture development." + ); + let source = refused[0].source.as_ref().unwrap(); + assert_eq!(source.file, "/etc/example/runtime.yaml"); + assert_eq!((source.line, source.column), (Some(7), Some(5))); + + assert_eq!( + accepted[0].message, + "The database connection is not encrypted; production refuses it" + ); + assert_eq!(accepted[0].suggested_action, "Write transport: tls."); +} + +#[test] +fn a_combination_has_no_pointer() { + let mut report = PostureReport::new(declared(Posture::Production)); + report.record(FoundSetting { + setting: &COMBINATION, + pointer: None, + position: None, + origin: SettingOrigin::Combination, + }); + let diagnostics = report.diagnostics(Path::new("/etc/example/runtime.yaml")); + assert_eq!(diagnostics[0].path, ""); +} + +#[test] +fn decide_refuses_in_production_with_every_setting_and_accepts_in_development() { + let file = Path::new("/etc/example/runtime.yaml"); + let mut production = PostureReport::new(declared(Posture::Production)); + let mut development = PostureReport::new(declared(Posture::Development)); + for report in [&mut production, &mut development] { + report.record(found(&PLAINTEXT, Some("/database/transport"))); + report.record(found(&INSECURE, Some("/issuer/allow"))); + } + let error = production.decide(file).unwrap_err(); + assert_eq!( + error + .diagnostics() + .iter() + .map(|d| d.code.as_str()) + .collect::>(), + [ + "platform.posture.example-plaintext", + "platform.posture.example-insecure" + ] + ); + assert_eq!(error.file(), Some(file)); + assert_eq!(development.decide(file), Ok(())); +} + +#[test] +fn a_report_with_no_settings_decides_ok_in_both_postures() { + let file = Path::new("/etc/example/runtime.yaml"); + for posture in [Posture::Production, Posture::Development] { + let report = PostureReport::new(declared(posture)); + assert!(report.diagnostics(file).is_empty()); + assert_eq!(report.decide(file), Ok(())); + } +} + +#[test] +fn ready_member_shape() { + let mut development = PostureReport::new(declared(Posture::Development)); + development.record(found(&PLAINTEXT, Some("/database/transport"))); + development.record(FoundSetting { + setting: &COMBINATION, + pointer: None, + position: None, + origin: SettingOrigin::Combination, + }); + assert_eq!( + Value::Object(development.ready_member()), + serde_json::json!({ + "posture": "development", + "developmentSettings": [ + {"code": "platform.posture.example-plaintext", "pointer": "/database/transport"}, + {"code": "evidence.posture.example-combination"} + ] + }) + ); + let production = PostureReport::new(declared(Posture::Production)); + assert_eq!( + Value::Object(production.ready_member()), + serde_json::json!({ + "posture": "production", + "developmentSettings": [] + }) + ); +} + +// Explicit production settings + +fn explicit(pointer: Option<&str>) -> FoundExplicitSetting { + FoundExplicitSetting { + setting: &UNRESTRICTED, + pointer: pointer.map(str::to_owned), + position: Some(Position { line: 9, column: 3 }), + origin: SettingOrigin::RuntimeFile, + } +} + +#[test] +fn an_explicit_setting_decides_ok_in_production_and_adds_no_diagnostic() { + let file = Path::new("/etc/example/runtime.yaml"); + let mut report = PostureReport::new(declared(Posture::Production)); + report.record_explicit(explicit(Some("/serve/allowedClients"))); + assert_eq!(report.explicit_settings().len(), 1); + assert!(report.settings().is_empty()); + assert!(report.diagnostics(file).is_empty()); + assert_eq!(report.decide(file), Ok(())); +} + +#[test] +fn an_explicit_setting_appears_in_no_ready_member() { + for (posture, name) in [ + (Posture::Production, "production"), + (Posture::Development, "development"), + ] { + let mut report = PostureReport::new(declared(posture)); + report.record_explicit(explicit(Some("/serve/allowedClients"))); + assert_eq!( + Value::Object(report.ready_member()), + serde_json::json!({"posture": name, "developmentSettings": []}) + ); + } +} + +#[test] +fn explicit_settings_do_not_change_the_development_diagnostics() { + let file = Path::new("/etc/example/runtime.yaml"); + let mut report = PostureReport::new(declared(Posture::Development)); + report.record_explicit(explicit(Some("/serve/allowedClients"))); + report.record(found(&PLAINTEXT, Some("/database/transport"))); + assert_eq!(report.diagnostics(file).len(), 1); +} + +// Startup log + +#[derive(Clone, Debug)] +struct Logged { + level: tracing::Level, + fields: BTreeMap, +} + +struct Collect(Arc>>); + +struct Fields<'a>(&'a mut BTreeMap); + +impl tracing::field::Visit for Fields<'_> { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) { + self.0.insert(field.name().to_owned(), format!("{value:?}")); + } + + fn record_str(&mut self, field: &tracing::field::Field, value: &str) { + self.0.insert(field.name().to_owned(), value.to_owned()); + } + + fn record_u64(&mut self, field: &tracing::field::Field, value: u64) { + self.0.insert(field.name().to_owned(), value.to_string()); + } +} + +impl tracing::Subscriber for Collect { + fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { + true + } + + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + + fn event(&self, event: &tracing::Event<'_>) { + let mut fields = BTreeMap::new(); + event.record(&mut Fields(&mut fields)); + self.0.lock().unwrap().push(Logged { + level: *event.metadata().level(), + fields, + }); + } + + fn enter(&self, _: &tracing::span::Id) {} + + fn exit(&self, _: &tracing::span::Id) {} +} + +fn logged(report: &PostureReport) -> Vec { + let events = Arc::new(Mutex::new(Vec::new())); + tracing::subscriber::with_default(Collect(events.clone()), || report.log_startup()); + let events = events.lock().unwrap().clone(); + events +} + +#[test] +fn startup_logs_the_posture_a_warning_per_development_setting_and_each_explicit_setting() { + let mut report = PostureReport::new(DeclaredPosture { + posture: Posture::Development, + source: PostureSource::Environment, + }); + report.record(found(&PLAINTEXT, Some("/database/transport"))); + report.record_explicit(explicit(Some("/serve/allowedClients"))); + let events = logged(&report); + assert_eq!(events.len(), 3); + + assert_eq!(events[0].level, tracing::Level::INFO); + assert_eq!(events[0].fields["message"], "posture declared"); + assert_eq!(events[0].fields["posture"], "development"); + assert_eq!(events[0].fields["posture_source"], "environment"); + assert_eq!(events[0].fields["development_settings"], "1"); + assert_eq!(events[0].fields["explicit_production_settings"], "1"); + + assert_eq!(events[1].level, tracing::Level::WARN); + assert_eq!( + events[1].fields["message"], + "development-only setting in use; production refuses it" + ); + assert_eq!( + events[1].fields["error_code"], + "platform.posture.example-plaintext" + ); + assert_eq!(events[1].fields["pointer"], "/database/transport"); + + assert_eq!(events[2].level, tracing::Level::INFO); + assert_eq!( + events[2].fields["message"], + "explicit production setting in use" + ); + assert_eq!( + events[2].fields["setting_code"], + "adapter.posture.example-unrestricted" + ); + assert_eq!(events[2].fields["pointer"], "/serve/allowedClients"); +} + +#[test] +fn startup_in_production_logs_one_line_for_a_clean_report() { + let report = PostureReport::new(declared(Posture::Production)); + let events = logged(&report); + assert_eq!(events.len(), 1); + assert_eq!(events[0].fields["posture"], "production"); + assert_eq!(events[0].fields["posture_source"], "flag"); + assert_eq!(events[0].fields["development_settings"], "0"); +} + +#[test] +fn posture_codes_are_recognised_by_their_second_segment() { + assert!(is_posture_code("platform.posture.insecure-issuer-http")); + assert!(is_posture_code("breg.posture.placeholder-identity")); + assert!(!is_posture_code("platform.database.test-only-plaintext")); + assert!(!is_posture_code("platform.activation.posture-mismatch")); + assert!(!is_posture_code("config.unknown-key")); + assert!(!is_posture_code("posture")); +} + +#[cfg(feature = "schema")] +#[test] +fn the_schema_is_the_inner_schema_with_the_development_codes() { + let mut generator = schemars::generate::SchemaSettings::draft2020_12().into_generator(); + let schema = generator.subschema_for::>(); + let schema = serde_json::to_value(&schema).unwrap(); + assert_eq!( + schema["x-registry-development-only"], + serde_json::json!(["platform.posture.example-plaintext"]) + ); +} diff --git a/crates/registry-platform-config/tests/posture_acceptance.rs b/crates/registry-platform-config/tests/posture_acceptance.rs new file mode 100644 index 0000000000..531ddb9e08 --- /dev/null +++ b/crates/registry-platform-config/tests/posture_acceptance.rs @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +//! A posture diagnostic cannot be hidden by a project check acceptance. + +use registry_platform_config::apply_check_acceptances; +use registry_platform_yaml::{Diagnostic, Report, Severity, Source}; + +const ACCEPTANCES: &str = "apiVersion: id.registrystack.org/formats/platform/check-acceptances/v1alpha1\nkind: PlatformCheckAcceptances\nacceptances:\n - code: platform.posture.insecure-issuer-http\n scope:\n file: runtime.yaml\n path: /issuer/allowInsecureHttp\n reason: We need it on the laptop.\n"; + +fn posture_warning(root: &std::path::Path) -> Diagnostic { + let mut diagnostic = Diagnostic::warning( + "platform.posture.insecure-issuer-http", + "/issuer/allowInsecureHttp", + "The issuer is reached over plain HTTP; production refuses it", + "Write allowInsecureHttp: false.", + ); + diagnostic.source = Some(Source { + file: root.join("runtime.yaml").display().to_string(), + line: Some(4), + column: Some(3), + }); + diagnostic +} + +#[test] +fn an_acceptance_naming_a_posture_code_is_refused_and_hides_nothing() { + let root = tempfile::tempdir().unwrap(); + std::fs::write( + root.path().join("runtime.yaml"), + "issuer:\n allowInsecureHttp: true\n", + ) + .unwrap(); + std::fs::write(root.path().join("check-acceptances.yaml"), ACCEPTANCES).unwrap(); + let mut report = Report::new(vec![posture_warning(root.path())]); + apply_check_acceptances(root.path(), &mut report); + + let posture = report + .diagnostics() + .iter() + .find(|d| d.code == "platform.posture.insecure-issuer-http") + .unwrap(); + assert_eq!(posture.accepted_reason, None); + assert_eq!(report.accepted_warning_count(), 0); + let refusal: Vec<_> = report + .diagnostics() + .iter() + .filter(|d| d.code == "config.check-acceptance-not-acceptable") + .collect(); + assert_eq!(refusal.len(), 1); + assert_eq!(refusal[0].severity, Severity::Error); + assert_eq!(refusal[0].path, "/acceptances/0/code"); +} + +#[test] +fn other_acceptances_in_the_same_file_still_apply() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("registry.yaml"), "a:\n b: 1\n").unwrap(); + let input = ACCEPTANCES.to_owned() + + " - code: example.access.unrestricted\n scope:\n file: registry.yaml\n path: /a/b\n reason: Reviewed.\n"; + std::fs::write(root.path().join("check-acceptances.yaml"), input).unwrap(); + let mut other = Diagnostic::warning("example.access.unrestricted", "/a/b", "m", "a"); + other.source = Some(Source { + file: root.path().join("registry.yaml").display().to_string(), + line: Some(2), + column: Some(3), + }); + let mut report = Report::new(vec![posture_warning(root.path()), other]); + apply_check_acceptances(root.path(), &mut report); + assert_eq!(report.accepted_warning_count(), 1); +} diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 2eeaca5b38..0d2beba581 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -14,6 +14,25 @@ position while the reader decodes it: exact for a node, and the holding mapping with `exact: false` under `#[serde(flatten)]`. +- `registry-platform-config` adds the development-only gate. A configuration + type with values only a development process may use implements + `DevelopmentClass`, and the member that holds it is a `Gated`, readable only + with the `DevelopmentWitness` the loader issues to a process that declared + development. `collect_development_settings` records each such value while it + decodes, and `PostureReport` is the one decision: production refuses every + recorded setting under its `.posture.` code, and development + accepts and lists it. `ready_member` gives the `posture` and + `developmentSettings` members a runtime adds to `/ready`, and `log_startup` + logs the declared posture, the development settings in use and the explicit + production settings in use. A check acceptance cannot hide a posture + diagnostic: one that names a posture code is refused with + `config.check-acceptance-not-acceptable`. No runtime uses the gate yet. + +- `registry-cli-report` adds `Report::with_posture`, which writes + `posture.value` and `posture.source` (`flag`, `environment` or `default`) + into a CLI report body after the command members. A report built without it + is unchanged. + - `registry-platform-httpsec` implements authcommon's `RefusalTraceId` for `TraceId` behind the opt-in `refusal-trace-id` feature, not `server`. A service that only serves HTTP no longer links `registry-platform-authcommon` From f4f74ba913b0ad4fbd769617f2a6638493768055 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:44:55 +0100 Subject: [PATCH 029/136] feat: answer /health and /ready with the shared bodies in four runtimes feat(casework): answer /health and /ready with the shared JSON bodies Both probes now answer application/json bodies with a status member, as the other services do, still with no token. A service that is not ready still answers 503. feat(coordinator): add the shared status member to /health and /ready The probe bodies keep their live and ready members and gain the status member the other services answer. The 503 body is unchanged. feat(scheduling): add /health and /ready beside /healthz and /readyz Scheduling answers the same probe paths and JSON bodies as the other services, with no token. The older paths keep answering an empty 200 for deployments that already probe them. feat(adapter): answer /health and /ready on the facade listener Load balancers and orchestrators can probe an Adapter without a token. /ready reports whether the journal migrations match the binary and the runtime role holds its journal privileges, with bodies that never vary with the project, and a project operation on either path is unserved under the reserved-path reason. Signed-off-by: Jeremi Joslin --- .../src/effective_contract.rs | 2 +- crates/registry-adapter-engine/src/load.rs | 10 +- crates/registry-adapter/src/facade.rs | 57 ++++ .../tests/effective_contract_live.rs | 2 +- .../registry-adapter/tests/health_routes.rs | 248 ++++++++++++++++++ crates/registry-casework/src/http.rs | 17 +- crates/registry-casework/tests/review_http.rs | 27 +- crates/registry-coordinator/src/http.rs | 48 +++- crates/registry-scheduling/src/http.rs | 20 ++ .../tests/postgres_commitments.rs | 39 +++ .../site/src/content/docs/operate/adapter.mdx | 20 ++ .../src/content/docs/operate/scheduling.mdx | 8 +- .../reference/apis/registry-scheduling.mdx | 12 +- .../reference/scheduling-configuration.mdx | 4 +- .../src/content/docs/security/scheduling.mdx | 4 +- products/adapter/CHANGELOG.md | 7 + products/casework/CHANGELOG.md | 4 + .../generated/registry-casework.openapi.json | 44 ++++ products/casework/scripts/generate_openapi.py | 9 +- products/coordinator/CHANGELOG.md | 5 + .../openapi/coordinator.openapi.json | 12 +- products/scheduling/CHANGELOG.md | 4 + .../registry-scheduling.openapi.json | 215 ++++++++++++++- .../scheduling/scripts/generate_openapi.py | 35 ++- .../scripts/test_generate_openapi.py | 19 +- 25 files changed, 826 insertions(+), 46 deletions(-) create mode 100644 crates/registry-adapter/tests/health_routes.rs diff --git a/crates/registry-adapter-engine/src/effective_contract.rs b/crates/registry-adapter-engine/src/effective_contract.rs index 388f6b58fb..46824c148b 100644 --- a/crates/registry-adapter-engine/src/effective_contract.rs +++ b/crates/registry-adapter-engine/src/effective_contract.rs @@ -432,7 +432,7 @@ fn public_unserved_reason(code: &str) -> &'static str { } "adapter.operation.route-missing" => "the binding has no loaded route", "adapter.operation.reserved-facade-path" => { - "the facade path is reserved for the Adapter effective-contract route" + "the facade path is reserved for the Adapter effective-contract, health and ready routes" } "adapter.operation.cursor-key-missing" => { "the paginated operation has no configured cursor key" diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index f64cfb7595..29fe064c91 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -1230,10 +1230,16 @@ fn compile_binding( &format!("{{{}}}", operation.record_type_parameter.as_str()), binding.record_type.as_str(), ); - if concrete_method_path == crate::effective_contract::WELL_KNOWN_PATH { + if [ + crate::effective_contract::WELL_KNOWN_PATH, + registry_platform_httputil::probe::HEALTH_PATH, + registry_platform_httputil::probe::READY_PATH, + ] + .contains(&concrete_method_path.as_str()) + { return Err(not_served( UnservedReason::ReservedFacadePath, - "the facade path is reserved for the Adapter effective-contract route", + "the facade path is reserved for the Adapter effective-contract, health and ready routes", )); } let is_post_read = diff --git a/crates/registry-adapter/src/facade.rs b/crates/registry-adapter/src/facade.rs index 6126c81b99..637023a52e 100644 --- a/crates/registry-adapter/src/facade.rs +++ b/crates/registry-adapter/src/facade.rs @@ -57,6 +57,8 @@ use crate::engine::route::{ run_async_status_poll, run_served_route_until, AsyncStatusPollKind, RouteContext, RouteFailure, EXCHANGE_DEADLINE, }; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; + use crate::govstack::consultation::{CAPABILITIES_PATH, MOUNT_PATH}; use crate::govstack::correlation::RequestCorrelation; use crate::idempotent::{ @@ -335,6 +337,20 @@ pub fn router(state: Arc) -> Router { } }), ); + let ready = Arc::clone(&state); + router = router + .route( + HEALTH_PATH, + get(|| async { probe_response(StatusCode::OK, HEALTH_BODY) }).fallback(probe_refusal), + ) + .route( + READY_PATH, + get(move || { + let shared = Arc::clone(&ready); + async move { readiness(shared).await } + }) + .fallback(probe_refusal), + ); let unmatched = Arc::clone(&state); let metrics = Arc::clone(&state.metrics); router @@ -946,6 +962,47 @@ async fn answer_async_status( } } +/// Body of a readiness probe that finds the journal unusable. It is a +/// constant: it names no project, source, client or database error. +const NOT_READY_BODY: &str = r#"{"status":"not-ready"}"#; + +/// A probe answer: a constant JSON body, no request id, no journal event. +fn probe_response(status: StatusCode, body: &'static str) -> Response { + let mut response = (status, body).into_response(); + response.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + no_store(response) +} + +/// A probe path called with a method other than GET. The answer is empty so +/// it does not vary with the project's problem document. +async fn probe_refusal() -> Response { + let mut response = no_store(StatusCode::METHOD_NOT_ALLOWED.into_response()); + response + .headers_mut() + .insert(header::ALLOW, HeaderValue::from_static("GET")); + response +} + +/// Unauthenticated readiness: whether the journal migration set is exactly +/// the set this binary supports and the runtime role holds its privileges. +/// It touches no source, appends no journal event, and answers a constant +/// body whatever the project or the cause of a failure. +async fn readiness(state: Arc) -> Response { + let journal_ready = match state.journal.get().await { + Ok(client) => journal::ready(&client).await.unwrap_or(false), + Err(_) => false, + }; + if journal_ready { + probe_response(StatusCode::OK, READY_BODY) + } else { + tracing::error!("the readiness probe found the journal unusable"); + probe_response(StatusCode::SERVICE_UNAVAILABLE, NOT_READY_BODY) + } +} + /// Return the immutable startup contract only to an authenticated machine /// caller and only while the live journal migration set is exactly the set /// this binary supports. This readiness check deliberately does not touch an diff --git a/crates/registry-adapter/tests/effective_contract_live.rs b/crates/registry-adapter/tests/effective_contract_live.rs index 73be8e7378..a0ed4ba49c 100644 --- a/crates/registry-adapter/tests/effective_contract_live.rs +++ b/crates/registry-adapter/tests/effective_contract_live.rs @@ -406,7 +406,7 @@ async fn a_valid_concrete_collision_is_unserved_before_router_construction() { ); assert_eq!( colliding["reason"], - "the facade path is reserved for the Adapter effective-contract route" + "the facade path is reserved for the Adapter effective-contract, health and ready routes" ); } assert_eq!( diff --git a/crates/registry-adapter/tests/health_routes.rs b/crates/registry-adapter/tests/health_routes.rs new file mode 100644 index 0000000000..7497faa650 --- /dev/null +++ b/crates/registry-adapter/tests/health_routes.rs @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Live HTTP proof for the unauthenticated `/health` and `/ready` probes of +//! the facade listener. Every test uses the real Adapter binary and a real +//! PostgreSQL journal. Absence of the database URL fails; it never turns +//! this boundary into a skipped test. +#![cfg(feature = "postgres-test")] + +#[allow(dead_code)] +#[path = "support/served/mod.rs"] +mod served_harness; + +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::time::Duration; + +use registry_adapter::engine::effective_contract::WELL_KNOWN_PATH; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; +use served_harness::upstream::UpstreamDouble; +use served_harness::{copy_example_project, replace_profile_text, Served}; + +const NOT_READY_BODY: &str = r#"{"status":"not-ready"}"#; + +/// One raw response: status, header lines (the `date` header, which the HTTP +/// server stamps per response, left out) and the body bytes. +#[derive(Debug, PartialEq, Eq)] +struct Raw { + status: u16, + headers: Vec, + body: Vec, +} + +fn raw(served: &Served, method: &str, path: &str, authorization: Option<&str>) -> Raw { + let mut stream = TcpStream::connect(("127.0.0.1", served.port)).expect("connect"); + stream + .set_read_timeout(Some(Duration::from_secs(30))) + .expect("timeout"); + let mut request = + format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"); + if let Some(value) = authorization { + request.push_str(&format!("Authorization: {value}\r\n")); + } + if method != "GET" { + request.push_str("Content-Length: 0\r\n"); + } + request.push_str("\r\n"); + stream.write_all(request.as_bytes()).expect("write"); + let mut bytes = Vec::new(); + stream.read_to_end(&mut bytes).expect("read"); + let split = bytes + .windows(4) + .position(|window| window == b"\r\n\r\n") + .expect("a header block"); + let head = String::from_utf8(bytes[..split].to_vec()).expect("utf8 headers"); + let mut lines = head.lines(); + let status = lines + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|code| code.parse().ok()) + .expect("a status code"); + let mut headers: Vec = lines + .filter(|line| !line.to_ascii_lowercase().starts_with("date:")) + .map(str::to_owned) + .collect(); + headers.sort(); + Raw { + status, + headers, + body: bytes[split + 4..].to_vec(), + } +} + +fn header<'a>(response: &'a Raw, name: &str) -> Option<&'a str> { + response.headers.iter().find_map(|line| { + let (candidate, value) = line.split_once(':')?; + candidate.eq_ignore_ascii_case(name).then(|| value.trim()) + }) +} + +fn assert_probe(response: &Raw, status: u16, body: &str) { + assert_eq!(response.status, status, "{response:?}"); + assert_eq!( + String::from_utf8_lossy(&response.body), + body, + "the body is the constant" + ); + assert_eq!(header(response, "content-type"), Some("application/json")); + assert!( + header(response, "x-registry-request-id").is_none(), + "a probe mints no request id: {response:?}" + ); +} + +#[tokio::test] +async fn probes_answer_identically_under_three_projects_with_and_without_authorization() { + let upstream = UpstreamDouble::start(); + let second = tempfile::tempdir().expect("a copied Adapter project"); + copy_example_project(second.path()); + replace_profile_text( + second.path(), + " path: /v1/records/{type}\n", + " path: /v9/records/{type}\n", + ); + let projects = [ + Served::start(&upstream.url("")).await, + Served::start_with_project(&upstream.url(""), &Served::govstack_project()).await, + Served::start_with_project(&upstream.url(""), second.path()).await, + ]; + + let mut seen: Vec> = Vec::new(); + for served in &projects { + let token = format!("Bearer {}", served.token("")); + let mut answers = Vec::new(); + for path in [HEALTH_PATH, READY_PATH] { + for authorization in [None, Some("Bearer not-a-token"), Some(token.as_str())] { + answers.push(raw(served, "GET", path, authorization)); + } + } + for (position, answer) in answers.iter().enumerate() { + let expected = if position < 3 { + HEALTH_BODY + } else { + READY_BODY + }; + assert_probe(answer, 200, expected); + } + // The same path answers byte-for-byte alike, whatever the header. + assert_eq!(answers[0], answers[1]); + assert_eq!(answers[0], answers[2]); + assert_eq!(answers[3], answers[4]); + assert_eq!(answers[3], answers[5]); + // A method other than GET refuses with no project-specific text. + let refused = raw(served, "POST", HEALTH_PATH, None); + assert_eq!(refused.status, 405, "{refused:?}"); + assert_eq!(header(&refused, "allow"), Some("GET")); + assert!(refused.body.is_empty(), "{refused:?}"); + answers.push(refused); + seen.push(answers); + } + assert_eq!(seen[0], seen[1], "the probes do not vary with the project"); + assert_eq!(seen[0], seen[2], "the probes do not vary with the project"); + assert_eq!( + upstream.request_count(), + 0, + "a probe never reaches a source" + ); +} + +#[tokio::test] +async fn a_journal_that_is_not_ready_answers_the_constant_503_without_database_text() { + let upstream = UpstreamDouble::start(); + let served = Served::start(&upstream.url("")).await; + assert_probe(&raw(&served, "GET", READY_PATH, None), 200, READY_BODY); + + served + .execute_sql( + "DELETE FROM adapter_schema_migrations \ + WHERE version = (SELECT max(version) FROM adapter_schema_migrations)", + ) + .await; + let drift = raw(&served, "GET", READY_PATH, None); + assert_probe(&drift, 503, NOT_READY_BODY); + + served + .execute_sql("DROP TABLE adapter_schema_migrations") + .await; + let missing = raw(&served, "GET", READY_PATH, Some("Bearer anything")); + assert_probe(&missing, 503, NOT_READY_BODY); + assert_eq!(drift, missing, "the refusal does not carry the cause"); + let text = String::from_utf8_lossy(&missing.body).to_lowercase(); + for fragment in ["relation", "adapter_", "postgres", "sql", "error"] { + assert!(!text.contains(fragment), "{fragment} leaked: {text}"); + } + assert_probe(&raw(&served, "GET", HEALTH_PATH, None), 200, HEALTH_BODY); + assert_eq!( + upstream.request_count(), + 0, + "readiness never probes a source" + ); +} + +#[tokio::test] +async fn probes_append_no_journal_row() { + let upstream = UpstreamDouble::start(); + let served = Served::start(&upstream.url("")).await; + let before = served.journal_kinds().await; + for _ in 0..3 { + for path in [HEALTH_PATH, READY_PATH] { + assert_eq!(raw(&served, "GET", path, None).status, 200); + } + } + served + .execute_sql("DROP TABLE adapter_schema_migrations") + .await; + assert_eq!(raw(&served, "GET", READY_PATH, None).status, 503); + assert_eq!( + served.journal_kinds().await, + before, + "neither a ready nor a not-ready probe appends an event" + ); +} + +#[tokio::test] +async fn a_project_declaring_health_or_ready_is_unserved_with_the_reserved_path_reason() { + for (record_type, probe_path, body) in [ + ("health", HEALTH_PATH, HEALTH_BODY), + ("ready", READY_PATH, READY_BODY), + ] { + let upstream = UpstreamDouble::start(); + let directory = tempfile::tempdir().expect("a copied Adapter project"); + copy_example_project(directory.path()); + replace_profile_text( + directory.path(), + " path: /v1/records/{type}\n", + " path: /{type}\n", + ); + let project_path = directory.path().join("project.yaml"); + let project = + std::fs::read_to_string(&project_path).expect("the copied project is readable"); + std::fs::write(&project_path, project.replace("person", record_type)) + .expect("write the colliding project"); + + let served = Served::start_with_project(&upstream.url(""), directory.path()).await; + assert_probe(&raw(&served, "GET", probe_path, None), 200, body); + + let token = served.token(""); + let readback = served.get(WELL_KNOWN_PATH, Some(&token)); + assert_eq!(readback.0, 200, "{}", readback.2); + let unserved = readback.2["contract"]["unserved"] + .as_array() + .expect("the contract carries unserved operations"); + let colliding: Vec<_> = unserved + .iter() + .filter(|entry| entry["reasonCode"] == "adapter.operation.reserved-facade-path") + .collect(); + assert!( + !colliding.is_empty(), + "{probe_path} is refused as reserved: {unserved:?}" + ); + for entry in colliding { + assert_eq!( + entry["reason"], + "the facade path is reserved for the Adapter effective-contract, health and ready routes" + ); + } + assert_eq!(upstream.request_count(), 0); + } +} diff --git a/crates/registry-casework/src/http.rs b/crates/registry-casework/src/http.rs index 4eab6c496a..0b9b4419df 100644 --- a/crates/registry-casework/src/http.rs +++ b/crates/registry-casework/src/http.rs @@ -17,6 +17,7 @@ use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use serde_json::error::Category; use uuid::Uuid; @@ -91,8 +92,8 @@ pub fn router(state: HttpState) -> Router { post(cancel_review_request), ); let app = Router::new() - .route("/health", get(health)) - .route("/ready", get(ready)) + .route(HEALTH_PATH, get(health)) + .route(READY_PATH, get(ready)) .route("/v1/casework", get(description)) .route("/.well-known/jwks.json", get(task_jwks)) .route("/v1/task-grants/{grant_id}/assertion", post(task_assertion)) @@ -468,13 +469,17 @@ async fn method_not_allowed() -> Response { problem_response(ProblemCode::RequestMethodNotAllowed, None, None) } -async fn health() -> StatusCode { - StatusCode::OK +fn probe_response(body: &'static str) -> Response { + ([(CONTENT_TYPE, "application/json")], body).into_response() } -async fn ready(RequestState(state): RequestState) -> Result { +async fn health() -> Response { + probe_response(HEALTH_BODY) +} + +async fn ready(RequestState(state): RequestState) -> Result { if state.service.ready().await.is_ok() { - Ok(StatusCode::OK) + Ok(probe_response(READY_BODY)) } else { Err(HttpError::ServiceUnavailable) } diff --git a/crates/registry-casework/tests/review_http.rs b/crates/registry-casework/tests/review_http.rs index 9ed3bbdc23..a1ac31e308 100644 --- a/crates/registry-casework/tests/review_http.rs +++ b/crates/registry-casework/tests/review_http.rs @@ -26,7 +26,10 @@ use registry_casework_client::{ use registry_casework_core::*; use registry_platform_config::{SecretProvider, SecretResolver}; -use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_httputil::{ + probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}, + FetchUrlPolicy, +}; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; use registry_platform_testing::{oidc_verifier_config, MockIdp}; use serde_json::{json, Value}; @@ -900,6 +903,28 @@ fn create_http_request(body: &ReviewCreateRequest, token: Option<&str>) -> Reque .expect("review HTTP request") } +#[tokio::test] +async fn health_and_ready_answer_the_shared_probe_bodies_without_a_token() { + let idp = MockIdp::start().await; + let (app, _service, _revoked, _changed, _failure, _source_state) = app(&idp).await; + for (path, expected) in [(HEALTH_PATH, HEALTH_BODY), (READY_PATH, READY_BODY)] { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK, "{path}"); + assert_eq!( + response.headers().get(CONTENT_TYPE).unwrap(), + "application/json", + "{path}" + ); + let body = to_bytes(response.into_body(), 1024).await.unwrap(); + assert_eq!(body.as_ref(), expected.as_bytes(), "{path}"); + } + idp.stop().await; +} + #[tokio::test] async fn delegated_reader_credential_cannot_enter_producer_create_or_cancel_routes() { let idp = MockIdp::start().await; diff --git a/crates/registry-coordinator/src/http.rs b/crates/registry-coordinator/src/http.rs index 491f29d2e6..0a08d316bf 100644 --- a/crates/registry-coordinator/src/http.rs +++ b/crates/registry-coordinator/src/http.rs @@ -28,6 +28,7 @@ use axum::{ use registry_platform_httpsec::{ normalize_framework_rejection, FrameworkRejection, ProblemBody, TraceContext, }; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use serde::{de::DeserializeOwned, Deserialize}; use serde_json::{json, Value}; use std::{future::Future, sync::Arc, time::Duration}; @@ -121,9 +122,9 @@ pub fn router(state: HttpState) -> Router { let ready_state = state.clone(); let ready_bindings = Arc::new(BindingReadiness::default()); let routes = Router::new() - .route("/health", get(|| async { Json(json!({"live":true})) })) + .route(HEALTH_PATH, get(|| async { Json(live_body()) })) .route( - "/ready", + READY_PATH, get(move || ready(ready_state.clone(), ready_bindings.clone())), ) .route("/v1/workflows/{workflow}", get(workflow_contract)) @@ -331,6 +332,18 @@ async fn authenticated_caller(s: &HttpState, headers: &HeaderMap) -> Result Value { + let mut body: Value = serde_json::from_str(shared).expect("shared probe bodies are JSON"); + body[member] = json!(true); + body +} +fn live_body() -> Value { + probe_body(HEALTH_BODY, "live") +} +fn ready_body() -> Value { + probe_body(READY_BODY, "ready") +} async fn ready(s: HttpState, bindings: Arc) -> Response { if !s.recovery_only && deployment::check(&s.store, &s.runtime, s.workflows.digest()) @@ -341,7 +354,7 @@ async fn ready(s: HttpState, bindings: Arc) -> Response { .check(|| s.store.check_runtime_bindings(&s.runtime)) .await { - (StatusCode::OK, Json(json!({"ready":true}))).into_response() + (StatusCode::OK, Json(ready_body())).into_response() } else { ( StatusCode::SERVICE_UNAVAILABLE, @@ -775,6 +788,31 @@ mod problem_tests { .flat_map(|path| path.as_object().unwrap().iter()) } + #[test] + fn probe_bodies_keep_their_own_member_and_add_the_shared_status() { + assert_eq!(live_body(), json!({"live":true,"status":"ok"})); + assert_eq!(ready_body(), json!({"ready":true,"status":"ready"})); + } + + #[test] + fn probe_routes_use_the_shared_paths() { + let document = openapi(); + for (path, key, word) in [ + (registry_platform_httputil::probe::HEALTH_PATH, "live", "ok"), + ( + registry_platform_httputil::probe::READY_PATH, + "ready", + "ready", + ), + ] { + let schema = &document["paths"][path]["get"]["responses"]["200"]["content"] + ["application/json"]["schema"]; + assert_eq!(schema["required"], json!([key, "status"]), "{path}"); + assert_eq!(schema["properties"][key]["type"], "boolean", "{path}"); + assert_eq!(schema["properties"]["status"]["const"], word, "{path}"); + } + } + #[test] fn openapi_summarizes_every_operation_once() { let document = openapi(); @@ -1789,9 +1827,9 @@ pub fn openapi() -> Value { ); paths[registry_review_protocol::REVIEW_COMPLETIONS_PATH]["post"]["responses"] = Value::Object(responses); - for (path, key) in [("/health", "live"), ("/ready", "ready")] { + for (path, key, word) in [(HEALTH_PATH, "live", "ok"), (READY_PATH, "ready", "ready")] { let mut responses = problem_responses(&[ProblemCode::RequestMethodNotAllowed]); - responses.insert("200".into(), json!({"description":"Health result","content":{"application/json":{"schema":{"type":"object","required":[key],"properties":{key:{"type":"boolean"}}}}}})); + responses.insert("200".into(), json!({"description":"Health result","content":{"application/json":{"schema":{"type":"object","required":[key,"status"],"properties":{key:{"type":"boolean"},"status":{"const":word}}}}}})); responses.insert( "503".into(), json!({"description":"Deployment unavailable or in recovery hold"}), diff --git a/crates/registry-scheduling/src/http.rs b/crates/registry-scheduling/src/http.rs index 113bc853d6..f6b5e21afb 100644 --- a/crates/registry-scheduling/src/http.rs +++ b/crates/registry-scheduling/src/http.rs @@ -37,6 +37,7 @@ use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use registry_scheduling_core::{ type_uri, valid_identifier, valid_reference, AdmissionRequest, AvailabilityPreviewRequest, CancelAppointmentRequest, CreateAppointmentRequest, ExternalReference, ProblemCode, @@ -88,6 +89,8 @@ pub fn metrics_router(metrics: Arc, store: PostgresStore) -> Router { pub fn router(state: HttpState) -> Router { http_edge( Router::new() + .route(HEALTH_PATH, get(health)) + .route(READY_PATH, get(ready)) .route("/healthz", get(healthz)) .route("/readyz", get(readyz)) .route(SCHEDULING_PATH, get(scheduling)) @@ -251,6 +254,23 @@ async fn method_not_allowed() -> Response { problem_response(ProblemCode::RequestMethodNotAllowed) } +fn probe_response(body: &'static str) -> Response { + ([(CONTENT_TYPE, "application/json")], body).into_response() +} + +async fn health() -> Response { + probe_response(HEALTH_BODY) +} + +/// Ready on the same terms as `readyz`. +async fn ready(State(state): State) -> Result { + if state.service.ready().await.is_ok() { + Ok(probe_response(READY_BODY)) + } else { + Err(HttpError(ProblemCode::ServiceUnavailable)) + } +} + async fn healthz() -> StatusCode { StatusCode::OK } diff --git a/crates/registry-scheduling/tests/postgres_commitments.rs b/crates/registry-scheduling/tests/postgres_commitments.rs index 3984ce2aeb..2c22a59906 100644 --- a/crates/registry-scheduling/tests/postgres_commitments.rs +++ b/crates/registry-scheduling/tests/postgres_commitments.rs @@ -23,6 +23,7 @@ use registry_platform_config::{SecretProvider, SecretReference, SecretResolver}; use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields}; use registry_platform_hooks::delivery::DeliveryOutcome; use registry_platform_hooks::{EnvelopeLimits, HookEnvelope, HookHandlerSource}; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use registry_platform_oidc::{ task_grant::{TaskGrantStatusEndpoint, TaskGrantStatusRegistry}, JwksFetcher, JwksFetcherConfig, TokenVerifierConfig, @@ -5890,6 +5891,38 @@ async fn an_allowed_commitment_writes_its_request_before_and_its_response_after( } } +/// The shared probe routes answer their fixed bodies with no token. The +/// older `/healthz` and `/readyz` spellings keep answering an empty 200. +#[tokio::test] +async fn probe_routes_answer_the_shared_bodies_and_the_older_spellings_still_answer() { + let fx = fixture().await; + for (path, expected) in [ + (HEALTH_PATH, Some(HEALTH_BODY)), + (READY_PATH, Some(READY_BODY)), + ("/healthz", None), + ("/readyz", None), + ] { + let response = fx + .http + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()) + .await + .expect("an in-process request always answers"); + assert_eq!(response.status(), StatusCode::OK, "{path}"); + let content_type = response.headers().get("content-type").cloned(); + let body = to_bytes(response.into_body(), 1024) + .await + .expect("a bounded test body"); + match expected { + Some(expected) => { + assert_eq!(content_type.unwrap(), "application/json", "{path}"); + assert_eq!(body.as_ref(), expected.as_bytes(), "{path}"); + } + None => assert!(body.is_empty(), "{path}"), + } + } +} + /// SCHEDULING-SEC-14: a commitment whose request entry the destination /// refuses never opens its capacity transaction. No claim is taken, no /// receipt is stored, and the caller is told the service is unavailable. @@ -5920,6 +5953,12 @@ async fn a_refused_request_entry_opens_no_capacity_transaction() { StatusCode::SERVICE_UNAVAILABLE, "readiness follows the audit destination" ); + let (status, _) = fx.get(READY_PATH, &fx.reader).await; + assert_eq!( + status, + StatusCode::SERVICE_UNAVAILABLE, + "the shared readiness route follows the audit destination" + ); } /// SCHEDULING-SEC-14: the response entry is written after commit. When the diff --git a/docs/site/src/content/docs/operate/adapter.mdx b/docs/site/src/content/docs/operate/adapter.mdx index 884fdc9e6a..dafcef209b 100644 --- a/docs/site/src/content/docs/operate/adapter.mdx +++ b/docs/site/src/content/docs/operate/adapter.mdx @@ -806,6 +806,26 @@ The stop report prints the same fix as its `next` step. {/* TODO[evidence]: no test names adapter.job.page-bytes-bound or the maximumRowsPerPage times maximumRowBytes memory ceiling; only the code that raises the stop is cited. */} +## Probe health and readiness + +The facade listener answers two probes without authentication, for load balancers and +orchestrators: + +- `GET /health` answers 200 `{"status":"ok"}` and does no work. +- `GET /ready` answers 200 `{"status":"ready"}` when the journal migrations match the binary + and the runtime role holds its journal privileges, and 503 `{"status":"not-ready"}` otherwise. + It reads the journal store and never contacts a source. + +The bodies are fixed and do not vary with the project. They tell a caller that an Adapter is +listening and whether its journal is usable, and nothing more. Because `/health` and `/ready` +belong to the listener, a project operation whose path is one of them is unserved, with the +reason code `adapter.operation.reserved-facade-path` in the effective contract. + +{/* Evidence: crates/registry-adapter/src/facade.rs; + crates/registry-adapter/src/journal.rs ready; + crates/registry-adapter/tests/health_routes.rs; + crates/registry-adapter-engine/src/load.rs ReservedFacadePath. */} + ## Scrape metrics Neither the facade listener nor the hook ingress serves metrics. Set `metricsListener.bind` in the diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index 1b460af3eb..2d7c554036 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -303,16 +303,16 @@ versions, a package that was not applied, and a database that names another `dat route instead: ```sh -curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8105/readyz +curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8105/ready ``` ```text 200 ``` -`/readyz` answers unavailable while PostgreSQL is unreachable, while the schema is not the one +`/ready` answers unavailable while PostgreSQL is unreachable, while the schema is not the one this release expects, and while the audit destination refuses writes, because no booking proceeds -without its audit entry. +without its audit entry. `/readyz` answers the same way with an empty body. ## Read the deployment @@ -445,7 +445,7 @@ to a new, empty database; the old ledger is not carried over. {/* Evidence: crates/registry-schedulingctl/src/{activation,records,intents}.rs; crates/registry-scheduling/src/store/activation.rs, publication and PolicyInUse; crates/registry-scheduling/src/runtime.rs, startup ready() and check_active_package(), workers - and retention; crates/registry-scheduling/src/http.rs, readyz(); + and retention; crates/registry-scheduling/src/http.rs, ready() and readyz(); crates/registry-schedulingctl/src/project.rs, package(); crates/registry-platform-config/src/loader.rs, validate_absolute_lexical_path(); crates/registry-scheduling/src/config.rs. Success lines observed with scheduling 0.42.0-dev against PostgreSQL 17, the standalone-exact-time project, and single-role credentials. */} diff --git a/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx b/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx index 936db918f2..a3bde4e337 100644 --- a/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx +++ b/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx @@ -296,12 +296,16 @@ checked per route. | Holds | `/v1/holds`, `/v1/holds/{holdId}` | Commitment | | Appointments | `/v1/appointments`, `/v1/appointments/{appointmentId}`, its `reschedule`, `cancel`, and `history` | Commitment for the mutations; Catalogue read for the reads | | Appointment receipt observation | `/v1/appointments/receipt` | Catalogue read, matching the exact original owner, key, and creation request | -| Liveness and readiness | `/healthz`, `/readyz` | Any caller, without a token | +| Liveness and readiness | `/health`, `/ready`, and the older `/healthz`, `/readyz` | Any caller, without a token | -`/readyz` answers `service.unavailable` while PostgreSQL is unreachable, while the schema is not -the one this release expects, and while the audit writer is not ready. +`/health` answers `{"status":"ok"}` and `/ready` answers `{"status":"ready"}`, both as +`application/json`. `/healthz` and `/readyz` keep answering an empty 200 for deployments that already +probe them. -{/* Evidence: crates/registry-scheduling/src/http.rs, router() and readyz(); +`/ready` and `/readyz` answer `service.unavailable` while PostgreSQL is unreachable, while the schema +is not the one this release expects, and while the audit writer is not ready. + +{/* Evidence: crates/registry-scheduling/src/http.rs, router(), health(), ready() and readyz(); crates/registry-scheduling-core/src/naming.rs, SCHEDULING_PATH, SERVICES_PATH, OFFERINGS_PATH, RESOURCES_PATH, LOCATIONS_PATH, AVAILABILITY_PATH, AVAILABILITY_EXPLAIN_PATH, HOLDS_PATH, and APPOINTMENTS_PATH and APPOINTMENT_RECEIPT_PATH; crates/registry-scheduling/src/store.rs, diff --git a/docs/site/src/content/docs/reference/scheduling-configuration.mdx b/docs/site/src/content/docs/reference/scheduling-configuration.mdx index 8aaa0cedff..3879edbcd8 100644 --- a/docs/site/src/content/docs/reference/scheduling-configuration.mdx +++ b/docs/site/src/content/docs/reference/scheduling-configuration.mdx @@ -561,14 +561,14 @@ separate connection that changes nothing: `service.unavailable`, because it may have taken effect. A retry under the same idempotency key then replays whatever committed. -`/readyz` reports unavailable while the destination refuses writes. +`/ready` and `/readyz` report unavailable while the destination refuses writes. An expired hold writes its history entry as `system` and no audit entry. {/* Evidence: crates/registry-scheduling/src/config.rs AuditConfig, the_audit_block_takes_a_file_or_stdout_destination, MAXIMUM_AUDIT_ROTATE_BYTES; crates/registry-scheduling/src/audit.rs; crates/registry-scheduling/src/service.rs commitment.unfinished, idempotency.expired; - crates/registry-scheduling/src/http.rs readyz; + crates/registry-scheduling/src/http.rs ready and readyz; crates/registry-scheduling/tests/postgres_commitments.rs. */} ## Destinations diff --git a/docs/site/src/content/docs/security/scheduling.mdx b/docs/site/src/content/docs/security/scheduling.mdx index b87582c38e..b42afb76bc 100644 --- a/docs/site/src/content/docs/security/scheduling.mdx +++ b/docs/site/src/content/docs/security/scheduling.mdx @@ -68,13 +68,13 @@ after the transaction ends. If either entry is refused, the caller gets `service.unavailable` instead of an unaudited answer. A refused `request` entry opens no transaction; a refused `response` entry after the commit answers `service.unavailable` with the commitment in place. -`/readyz` follows the audit writer. +`/ready` and `/readyz` follow the audit writer. {/* Evidence: crates/registry-scheduling/tests/postgres_commitments.rs a_refused_request_entry_opens_no_capacity_transaction, a_failed_capacity_transaction_pairs_its_request_entry, a_replayed_receipt_is_released_only_after_its_response_entry_is_accepted; - crates/registry-scheduling/src/http.rs readyz; + crates/registry-scheduling/src/http.rs ready and readyz; crates/registry-scheduling/src/service.rs audit_ready. */} ## Operator obligations diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index d1a93aa2fc..bd27aca006 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- The facade listener answers `GET /health` and `GET /ready` without + authentication. `/health` answers `{"status":"ok"}`. `/ready` answers + `{"status":"ready"}` when the journal migrations match the binary and the + runtime role holds its journal privileges, and a constant 503 + `{"status":"not-ready"}` otherwise. The bodies never vary with the + project. A project operation whose facade path is `/health` or `/ready` is + unserved under `adapter.operation.reserved-facade-path`. - `adapter serve` grants the runtime database role the table privileges its deployment needs, after it migrates and before it listens, when the runtime and migration sessions run as different roles. The grantee is the role the diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index f7e25a466e..40ccadf9bc 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- `GET /health` answers `{"status":"ok"}` and `GET /ready` answers + `{"status":"ready"}` as `application/json`, in place of an empty 200. Both + still need no token, and a service that is not ready still answers 503. + ## 0.47.0 - 2026-11-21 - BREAKING: `caseworkctl provider add` prints the BReg project fragments it diff --git a/products/casework/generated/registry-casework.openapi.json b/products/casework/generated/registry-casework.openapi.json index 59cde8336f..9445320943 100644 --- a/products/casework/generated/registry-casework.openapi.json +++ b/products/casework/generated/registry-casework.openapi.json @@ -886,6 +886,21 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, + "HealthStatus": { + "description": "Probe answer. Members beside status may be added.", + "properties": { + "status": { + "enum": [ + "ok" + ], + "type": "string" + } + }, + "required": [ + "status" + ], + "type": "object" + }, "HolidaySetDocument": { "additionalProperties": false, "description": "One live, revisioned holiday set supplied separately from deployed policy.", @@ -2509,6 +2524,21 @@ ], "type": "object" }, + "ReadyStatus": { + "description": "Probe answer. Members beside status may be added.", + "properties": { + "status": { + "enum": [ + "ready" + ], + "type": "string" + } + }, + "required": [ + "status" + ], + "type": "object" + }, "ReviewAccountabilityRecord": { "additionalProperties": false, "properties": { @@ -5587,6 +5617,13 @@ ], "responses": { "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HealthStatus" + } + } + }, "description": "Success", "headers": { "traceparent": { @@ -5675,6 +5712,13 @@ ], "responses": { "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadyStatus" + } + } + }, "description": "Success", "headers": { "traceparent": { diff --git a/products/casework/scripts/generate_openapi.py b/products/casework/scripts/generate_openapi.py index 83e6eef28a..f61606f775 100644 --- a/products/casework/scripts/generate_openapi.py +++ b/products/casework/scripts/generate_openapi.py @@ -36,8 +36,8 @@ class Endpoint: # Transport metadata only. DTO shapes and all statuses/problems come from Rust. ENDPOINTS = [ - Endpoint("GET","/health","health",public=True), - Endpoint("GET","/ready","readiness",public=True), + Endpoint("GET","/health","health","HealthStatus",public=True), + Endpoint("GET","/ready","readiness","ReadyStatus",public=True), Endpoint("GET","/.well-known/jwks.json","getTaskAuthorityKeys","TaskAuthorityJwks",public=True), Endpoint("GET","/v1/casework","describeCasework","Description"), Endpoint("GET","/v1/review-policies","listReviewPolicies","ReviewPolicyClosureList"), @@ -127,6 +127,8 @@ def rewrite(value): put(component(name), rewrite(definition)) put(root_name, rewrite(schema)) result["TaskAuthorityJwks"] = {"type":"object","description":"JSON Web Key Set of the configured task authority's public verification keys.","required":["keys"],"properties":{"keys":{"type":"array","items":{"type":"object"}}}} + for name,word in (("HealthStatus","ok"),("ReadyStatus","ready")): + result[name]={"type":"object","description":"Probe answer. Members beside status may be added.","required":["status"],"properties":{"status":{"type":"string","enum":[word]}}} return result def parameter(name: str, where: str, schema: dict, required: bool = False, description: str = "") -> dict: @@ -281,7 +283,8 @@ def walk(value): def verify_source(repository_root: Path, openapi: dict) -> None: source=(repository_root/"crates/registry-casework/src/http.rs").read_text().split("#[cfg(test)]",1)[0] - routes=set(re.findall(r'\.route\(\s*"([^"]+)"',source)) + probe_paths={"HEALTH_PATH":"/health","READY_PATH":"/ready"} + routes={literal or probe_paths[name] for literal,name in re.findall(r'\.route\(\s*(?:"([^"]+)"|([A-Z_]+_PATH))',source)} if routes!=set(openapi["paths"]):raise ValueError(f"runtime route inventory drifted: {sorted(routes ^ set(openapi['paths']))}") if "SourceBinding" in openapi["components"]["schemas"]:raise ValueError("retired SourceBinding remains") rendered=json.dumps(openapi) diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index 4739f682dd..4b9f4b17e3 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- `GET /health` and `GET /ready` carry the `status` member the other + services answer: `{"live":true,"status":"ok"}` and + `{"ready":true,"status":"ready"}`. The `live` and `ready` members stay, and + the 503 body is unchanged. + - 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 diff --git a/products/coordinator/generated/openapi/coordinator.openapi.json b/products/coordinator/generated/openapi/coordinator.openapi.json index 672b07189f..7296057fc4 100644 --- a/products/coordinator/generated/openapi/coordinator.openapi.json +++ b/products/coordinator/generated/openapi/coordinator.openapi.json @@ -1196,10 +1196,14 @@ "properties": { "live": { "type": "boolean" + }, + "status": { + "const": "ok" } }, "required": [ - "live" + "live", + "status" ], "type": "object" } @@ -1248,10 +1252,14 @@ "properties": { "ready": { "type": "boolean" + }, + "status": { + "const": "ready" } }, "required": [ - "ready" + "ready", + "status" ], "type": "object" } diff --git a/products/scheduling/CHANGELOG.md b/products/scheduling/CHANGELOG.md index 1295ac5d3c..8031d4182c 100644 --- a/products/scheduling/CHANGELOG.md +++ b/products/scheduling/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- Add `GET /health` and `GET /ready`, answering `{"status":"ok"}` and + `{"status":"ready"}` as `application/json` with no token, as the other + services do. `/healthz` and `/readyz` keep answering an empty 200. + - A task grant with more than 900 seconds left on the offline path (`taskGrantStatus: unchecked-final-fifteen-minutes`) now answers 403 `grant.lifetime-too-long` in place of `operation.not-authorized`, so the diff --git a/products/scheduling/generated/registry-scheduling.openapi.json b/products/scheduling/generated/registry-scheduling.openapi.json index 904c244fba..7432330fa2 100644 --- a/products/scheduling/generated/registry-scheduling.openapi.json +++ b/products/scheduling/generated/registry-scheduling.openapi.json @@ -1075,6 +1075,21 @@ ], "type": "object" }, + "HealthStatus": { + "additionalProperties": true, + "properties": { + "status": { + "enum": [ + "ok" + ], + "type": "string" + } + }, + "required": [ + "status" + ], + "type": "object" + }, "HoldDocument": { "additionalProperties": true, "properties": { @@ -2549,6 +2564,21 @@ } ] }, + "ReadyStatus": { + "additionalProperties": true, + "properties": { + "status": { + "enum": [ + "ready" + ], + "type": "string" + } + }, + "required": [ + "status" + ], + "type": "object" + }, "RecordAttendanceRequest": { "additionalProperties": false, "properties": { @@ -2786,10 +2816,10 @@ }, "openapi": "3.1.0", "paths": { - "/healthz": { + "/health": { "get": { "description": "Process is live. No authentication, no storage, no policy.", - "operationId": "getLiveness", + "operationId": "getHealth", "parameters": [ { "description": "Optional W3C trace context continued in the response.", @@ -2803,6 +2833,13 @@ ], "responses": { "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HealthStatus" + } + } + }, "description": "Success", "headers": { "cache-control": { @@ -2855,10 +2892,79 @@ "x-scheduling-authority": "unauthenticated" } }, - "/readyz": { + "/healthz": { + "get": { + "description": "Process is live. No authentication, no storage, no policy. Answers an empty 200 and stays beside /health for deployments that already probe it.", + "operationId": "getLiveness", + "parameters": [ + { + "description": "Optional W3C trace context continued in the response.", + "in": "header", + "name": "traceparent", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Success", + "headers": { + "cache-control": { + "$ref": "#/components/headers/CacheControlHeader" + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "405": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestMethodNotAllowed" + } + } + }, + "description": "Problem response: request.method-not-allowed", + "headers": { + "cache-control": { + "$ref": "#/components/headers/CacheControlHeader" + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "413": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestBodyTooLarge" + } + } + }, + "description": "Problem response: request.body-too-large", + "headers": { + "cache-control": { + "$ref": "#/components/headers/CacheControlHeader" + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + } + }, + "security": [], + "summary": "Liveness, older spelling", + "x-scheduling-authority": "unauthenticated" + } + }, + "/ready": { "get": { "description": "Asks the Scheduling store to answer. A store that cannot answer is service.unavailable, with Retry-After.", - "operationId": "getReadiness", + "operationId": "getReady", "parameters": [ { "description": "Optional W3C trace context continued in the response.", @@ -2872,6 +2978,13 @@ ], "responses": { "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadyStatus" + } + } + }, "description": "Success", "headers": { "cache-control": { @@ -2949,6 +3062,100 @@ "x-scheduling-authority": "unauthenticated" } }, + "/readyz": { + "get": { + "description": "Asks the Scheduling store to answer. A store that cannot answer is service.unavailable, with Retry-After. Answers an empty 200 and stays beside /ready for deployments that already probe it.", + "operationId": "getReadiness", + "parameters": [ + { + "description": "Optional W3C trace context continued in the response.", + "in": "header", + "name": "traceparent", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Success", + "headers": { + "cache-control": { + "$ref": "#/components/headers/CacheControlHeader" + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "405": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestMethodNotAllowed" + } + } + }, + "description": "Problem response: request.method-not-allowed", + "headers": { + "cache-control": { + "$ref": "#/components/headers/CacheControlHeader" + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "413": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestBodyTooLarge" + } + } + }, + "description": "Problem response: request.body-too-large", + "headers": { + "cache-control": { + "$ref": "#/components/headers/CacheControlHeader" + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemServiceUnavailable" + } + } + }, + "description": "Problem response: service.unavailable", + "headers": { + "Retry-After": { + "description": "Seconds before retrying the unavailable dependency; the runtime answers 5.", + "schema": { + "minimum": 0, + "type": "integer" + } + }, + "cache-control": { + "$ref": "#/components/headers/CacheControlHeader" + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + } + }, + "security": [], + "summary": "Readiness, older spelling", + "x-scheduling-authority": "unauthenticated" + } + }, "/v1/appointments": { "get": { "description": "Lists only the authenticated caller's appointments carrying the exact opaque reference. The 15-minute cursor is bound to both the caller and the reference, and ownership is rechecked on every page. Claims whose owner has been erased are absent. Scheduling stores the tuple without calling the referenced product.", diff --git a/products/scheduling/scripts/generate_openapi.py b/products/scheduling/scripts/generate_openapi.py index 9bd0ee01b0..e32f118c72 100644 --- a/products/scheduling/scripts/generate_openapi.py +++ b/products/scheduling/scripts/generate_openapi.py @@ -48,6 +48,7 @@ TYPED_SOURCE = "crates/registry-scheduling-core/src/typed.rs" OPERATIONAL_SOURCE = "crates/registry-scheduling-core/src/operational.rs" BUSY_SOURCE = "crates/registry-scheduling-core/src/source_busy.rs" +PROBE_SOURCE = "crates/registry-platform-httputil/src/probe.rs" ATTENDANCE_SOURCE = "crates/registry-scheduling-core/src/attendance.rs" ADMISSION_SOURCE = "crates/registry-scheduling-core/src/admission.rs" PROBLEM_SOURCE = "crates/registry-scheduling-core/src/problem.rs" @@ -60,6 +61,8 @@ # this set from the `axum` router, resolving the constants the router names # through `crates/registry-scheduling-core/src/naming.rs`. ROUTES = { + "/health", + "/ready", "/healthz", "/readyz", "/v1/scheduling", @@ -163,6 +166,8 @@ # The axum handler behind each operation. `verify_handler_wiring` reads the # handler back out of http.rs and checks the document against what it does. ROUTE_HANDLERS = { + ("GET", "/health"): "health", + ("GET", "/ready"): "ready", ("GET", "/healthz"): "healthz", ("GET", "/readyz"): "readyz", ("GET", "/v1/scheduling"): "scheduling", @@ -189,6 +194,8 @@ } OPERATION_IDS = { + ("GET", "/health"): "getHealth", + ("GET", "/ready"): "getReady", ("GET", "/healthz"): "getLiveness", ("GET", "/readyz"): "getReadiness", ("GET", "/v1/scheduling"): "describeScheduling", @@ -266,6 +273,8 @@ ] OPERATION_PROBLEMS = { + ("GET", "/health"): EDGE, + ("GET", "/ready"): EDGE + STORAGE, ("GET", "/healthz"): EDGE, ("GET", "/readyz"): EDGE + STORAGE, ("GET", "/v1/scheduling"): EDGE + AUTHENTICATION + STORAGE, @@ -635,6 +644,8 @@ def schemas(problem_entries: list[dict]) -> dict: {**busy_counts, "kind": {**text, "enum": ["applied", "already-applied"]}, "revision": revision}, [*busy_counts, "kind", "revision"], ), + "HealthStatus": answer({"status": {**text, "enum": ["ok"]}}, ["status"]), + "ReadyStatus": answer({"status": {**text, "enum": ["ready"]}}, ["status"]), "SchedulingServiceDocument": answer( {"schedulingId": text, "policyRevision": revision, "policyDigest": text}, ["schedulingId", "policyRevision", "policyDigest"], @@ -930,13 +941,23 @@ def document(contract: dict) -> dict: entries = contract["entries"] catalog = catalog_of(contract) paths = { - "/healthz": {"get": unauthenticated( + "/health": {"get": unauthenticated( "Liveness", "Process is live. No authentication, no storage, no policy.", + "HealthStatus", )}, - "/readyz": {"get": unauthenticated( + "/ready": {"get": unauthenticated( "Readiness", "Asks the Scheduling store to answer. A store that cannot answer is service.unavailable, with Retry-After.", + "ReadyStatus", + )}, + "/healthz": {"get": unauthenticated( + "Liveness, older spelling", + "Process is live. No authentication, no storage, no policy. Answers an empty 200 and stays beside /health for deployments that already probe it.", + )}, + "/readyz": {"get": unauthenticated( + "Readiness, older spelling", + "Asks the Scheduling store to answer. A store that cannot answer is service.unavailable, with Retry-After. Answers an empty 200 and stays beside /ready for deployments that already probe it.", )}, "/v1/scheduling": {"get": operation( "Describe this Scheduling deployment", @@ -1212,12 +1233,18 @@ def rust_function(source: str, name: str) -> tuple[str, str]: def route_inventory( - http_source: str, naming_source: str, operational_source: str = "", busy_source: str = "" + http_source: str, + naming_source: str, + operational_source: str = "", + busy_source: str = "", ) -> dict[tuple[str, str], str]: """The (method, path) -> handler table, read back out of the axum router.""" signature, body = rust_function(http_source, "router") + # The probe paths are the shared constants the router names from the HTTP + # helper crate, so their source is read from the repository itself. + probe_source = production_source(_root(), PROBE_SOURCE) constants: dict[str, str] = {} - for source in (naming_source, operational_source, busy_source, http_source): + for source in (naming_source, operational_source, busy_source, probe_source, http_source): constants.update( { name: value diff --git a/products/scheduling/scripts/test_generate_openapi.py b/products/scheduling/scripts/test_generate_openapi.py index 870db9b874..83c2b39fbf 100644 --- a/products/scheduling/scripts/test_generate_openapi.py +++ b/products/scheduling/scripts/test_generate_openapi.py @@ -232,7 +232,7 @@ def test_every_documented_problem_matches_its_pinned_rust_catalog_entry(self) -> self.assertEqual(entry["description"], properties["detail"]["const"]) self.assertEqual(entry["httpStatuses"][0], properties["status"]["const"]) self.assertEqual(34, len(self.contract["entries"])) - self.assertEqual(83, len(self.openapi["components"]["schemas"])) + self.assertEqual(85, len(self.openapi["components"]["schemas"])) def test_every_operation_answers_exactly_the_problems_it_was_mapped(self) -> None: for key, expected in GENERATOR.OPERATION_PROBLEMS.items(): @@ -340,6 +340,8 @@ def test_a_drifted_route_table_fails_the_generator(self) -> None: def test_an_operation_documents_the_authority_its_handler_uses(self) -> None: expected = { + ("GET", "/health"): "unauthenticated", + ("GET", "/ready"): "unauthenticated", ("GET", "/healthz"): "unauthenticated", ("GET", "/readyz"): "unauthenticated", ("GET", "/v1/scheduling"): "reads-scope", @@ -378,7 +380,7 @@ def test_an_operation_documents_the_authority_its_handler_uses(self) -> None: for item in path.values() ] self.assertEqual(1, authorities.count("explain-scope")) - self.assertEqual(2, authorities.count("unauthenticated")) + self.assertEqual(4, authorities.count("unauthenticated")) self.assertEqual(6, authorities.count("task-grant")) self.assertEqual(10, authorities.count("reads-scope")) self.assertEqual(2, authorities.count("busy-import-profile")) @@ -581,15 +583,22 @@ def test_a_fallible_service_method_always_documents_an_unavailable_dependency(se # Liveness is the one route that reaches neither the store nor the # issuer's key material. Every other route reaches at least one of # them, and an outage in either is answered with a retry. - if key == ("GET", "/healthz"): + if key in (("GET", "/health"), ("GET", "/healthz")): self.assertNotIn("service.unavailable", codes, key) else: self.assertIn("service.unavailable", codes, key) self.assertIn("Retry-After", operation(self.openapi, key)["responses"]["503"]["headers"]) def test_infrastructure_routes_are_open_and_distinguish_live_from_ready(self) -> None: - health = operation(self.openapi, ("GET", "/healthz")) - ready = operation(self.openapi, ("GET", "/readyz")) + for health_key, ready_key in ( + (("GET", "/health"), ("GET", "/ready")), + (("GET", "/healthz"), ("GET", "/readyz")), + ): + self.assert_infrastructure_routes_are_open(health_key, ready_key) + + def assert_infrastructure_routes_are_open(self, health_key, ready_key) -> None: + health = operation(self.openapi, health_key) + ready = operation(self.openapi, ready_key) self.assertEqual([], health["security"]) self.assertEqual([], ready["security"]) self.assertNotIn("requestBody", health) From b15584aacd4eb30cad83251f7e92495631999d9a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 04:52:56 +0100 Subject: [PATCH 030/136] feat: accept JSON probe bodies in the clients and package requesters in Messaging feat(messaging): let the client accept a JSON body from /health and /ready The Messaging client accepts an empty body or a bounded JSON object from either probe and refuses a larger one, so it keeps working when a runtime answers a JSON probe body. The runtime still answers an empty 200. feat(messaging): admit the package's requester clients with allowedClients: from-package An operator writes the admitted clients once, in the package: from-package admits exactly the clients the access profiles name. A written list still has to cover every profile's clients, and an omitted member, an empty list and unrestricted are still refused. rstack dev writes from-package. feat(documents): let the client accept a JSON body from /health The Documents client accepts an empty body or a bounded JSON object from the health probe and refuses a larger one, so it keeps working when the runtime answers a JSON probe body. feat(breg): let the client ignore members it does not know in a probe answer BRegProbeStatus still requires status and now ignores other members, so the client keeps working when /ready gains members. Signed-off-by: Jeremi Joslin --- crates/registry-breg-client/src/response.rs | 3 +- .../tests/http_boundary.rs | 15 + .../registry-documents-client/src/client.rs | 24 +- .../tests/http_boundary.rs | 61 ++++ .../registry-messaging-client/src/client.rs | 44 ++- .../tests/http_boundary.rs | 74 ++++- crates/registry-messaging-core/src/access.rs | 13 + crates/registry-messaging/src/config.rs | 277 +++++++++++++++--- crates/registry-messaging/src/runtime.rs | 3 +- crates/registry-messaging/src/schema.rs | 42 ++- .../tests/postgres_messages.rs | 27 ++ .../registry-messaging/tests/support/mod.rs | 27 +- .../tests/token_characterisation.rs | 10 +- .../registry-messagingctl/src/dev/borrowed.rs | 4 +- .../registry-messagingctl/src/dev/config.rs | 4 +- .../src/identity_facts.rs | 33 +-- .../src/content/docs/operate/messaging.mdx | 5 +- .../src/content/docs/security/messaging.mdx | 7 +- products/breg/CHANGELOG.md | 4 + products/documents/CHANGELOG.md | 5 + products/messaging/CHANGELOG.md | 11 + .../generated/runtime/runtime.schema.json | 24 +- .../scripts/check-config-conformance.py | 2 +- 23 files changed, 581 insertions(+), 138 deletions(-) diff --git a/crates/registry-breg-client/src/response.rs b/crates/registry-breg-client/src/response.rs index 0a07c7915d..ab70ed4d8c 100644 --- a/crates/registry-breg-client/src/response.rs +++ b/crates/registry-breg-client/src/response.rs @@ -2,8 +2,9 @@ use registry_platform_httpsec::TraceId; use serde::{Deserialize, Serialize}; use std::fmt; +/// The probe answer. Members other than `status` are ignored so the client +/// keeps working against servers that report more. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] pub struct BRegProbeStatus { pub status: String, } diff --git a/crates/registry-breg-client/tests/http_boundary.rs b/crates/registry-breg-client/tests/http_boundary.rs index af46af8971..c162ad2cc8 100644 --- a/crates/registry-breg-client/tests/http_boundary.rs +++ b/crates/registry-breg-client/tests/http_boundary.rs @@ -1008,3 +1008,18 @@ async fn derived_response_limits_retain_credentials_and_leave_the_original_bound assert_eq!(requests[0].uri, requests[1].uri); assert_eq!(requests[0].authorization, requests[1].authorization); } + +#[test] +fn probe_status_ignores_members_it_does_not_know() { + let status: registry_breg_client::BRegProbeStatus = serde_json::from_str( + r#"{"status":"ready","posture":"production","developmentSettings":[]}"#, + ) + .expect("unknown members are ignored"); + assert_eq!(status.status, "ready"); + assert!( + serde_json::from_str::( + r#"{"posture":"production"}"# + ) + .is_err() + ); +} diff --git a/crates/registry-documents-client/src/client.rs b/crates/registry-documents-client/src/client.rs index d4705c4c89..ada3adc05f 100644 --- a/crates/registry-documents-client/src/client.rs +++ b/crates/registry-documents-client/src/client.rs @@ -31,6 +31,7 @@ use crate::{DocumentsClientError, DocumentsProtocolFailure}; const JSON_MEDIA_TYPE: &str = "application/json"; const PROBLEM_MEDIA_TYPE: &str = "application/problem+json"; const MAXIMUM_PROBLEM_BYTES: u64 = 8 * 1024; +const MAXIMUM_PROBE_BYTES: u64 = 4096; const DEFAULT_MAXIMUM_RESPONSE_BYTES: u64 = 4 * 1024 * 1024; const MAXIMUM_RESPONSE_BYTES: u64 = 16 * 1024 * 1024; const DEFAULT_MAXIMUM_DOWNLOAD_BYTES: u64 = 16 * 1024 * 1024; @@ -271,7 +272,8 @@ impl DocumentsClient { }) } - /// Whether the process answers at all. + /// Whether the process answers at all. The answer is 200 with an empty + /// body or a JSON object of at most 4096 bytes whose members are ignored. pub async fn health(&self) -> Result, DocumentsClientError> { let url = self.url(HEALTH_PATH, &[])?; let response = @@ -289,10 +291,10 @@ impl DocumentsClient { return Err(problem_or_status(response).await); } let trace_id = response_trace(status, response.headers())?; - // The health answer has no body, so any byte is a protocol failure - // rather than a response the caller's bound was too small for. - match read_bounded(response, 0).await { - Ok(_) => {} + // The probe answers an empty body or a small JSON object. Its members + // are not read: the status code is the answer. + let body = match read_bounded(response, MAXIMUM_PROBE_BYTES).await { + Ok(body) => body, Err( BoundedReadError::ContentLengthExceeded { .. } | BoundedReadError::BodyTooLarge { .. }, @@ -308,6 +310,18 @@ impl DocumentsClient { kind: read_failure_kind(&error), }) } + }; + if !body.is_empty() + && !matches!( + serde_json::from_slice::(&body), + Ok(serde_json::Value::Object(_)) + ) + { + return Err(protocol( + status, + DocumentsProtocolFailure::Body, + Some(trace_id), + )); } Ok(DocumentsComplete { value: (), diff --git a/crates/registry-documents-client/tests/http_boundary.rs b/crates/registry-documents-client/tests/http_boundary.rs index bb3922a7c2..12810930cf 100644 --- a/crates/registry-documents-client/tests/http_boundary.rs +++ b/crates/registry-documents-client/tests/http_boundary.rs @@ -183,3 +183,64 @@ async fn a_healthy_answer_with_a_body_is_a_protocol_failure() { ); server.abort(); } + +fn json_probe(body: String) -> Response { + ( + StatusCode::OK, + [ + (CONTENT_TYPE, "application/json"), + ( + axum::http::header::HeaderName::from_static("traceparent"), + TRACEPARENT, + ), + ], + body, + ) + .into_response() +} + +#[tokio::test] +async fn a_healthy_answer_with_a_json_object_body_is_accepted() { + let (client, server) = client_for(|| { + json_probe(r#"{"status":"ready","posture":"production","developmentSettings":[]}"#.into()) + }) + .await; + let complete = client.health().await.expect("a JSON object probe body"); + assert_eq!(complete.trace_id, TRACE_ID); + server.abort(); +} + +#[tokio::test] +async fn a_healthy_answer_with_a_json_body_that_is_not_an_object_is_a_protocol_failure() { + let (client, server) = client_for(|| json_probe("[1]".into())).await; + let error = client.health().await.unwrap_err(); + assert!( + matches!( + error, + DocumentsClientError::Protocol { + failure: DocumentsProtocolFailure::Body, + .. + } + ), + "{error:?}" + ); + server.abort(); +} + +#[tokio::test] +async fn a_healthy_answer_with_an_oversized_json_body_is_a_protocol_failure() { + let (client, server) = + client_for(|| json_probe(format!(r#"{{"note":"{}"}}"#, "a".repeat(8 * 1024)))).await; + let error = client.health().await.unwrap_err(); + assert!( + matches!( + error, + DocumentsClientError::Protocol { + failure: DocumentsProtocolFailure::Body, + .. + } + ), + "{error:?}" + ); + server.abort(); +} diff --git a/crates/registry-messaging-client/src/client.rs b/crates/registry-messaging-client/src/client.rs index 3bf08b7110..61fe339e79 100644 --- a/crates/registry-messaging-client/src/client.rs +++ b/crates/registry-messaging-client/src/client.rs @@ -26,6 +26,8 @@ use crate::{MessagingClientConfig, MessagingClientError, MessagingProtocolFailur const JSON_MEDIA_TYPE: &str = "application/json"; const PROBLEM_MEDIA_TYPE: &str = "application/problem+json"; const MAXIMUM_PROBLEM_BYTES: u64 = 8 * 1024; +/// Longest `/health` or `/ready` body this client reads. +const MAXIMUM_PROBE_BYTES: u64 = 4096; /// Longest `Retry-After` wait, in whole seconds, this client reports on a /// 429 refusal. A daily limit clears as the profile's oldest counted @@ -82,14 +84,14 @@ impl MessagingClient { /// Whether the process answers at all. Liveness says nothing about the /// store; use `ready` for that. pub async fn health(&self) -> Result, MessagingClientError> { - self.get_empty(HEALTH_PATH).await + self.get_probe(HEALTH_PATH).await } /// Whether the runtime can serve: its store is reachable and carries /// exactly the schema this runtime expects. A runtime that is not ready /// answers the typed `ProblemCode::ServiceUnavailable`. pub async fn ready(&self) -> Result, MessagingClientError> { - self.get_empty(READY_PATH).await + self.get_probe(READY_PATH).await } /// Submit one message under `idempotency_key`. The runtime answers the @@ -265,7 +267,9 @@ impl MessagingClient { .map_err(|_| MessagingClientError::configuration("the service base URL is not usable")) } - async fn get_empty(&self, path: &str) -> Result, MessagingClientError> { + /// A probe answers 200 with an empty body or a JSON object; its + /// members are not read, the status code is the answer. + async fn get_probe(&self, path: &str) -> Result, MessagingClientError> { let url = self.url_from_constant(path)?; let response = self.send(self.http.get(url)).await?; let status = response.status(); @@ -273,18 +277,30 @@ impl MessagingClient { return Err(self.problem_or_status(response).await); } let trace_id = response_trace(status, response.headers())?; - let body = - read_bounded(response, 1) - .await - .map_err(|error| MessagingClientError::Transport { - kind: read_failure_kind(&error), - })?; + let json_media_type = exact_media_type(response.headers(), JSON_MEDIA_TYPE); + let body = read_bounded(response, MAXIMUM_PROBE_BYTES) + .await + .map_err(|error| MessagingClientError::Transport { + kind: read_failure_kind(&error), + })?; if !body.is_empty() { - return Err(protocol( - status, - MessagingProtocolFailure::Body, - Some(trace_id), - )); + if !json_media_type { + return Err(protocol( + status, + MessagingProtocolFailure::MediaType, + Some(trace_id), + )); + } + if !matches!( + serde_json::from_slice::(&body), + Ok(serde_json::Value::Object(_)) + ) { + return Err(protocol( + status, + MessagingProtocolFailure::Body, + Some(trace_id), + )); + } } Ok(MessagingComplete { value: (), diff --git a/crates/registry-messaging-client/tests/http_boundary.rs b/crates/registry-messaging-client/tests/http_boundary.rs index 78237b2408..42687123f6 100644 --- a/crates/registry-messaging-client/tests/http_boundary.rs +++ b/crates/registry-messaging-client/tests/http_boundary.rs @@ -613,13 +613,83 @@ async fn a_failure_that_is_not_a_problem_document_is_a_protocol_failure() { } #[tokio::test] -async fn a_success_with_a_body_is_a_protocol_failure() { +async fn a_success_with_a_body_that_is_not_json_is_a_protocol_failure() { let (client, server) = serve("", &Fixture::new(StatusCode::OK, None, "x")).await; assert!(matches!( client.health().await, Err(MessagingClientError::Protocol { status: 200, - failure: MessagingProtocolFailure::Body, + failure: MessagingProtocolFailure::MediaType, + .. + }) + )); + server.abort(); +} + +#[tokio::test] +async fn health_and_ready_accept_the_json_status_body() { + let health = Fixture::new( + StatusCode::OK, + Some("application/json"), + r#"{"status":"ok"}"#, + ); + let (client, server) = serve("", &health).await; + assert_eq!(client.health().await.expect("health").trace_id, TRACE_ID); + server.abort(); + + let ready = Fixture::new( + StatusCode::OK, + Some("application/json"), + r#"{"status":"ready","extra":[1,2]}"#, + ); + let (client, server) = serve("", &ready).await; + assert_eq!(client.ready().await.expect("ready").trace_id, TRACE_ID); + server.abort(); +} + +#[tokio::test] +async fn a_probe_body_over_the_bound_is_refused_as_too_large() { + let body = format!(r#"{{"status":"ok","padding":"{}"}}"#, "x".repeat(8 * 1024)); + let fixture = Fixture::new(StatusCode::OK, Some("application/json"), &body); + let (client, server) = serve("", &fixture).await; + assert!(matches!( + client.health().await, + Err(MessagingClientError::Transport { + kind: TransportKind::ResponseTooLarge, + }) + )); + server.abort(); +} + +#[tokio::test] +async fn a_probe_body_that_is_not_a_json_object_is_a_protocol_failure() { + for body in ["[]", "\"ok\"", "{"] { + let fixture = Fixture::new(StatusCode::OK, Some("application/json"), body); + let (client, server) = serve("", &fixture).await; + assert!( + matches!( + client.ready().await, + Err(MessagingClientError::Protocol { + status: 200, + failure: MessagingProtocolFailure::Body, + .. + }) + ), + "body {body}" + ); + server.abort(); + } +} + +#[tokio::test] +async fn a_probe_body_under_another_media_type_is_a_protocol_failure() { + let fixture = Fixture::new(StatusCode::OK, Some("text/plain"), r#"{"status":"ok"}"#); + let (client, server) = serve("", &fixture).await; + assert!(matches!( + client.health().await, + Err(MessagingClientError::Protocol { + status: 200, + failure: MessagingProtocolFailure::MediaType, .. }) )); diff --git a/crates/registry-messaging-core/src/access.rs b/crates/registry-messaging-core/src/access.rs index 1639ce5c7b..ac3c4616a5 100644 --- a/crates/registry-messaging-core/src/access.rs +++ b/crates/registry-messaging-core/src/access.rs @@ -370,6 +370,19 @@ impl AccessProfiles { self.profiles.values() } + /// The clients the profiles name, sorted and distinct. The runtime and + /// adopter tooling both derive the admitted clients from this one set. + #[must_use] + pub fn requester_clients(&self) -> Vec { + let mut clients: Vec = self + .iter() + .flat_map(|profile| profile.requester_clients.iter().cloned()) + .collect(); + clients.sort(); + clients.dedup(); + clients + } + #[must_use] pub fn is_empty(&self) -> bool { self.profiles.is_empty() diff --git a/crates/registry-messaging/src/config.rs b/crates/registry-messaging/src/config.rs index 5bdf8c7ac3..4347591b96 100644 --- a/crates/registry-messaging/src/config.rs +++ b/crates/registry-messaging/src/config.rs @@ -2,34 +2,35 @@ //! The operator runtime configuration document and the package it names. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::time::Duration; use registry_messaging_core::{ - typed, ProviderKind, MESSAGING_RUNTIME_API_VERSION, MESSAGING_RUNTIME_KIND, PACKAGE_FILE, - RETIRED_MESSAGING_RUNTIME_API_VERSION, + typed, AccessProfiles, ProviderKind, MESSAGING_RUNTIME_API_VERSION, MESSAGING_RUNTIME_KIND, + PACKAGE_FILE, RETIRED_MESSAGING_RUNTIME_API_VERSION, }; use registry_platform_audit::{ AuditDestination, AuditDestinationError, AuditDestinationKind, MAX_AUDIT_RETAIN_DAYS, MIN_AUDIT_ROTATE_BYTES, }; -use registry_platform_config::{ - AuditKeyConfig, ConfigBlockError, ConfigBlockErrorKind, MetricsBindError, RemovedKey, - RuntimeConfigLoader, RuntimeEnvelope, RuntimeFileCheck, SecretReference, SecretResolver, - DEFAULT_STAND_IN, REMOVED_OIDC_JWKS_SOURCE_KIND, REMOVED_OIDC_JWKS_URI, -}; pub use registry_platform_config::{ - DatabaseConfig, EnvironmentSecretProviderConfig, FileSecretProviderConfig, - JwksSource as OidcJwksSource, ListenerNetworkExposure, MetricsListenerConfig, - OidcClientsConfig, OidcIssuerConfig, PackageConfig as RuntimePackageConfig, - PrivateListenerConfig as ListenerConfig, SecretProvidersConfig, TlsTermination, + AdmittedClients, DatabaseConfig, EnvironmentSecretProviderConfig, FileSecretProviderConfig, + JwksSource as OidcJwksSource, ListenerNetworkExposure, MetricsListenerConfig, OidcIssuerConfig, + OidcPackageClientsConfig, PackageClients, PackageClientsError, + PackageConfig as RuntimePackageConfig, PrivateListenerConfig as ListenerConfig, + SecretProvidersConfig, TlsTermination, MAX_ASSERTION_ISSUERS_PER_CLIENT as MAXIMUM_ASSERTION_ISSUERS_PER_CLIENT, MAX_ASSERTION_ISSUER_BYTES as MAXIMUM_ASSERTION_ISSUER_BYTES, MAX_ASSERTION_ISSUER_CLIENTS as MAXIMUM_ASSERTION_ISSUER_CLIENTS, MAX_ASSERTION_ISSUER_CLIENT_BYTES as MAXIMUM_ASSERTION_ISSUER_CLIENT_BYTES, UNAVAILABLE_CODE as RUNTIME_CONFIG_UNAVAILABLE_CODE, }; +use registry_platform_config::{ + AuditKeyConfig, ConfigBlockError, ConfigBlockErrorKind, MetricsBindError, RemovedKey, + RuntimeConfigLoader, RuntimeEnvelope, RuntimeFileCheck, SecretReference, SecretResolver, + DEFAULT_STAND_IN, REMOVED_OIDC_JWKS_SOURCE_KIND, REMOVED_OIDC_JWKS_URI, +}; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, @@ -295,12 +296,13 @@ pub struct OidcConfig { #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-issuer"))] #[cfg_attr(feature = "schema", schemars(flatten))] pub provider: OidcIssuerConfig, - /// The OAuth clients this runtime admits. Every access profile resolves - /// its caller from the matched client, so the list is never empty, and - /// every client a profile names must appear here. - #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-clients"))] + /// The OAuth clients this runtime admits: `from-package` for the + /// requester clients of the package's access profiles, or a list that + /// covers every client a profile names. Every access profile resolves its + /// caller from the matched client, so the admitted set is never empty. + #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-package-clients"))] #[cfg_attr(feature = "schema", schemars(flatten))] - pub clients: OidcClientsConfig, + pub clients: OidcPackageClientsConfig, #[serde(default = "default_scope_claim")] pub scope_claim: String, } @@ -690,19 +692,34 @@ impl RuntimeConfig { // so `allowedClients: unrestricted` would admit every client the // issuer verifies while reaching no profile. Development keeps no // exception. - if oidc.clients.allowed_clients.is_empty() - || oidc.clients.allowed_clients.iter().any(String::is_empty) - { - findings.push(RuntimeConfigError::AllowedClientsRequired); + match &oidc.clients.allowed_clients { + PackageClients::Unrestricted => { + findings.push(RuntimeConfigError::AllowedClientsRequired) + } + PackageClients::Listed(clients) => { + if clients.iter().any(String::is_empty) { + findings.push(RuntimeConfigError::AllowedClientsRequired); + } + self.check_assertion_issuer_clients(clients, findings); + } + PackageClients::FromPackage => {} } - for (client, issuers) in &oidc.clients.assertion_issuers { + } + + /// Every client `assertionIssuers` names must be one the runtime admits. + fn check_assertion_issuer_clients( + &self, + admitted: &[String], + findings: &mut Vec, + ) { + for (client, issuers) in &self.authentication.oidc.clients.assertion_issuers { let pointer = pointer_to(&["authentication", "oidc", "assertionIssuers", client]); if issuers.is_empty() { findings.push(RuntimeConfigError::EmptyAssertionIssuers { pointer: pointer.clone(), }); } - if !oidc.clients.allowed_clients.contains(client) { + if !admitted.contains(client) { findings.push(RuntimeConfigError::AssertionIssuerClientNotAllowed { pointer }); } } @@ -768,27 +785,62 @@ impl RuntimeConfig { loaded: &LoadedPackage, findings: &mut Vec, ) { - let allowed: BTreeSet<&str> = self - .authentication - .oidc - .clients - .allowed_clients - .iter() - .map(String::as_str) - .collect(); - for profile in loaded.package.access_profiles().iter() { - if profile - .requester_clients - .iter() - .any(|client| !allowed.contains(client.as_str())) - { - findings.push(RuntimeConfigError::ProfileClientNotAllowed { - profile: profile.id.clone(), - }); + match self.admitted_clients(loaded.package.access_profiles()) { + Ok(admitted) => { + if self.authentication.oidc.clients.allowed_clients == PackageClients::FromPackage { + self.check_assertion_issuer_clients(admitted.as_slice(), findings); + } } + // Each profile the list leaves out is its own finding. + Err(RuntimeConfigError::ProfileClientNotAllowed { .. }) => { + if let PackageClients::Listed(listed) = + &self.authentication.oidc.clients.allowed_clients + { + for profile in loaded.package.access_profiles().iter() { + if profile + .requester_clients + .iter() + .any(|client| !listed.contains(client)) + { + findings.push(RuntimeConfigError::ProfileClientNotAllowed { + profile: profile.id.clone(), + }); + } + } + } + } + Err(error) => findings.push(error), } } + /// The clients the token verifier admits, given the access profiles of + /// the package this runtime serves. `from-package` is the sorted union of + /// the profiles' requester clients, and a list must cover every one of + /// them, or the profile naming the missing client could never be reached. + /// The verifier is never handed an empty list, which it reads as "every + /// client". + pub fn admitted_clients( + &self, + profiles: &AccessProfiles, + ) -> Result { + let allowed = &self.authentication.oidc.clients.allowed_clients; + allowed + .resolve(&profiles.requester_clients()) + .map_err(|error| match error { + PackageClientsError::Unrestricted | PackageClientsError::Empty => { + RuntimeConfigError::AllowedClientsRequired + } + PackageClientsError::Missing(client) => { + RuntimeConfigError::ProfileClientNotAllowed { + profile: profiles + .iter() + .find(|profile| profile.requester_clients.contains(&client)) + .map_or_else(String::new, |profile| profile.id.clone()), + } + } + }) + } + /// Each connection must be for a provider the package declares, of the /// declared type, and an `http` connection must satisfy the package half /// it completes. @@ -912,7 +964,7 @@ impl RuntimeConfig { /// [`access_token_typ_set`] admits exactly that pair, so an ID token or any /// other JWT minted for this audience is refused. #[must_use] - pub fn verifier_profile(&self) -> TokenVerifierConfig { + pub fn verifier_profile(&self, admitted: &AdmittedClients) -> TokenVerifierConfig { TokenVerifierConfig::access_token_profile( self.authentication.oidc.provider.issuer.to_string(), vec![self.authentication.oidc.provider.audience.clone()], @@ -923,7 +975,7 @@ impl RuntimeConfig { access_token_typ_set(MESSAGING_ACCESS_TOKEN_TYPE), ) .with_scope_claim(self.authentication.oidc.scope_claim.clone()) - .with_allowed_clients(self.authentication.oidc.clients.allowed_clients.clone()) + .with_allowed_clients(admitted.as_slice().to_vec()) .with_assertion_issuers(self.authentication.oidc.clients.assertion_issuers.clone()) } @@ -1729,6 +1781,7 @@ pub(crate) mod tests { use super::*; use registry_platform_yaml::{Severity, MAXIMUM_DIAGNOSTICS_PER_FILE}; use serde_json::{json, Value}; + use std::collections::BTreeSet; /// The starter package's manifest, as a value a test may change. pub(crate) fn package_value() -> Value { @@ -2524,6 +2577,143 @@ pub(crate) mod tests { ); } + fn profile_naming(id: &str, clients: &[&str]) -> registry_messaging_core::AccessProfile { + registry_messaging_core::AccessProfile { + id: id.to_owned(), + label: None, + description: None, + principal_claim: "sub".to_owned(), + required_scopes: vec!["messaging:send".to_owned()], + requester_clients: clients.iter().map(|client| (*client).to_owned()).collect(), + actor_kind: None, + acts_as: registry_messaging_core::ActsAs::Operator, + sender_profiles: Vec::new(), + templates: Vec::new(), + allow_direct_content: false, + requests_per_minute: 60, + burst: 10, + maximum_messages_per_day: None, + } + } + + fn from_package() -> Value { + let mut value = base(); + value["authentication"]["oidc"]["allowedClients"] = json!("from-package"); + value + } + + #[tokio::test] + async fn from_package_admits_exactly_the_package_clients() { + use crate::auth::tests::{keys, token}; + use registry_platform_oidc::TokenVerifier; + + let config = load(from_package()).expect("from-package loads against the starter package"); + let profiles = registry_messaging_core::AccessProfiles::new(vec![ + profile_naming("first", &["c1", "c2"]), + profile_naming("second", &["c3"]), + ]) + .unwrap(); + let admitted = config.admitted_clients(&profiles).unwrap(); + assert_eq!(admitted.as_slice(), ["c1", "c2", "c3"]); + let mut profile = config.verifier_profile(&admitted); + assert_eq!(profile.allowed_clients, ["c1", "c2", "c3"]); + profile.allowed_algorithms = vec![jsonwebtoken::Algorithm::HS256]; + let verifier = TokenVerifier::new(profile, keys()); + let signed = |client: &str| { + token(json!({ + "iss": "https://identity.example.test", + "aud": "urn:example:messaging", + "sub": "principal", + "azp": client, + "scope": "messaging:send", + })) + }; + for client in ["c1", "c2", "c3"] { + verifier + .verify(&signed(client)) + .await + .unwrap_or_else(|error| panic!("{client} is admitted: {error}")); + } + let refused = verifier.verify(&signed("c4")).await; + assert!( + matches!( + refused, + Err(registry_platform_oidc::OidcError::ClientNotAllowed) + ), + "{refused:?}" + ); + } + + #[test] + fn from_package_never_reaches_the_verifier_as_an_empty_list() { + let config = load(from_package()).unwrap(); + let none = registry_messaging_core::AccessProfiles::default(); + let error = config.admitted_clients(&none).unwrap_err(); + assert!( + matches!(error, RuntimeConfigError::AllowedClientsRequired), + "{error}" + ); + } + + #[test] + fn an_explicit_list_missing_a_package_client_is_refused_with_the_profile() { + let mut value = base(); + value["authentication"]["oidc"]["allowedClients"] = json!(["case-system"]); + let config = RuntimeConfig::parse_with_environment( + &serde_json::to_string(&value).unwrap(), + &no_environment, + ) + .unwrap(); + let profiles = registry_messaging_core::AccessProfiles::new(vec![ + profile_naming("covered", &["case-system"]), + profile_naming("left-out", &["operations-console"]), + ]) + .unwrap(); + let error = config.admitted_clients(&profiles).unwrap_err(); + assert!( + matches!(&error, RuntimeConfigError::ProfileClientNotAllowed { profile } if profile == "left-out"), + "{error}" + ); + } + + #[test] + fn assertion_issuer_client_outside_the_package_is_refused_under_from_package() { + let mut value = from_package(); + value["authentication"]["oidc"]["assertionIssuers"] = + json!({"unknown-client": ["https://assertions.example.test"]}); + let error = load(value).unwrap_err(); + assert!( + matches!( + error, + RuntimeConfigError::AssertionIssuerClientNotAllowed { .. } + ), + "{error}" + ); + assert_eq!( + error.pointer(), + "/authentication/oidc/assertionIssuers/unknown-client" + ); + let mut value = from_package(); + value["authentication"]["oidc"]["assertionIssuers"] = + json!({"case-system": ["https://assertions.example.test"]}); + assert!(load(value).unwrap().binds_assertion_issuers()); + } + + #[test] + fn the_keywords_other_than_from_package_and_unrestricted_are_refused() { + let mut value = base(); + value["authentication"]["oidc"]["allowedClients"] = json!("any"); + let error = load(value).unwrap_err(); + assert_eq!(error.code(), "config.invalid-value", "{error}"); + assert_eq!(error.pointer(), "/authentication/oidc/allowedClients"); + let mut value = base(); + value["authentication"]["oidc"]["allowedClients"] = json!("unrestricted"); + assert!(matches!( + load(value).unwrap_err(), + RuntimeConfigError::AllowedClientsRequired + )); + } + #[test] fn a_repeated_allowed_client_is_refused_at_the_repetition() { let mut value = base(); @@ -3010,7 +3200,8 @@ pub(crate) mod tests { #[test] fn the_verifier_admits_only_the_access_token_media_type() { let config = load(base()).unwrap(); - let profile = config.verifier_profile(); + let admitted = AdmittedClients::new(vec!["case-system".to_owned()]).unwrap(); + let profile = config.verifier_profile(&admitted); assert!(registry_platform_oidc::is_access_token_typ_pair( &profile.allowed_typ )); diff --git a/crates/registry-messaging/src/runtime.rs b/crates/registry-messaging/src/runtime.rs index 9658b4249a..a51af188c2 100644 --- a/crates/registry-messaging/src/runtime.rs +++ b/crates/registry-messaging/src/runtime.rs @@ -396,8 +396,9 @@ pub async fn assemble( )?); let keys = config.jwks_fetcher(&secrets).await?; + let admitted = config.admitted_clients(loaded.package.access_profiles())?; let authenticator = Arc::new(MessagingAuthenticator::new( - config.verifier_profile(), + config.verifier_profile(&admitted), keys, loaded.package.access_profiles().clone(), config.binds_assertion_issuers(), diff --git a/crates/registry-messaging/src/schema.rs b/crates/registry-messaging/src/schema.rs index a0fb8ff5aa..07848df08f 100644 --- a/crates/registry-messaging/src/schema.rs +++ b/crates/registry-messaging/src/schema.rs @@ -681,21 +681,32 @@ fn install_runtime_constraints(schema: &mut Value) { set_definition_property(schema, definition, property, "pattern", json!("^/")); } // Every access profile resolves its caller from the matched client, so - // a Messaging deployment always lists the clients it admits. The shared + // a Messaging deployment always states the clients it admits. The shared // block requires the member and also admits the keyword `unrestricted`, // which this runtime refuses in every mode, so the member is restated - // as the list alone and the shared definition is dropped. + // as `from-package` or the list, and the shared definition is dropped. if let Some(clients) = schema.pointer_mut("/$defs/OidcConfig/properties/allowedClients") { *clients = json!({ - "description": "Client identifiers whose access tokens are admitted. Required in every\nfile; an omitted or empty list, an empty or repeated client, and\n`unrestricted` are refused.", - "type": "array", - "items": {"type": "string", "minLength": 1}, - "minItems": 1, - "uniqueItems": true, + "description": "The clients whose access tokens are admitted. Required in every\nfile: `from-package` admits the requester clients of the package's access\nprofiles, and a list of at least one distinct client must cover them. An\nomitted or empty list, an empty or repeated client, and `unrestricted` are\nrefused.", + "oneOf": [ + {"type": "string", "const": "from-package"}, + { + "type": "array", + "items": {"type": "string", "minLength": 1}, + "minItems": 1, + "uniqueItems": true, + }, + ], }); } + if let Some(issuers) = + schema.pointer_mut("/$defs/OidcConfig/properties/assertionIssuers/description") + { + *issuers = json!("Assertion authorities each client may exchange a subject token from,\nkeyed by client identifier. Omitted, no assertion-issuer rule applies;\nwritten, it lists at least one client, each with at least one\nauthority. Once a client is listed, a token it exchanged is accepted\nonly for one of that client's declared authorities, and a client that\nis not listed may exchange from no authority."); + } if let Some(definitions) = schema.pointer_mut("/$defs").and_then(Value::as_object_mut) { definitions.remove("OidcAllowedClients"); + definitions.remove("OidcPackageAllowedClients"); } if let Some(profiles) = schema .pointer_mut("/properties/tlsTrustProfiles") @@ -810,8 +821,9 @@ mod tests { document["$defs"]["RetentionConfig"]["properties"]["payloadRetentionDays"]["maximum"], MAXIMUM_PAYLOAD_RETENTION_DAYS ); - // `allowedClients` is decided in every file, and only as a list: - // the runtime refuses `unrestricted` in every mode. + // `allowedClients` is decided in every file: the keyword + // `from-package` or a non-empty list. The runtime refuses + // `unrestricted` in every mode, so the schema does not offer it. let oidc = &document["$defs"]["OidcConfig"]; assert_eq!( oidc["required"] @@ -825,11 +837,15 @@ mod tests { let clients = &oidc["properties"]["allowedClients"]; assert!(clients.get("default").is_none()); assert!(clients.get("$ref").is_none(), "{clients}"); - assert_eq!(clients["type"], "array"); - assert_eq!(clients["minItems"], 1); - assert_eq!(clients["uniqueItems"], true); - assert_eq!(clients["items"]["minLength"], 1); + let forms = clients["oneOf"].as_array().expect("two written forms"); + assert_eq!(forms.len(), 2, "{clients}"); + assert_eq!(forms[0], json!({"type": "string", "const": "from-package"})); + assert_eq!(forms[1]["type"], "array"); + assert_eq!(forms[1]["minItems"], 1); + assert_eq!(forms[1]["uniqueItems"], true); + assert_eq!(forms[1]["items"]["minLength"], 1); assert!(document["$defs"].get("OidcAllowedClients").is_none()); + assert!(document["$defs"].get("OidcPackageAllowedClients").is_none()); assert_eq!( document["$defs"]["OidcConfig"]["additionalProperties"], false, "unknown keys are refused" diff --git a/crates/registry-messaging/tests/postgres_messages.rs b/crates/registry-messaging/tests/postgres_messages.rs index 25b27d0efa..b8941c5f49 100644 --- a/crates/registry-messaging/tests/postgres_messages.rs +++ b/crates/registry-messaging/tests/postgres_messages.rs @@ -46,6 +46,33 @@ fn assert_problem(answer: &(StatusCode, Value), status: StatusCode, code: &str) assert_eq!(answer.1["code"], code, "{}", answer.1); } +/// The runtime file of the harness says `allowedClients: from-package` and +/// lists no client. The package's two requester clients both reach their +/// profile, and a client the package does not name is refused. +#[tokio::test] +async fn a_runtime_that_admits_the_package_clients_serves_a_call_from_each() { + let harness = Harness::start().await; + let text = std::fs::read_to_string(harness.runtime_path()).unwrap(); + assert!(text.contains("allowedClients: from-package"), "{text}"); + + let accepted = harness + .submit(&sender_token(), "from-package-key", &email_submission()) + .await; + assert_eq!(accepted.0, StatusCode::ACCEPTED, "{}", accepted.1); + let uri = format!("/v1/messages/{}", accepted.1["id"].as_str().unwrap()); + let (status, view) = harness.call("GET", &uri, Some(&operator_token())).await; + assert_eq!(status, StatusCode::OK, "{view}"); + + let stranger = token(json!({ + "sub": "unlisted-principal", + "azp": "reporting-job", + "registry_scopes": "messaging:send", + "registry_actor_kind": "service", + })); + let refused = harness.call("GET", &uri, Some(&stranger)).await; + assert_eq!(refused.0, StatusCode::UNAUTHORIZED, "{}", refused.1); +} + #[tokio::test] async fn operator_reads_and_action_previews_ignore_a_refused_audit_destination() { let harness = Harness::start().await; diff --git a/crates/registry-messaging/tests/support/mod.rs b/crates/registry-messaging/tests/support/mod.rs index 464d13f2ba..24a2309a7f 100644 --- a/crates/registry-messaging/tests/support/mod.rs +++ b/crates/registry-messaging/tests/support/mod.rs @@ -23,7 +23,7 @@ use jsonwebtoken::{Algorithm, EncodingKey, Header}; use registry_messaging::activation::ApplyRequest; use registry_messaging::audit::MessagingAudit; use registry_messaging::auth::MessagingAuthenticator; -use registry_messaging::config::RuntimeConfig; +use registry_messaging::config::{AdmittedClients, RuntimeConfig}; use registry_messaging::dispatch::{dispatcher, Transports}; use registry_messaging::http::{metrics_router, router, HttpState, Readiness}; use registry_messaging::limits::{ @@ -329,8 +329,11 @@ impl Harness { loaded.receipt_providers(), )); let metrics = Arc::new(Metrics::default()); + let admitted = config + .admitted_clients(package.access_profiles()) + .expect("the clients the runtime file admits"); let authenticator = Arc::new(MessagingAuthenticator::new( - verifier(), + verifier(&admitted), keys(), package.access_profiles().clone(), false, @@ -370,6 +373,13 @@ impl Harness { self.root.path().join("runtime.yaml") } + /// The clients the runtime file admits, derived from the package. + fn admitted(&self) -> AdmittedClients { + self.config + .admitted_clients(self.package.access_profiles()) + .expect("the clients the runtime file admits") + } + pub async fn publish(&self) {} /// Every record the journal holds, across its segments, oldest first @@ -497,7 +507,7 @@ impl Harness { )); router(HttpState { authenticator: Arc::new(MessagingAuthenticator::new( - verifier(), + verifier(&self.admitted()), keys(), profiles, false, @@ -539,7 +549,7 @@ impl Harness { )); router(HttpState { authenticator: Arc::new(MessagingAuthenticator::new( - verifier(), + verifier(&self.admitted()), keys(), self.package.access_profiles().clone(), false, @@ -693,7 +703,7 @@ fn write_runtime(root: &Path, package: &Path, database: &str, providers: Value) "issuer": ISSUER, "audience": AUDIENCE, "jwksSource": {"type": "static", "documentRef": format!("secret:env/{jwks_name}")}, - "allowedClients": ["case-system", "operations-console"] + "allowedClients": "from-package" }}, "audit": { "path": root.join("audit").join("messaging.jsonl"), @@ -711,7 +721,7 @@ fn write_runtime(root: &Path, package: &Path, database: &str, providers: Value) /// The runtime's verifier profile, with the symmetric test algorithm in /// place of the production asymmetric pair. -fn verifier() -> TokenVerifierConfig { +fn verifier(admitted: &AdmittedClients) -> TokenVerifierConfig { TokenVerifierConfig::access_token_profile( ISSUER, vec![AUDIENCE.to_owned()], @@ -719,10 +729,7 @@ fn verifier() -> TokenVerifierConfig { registry_platform_oidc::access_token_typ_set("at+jwt"), ) .with_scope_claim("registry_scopes") - .with_allowed_clients(vec![ - "case-system".to_owned(), - "operations-console".to_owned(), - ]) + .with_allowed_clients(admitted.as_slice().to_vec()) } fn keys() -> Arc { diff --git a/crates/registry-messaging/tests/token_characterisation.rs b/crates/registry-messaging/tests/token_characterisation.rs index 275997689c..d0de187b95 100644 --- a/crates/registry-messaging/tests/token_characterisation.rs +++ b/crates/registry-messaging/tests/token_characterisation.rs @@ -161,10 +161,14 @@ async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { .await .expect("the static key source"); + let profiles = profiles(&case, &scope); + let admitted = config + .admitted_clients(&profiles) + .expect("the listed clients cover the profile"); let authenticator = MessagingAuthenticator::new( - config.verifier_profile(), + config.verifier_profile(&admitted), Arc::clone(&keys), - profiles(&case, &scope), + profiles, config.binds_assertion_issuers(), ); let token = case.token.expose(); @@ -178,7 +182,7 @@ async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { Err(AuthenticationError::Claims) => refusal("claims"), Err(AuthenticationError::Unavailable) => refusal("unavailable"), Err(error @ (AuthenticationError::Refused | AuthenticationError::Profile)) => { - let reference = TokenVerifier::new(config.verifier_profile(), keys); + let reference = TokenVerifier::new(config.verifier_profile(&admitted), keys); match reference.verify(token).await { Err(failure) => refusal(failure.authentication_stage().label()), Ok(verified) if error == AuthenticationError::Profile => { diff --git a/crates/registry-messagingctl/src/dev/borrowed.rs b/crates/registry-messagingctl/src/dev/borrowed.rs index ec3287f8bb..d07f577c13 100644 --- a/crates/registry-messagingctl/src/dev/borrowed.rs +++ b/crates/registry-messagingctl/src/dev/borrowed.rs @@ -391,9 +391,7 @@ pub(super) async fn verify( access_token_typ_set("at+jwt"), ) .with_scope_claim("scope") - .with_allowed_clients(crate::identity_facts::requester_clients( - loaded.package.access_profiles(), - )); + .with_allowed_clients(loaded.package.access_profiles().requester_clients()); let verified = TokenVerifier::new(verifier.clone(), keys.clone()) .verify(signed) .await diff --git a/crates/registry-messagingctl/src/dev/config.rs b/crates/registry-messagingctl/src/dev/config.rs index 59f2f83381..f3af4b62c9 100644 --- a/crates/registry-messagingctl/src/dev/config.rs +++ b/crates/registry-messagingctl/src/dev/config.rs @@ -242,8 +242,6 @@ fn runtime_members( loaded: &LoadedPackage, endpoints: &Endpoints, ) -> Value { - let allowed_clients = - crate::identity_facts::requester_clients(loaded.package.access_profiles()); let providers: serde_json::Map = loaded .package .providers() @@ -309,7 +307,7 @@ fn runtime_members( "authentication": {"oidc": { "issuer": ISSUER, "audience": AUDIENCE, - "allowedClients": allowed_clients, + "allowedClients": "from-package", // The session's signing key is generated beside this file, so // the runtime reads its key set directly. "jwksSource": {"type": "static", "documentRef": "secret:file/jwks.json"}, diff --git a/crates/registry-messagingctl/src/identity_facts.rs b/crates/registry-messagingctl/src/identity_facts.rs index 5f556348c9..74a62c247a 100644 --- a/crates/registry-messagingctl/src/identity_facts.rs +++ b/crates/registry-messagingctl/src/identity_facts.rs @@ -15,7 +15,7 @@ use std::path::Path; use registry_messaging::config::RuntimeConfig; use registry_messaging::package::LoadedPackage; -use registry_messaging_core::{AccessProfiles, ActorKind}; +use registry_messaging_core::ActorKind; use registry_thunderid_tooling::identity_facts::{ self, AccessProfile as FactsProfile, ActorKind as FactsActorKind, Admission, ClaimType, IdentityFacts, @@ -31,17 +31,6 @@ const DEFAULT_SCOPE_CLAIM: &str = "scope"; /// one of these grants no scope without a mapping Messaging does not offer. const RESERVED_SCOPE_CLAIMS: [&str; 4] = ["sub", "client_id", "azp", "aud"]; -/// The clients the package's access profiles name, sorted and distinct. -pub(crate) fn requester_clients(profiles: &AccessProfiles) -> Vec { - let mut clients: Vec = profiles - .iter() - .flat_map(|profile| profile.requester_clients.iter().cloned()) - .collect(); - clients.sort(); - clients.dedup(); - clients -} - #[derive(Debug)] pub(crate) enum FactsError { /// A profile cannot be stated as facts; the message names no value. @@ -71,12 +60,10 @@ pub(crate) fn facts( loaded: &LoadedPackage, ) -> Result { let oidc = &config.authentication.oidc; - let admitted = &oidc.clients.allowed_clients; - let allowed = if admitted.is_empty() { - Admission::Unrestricted - } else { - Admission::Clients(admitted.clone()) - }; + let admitted = config + .admitted_clients(loaded.package.access_profiles()) + .map_err(|error| FactsError::Unstatable(error.to_string()))?; + let allowed = Admission::Clients(admitted.into_vec()); let mut facts = IdentityFacts::new( PRODUCT, oidc.provider.issuer.as_str(), @@ -103,16 +90,6 @@ pub(crate) fn facts( profile.id ))); } - if let Some(client) = profile - .requester_clients - .iter() - .find(|client| !allowed.admits(client)) - { - return Err(FactsError::Unstatable(format!( - "the access profile `{}` names the client `{client}`, which authentication.oidc.allowedClients does not admit", - profile.id - ))); - } if profile.principal_claim != "sub" { facts .claims diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index 67518531f7..a6df8ab39b 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -105,7 +105,10 @@ Set `package.root` to the absolute path of the package directory. Optionally set Set `listener.bind` to the private address your proxy reaches, and `tlsTermination` to `operator-controlled-upstream`: the example's `development-loopback` is refused on any non-loopback bind, and a public unicast address is refused under every setting. Set `authentication.oidc` to your -issuer and audience; `allowedClients` must list every client an access profile names. +issuer and audience. Write `allowedClients: from-package` to admit exactly the clients the +package's access profiles name, so the clients are written once, in `messaging.yaml`. A list is also +accepted, and it must include every client an access profile names. Clients in the list that no +profile names are admitted by the verifier but reach no profile. Each provider the package declares gets a connection with the same id and `type`: diff --git a/docs/site/src/content/docs/security/messaging.mdx b/docs/site/src/content/docs/security/messaging.mdx index 37da7d72c5..6336782308 100644 --- a/docs/site/src/content/docs/security/messaging.mdx +++ b/docs/site/src/content/docs/security/messaging.mdx @@ -30,8 +30,11 @@ Every `/v1` route except the provider callback routes resolves its caller first. A credential is an RFC 9068 access token from the configured issuer and audience, from a client in `authentication.oidc.allowedClients`, signed by a published or static key. An exchanged token is refused unless `assertionIssuers` declares its authority. -`allowedClients: unrestricted` is refused in every mode, because an access profile resolves from -the matched client. +`allowedClients` is required in every runtime file. `allowedClients: from-package` admits the sorted +union of the access profiles' `requesterClients` and nothing more, so the package and the runtime +file cannot disagree. An explicit list must include every client an access profile names, or the +runtime refuses to start. `allowedClients: unrestricted` and an empty list are refused in every mode, +because an access profile resolves from the matched client. A refused or malformed credential, or one whose verified claims do not resolve to a client, is `401 authentication.refused` with a `WWW-Authenticate: Bearer` challenge. A credential that verifies but resolves to no usable access profile (including an exchanged token diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 362cc56951..96b0445c0b 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- The Rust BReg client decodes `/health` and `/ready` answers that carry + members besides `status`, and ignores them. `status` is still required and + checked. + - The Rust, Node and Python hook verifiers in the BReg clients refuse a delivery time more than 300 seconds from the receiver clock, either way, with the new code `stale-delivery`. A receiver that passed nothing gets that diff --git a/products/documents/CHANGELOG.md b/products/documents/CHANGELOG.md index f57c1909c2..c3171fe278 100644 --- a/products/documents/CHANGELOG.md +++ b/products/documents/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- The Rust Documents client accepts a `/health` answer with an empty body or a + JSON object body of at most 4096 bytes, and ignores the object's members. A + larger body, or a body that is not a JSON object, is still a body protocol + failure. + - Accept an optional `project.label` and `project.description` in the project block, as the shared project block does. They are display text for people and change no compiled output. diff --git a/products/messaging/CHANGELOG.md b/products/messaging/CHANGELOG.md index 219ddd62e9..47ba454259 100644 --- a/products/messaging/CHANGELOG.md +++ b/products/messaging/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +- `authentication.oidc.allowedClients` accepts the keyword `from-package`, + which admits the requester clients of the package's access profiles, so the + clients are written once, in the package. The member stays required, and an + omitted member, an empty list and `unrestricted` are still refused. A list + must still include every client a profile names. `rstack dev` writes + `from-package`. + +- `registry-messaging-client` accepts an empty body or a JSON object of at + most 4096 bytes from `/health` and `/ready`, and refuses a larger one. The + runtime still answers an empty `200`. + ## 0.47.0 - 2026-11-21 - BREAKING: `providers`, `senderProfiles`, and `accessProfiles` in diff --git a/products/messaging/generated/runtime/runtime.schema.json b/products/messaging/generated/runtime/runtime.schema.json index 98f004de37..3f0255e36b 100644 --- a/products/messaging/generated/runtime/runtime.schema.json +++ b/products/messaging/generated/runtime/runtime.schema.json @@ -521,14 +521,22 @@ "type": "boolean" }, "allowedClients": { - "description": "Client identifiers whose access tokens are admitted. Required in every\nfile; an omitted or empty list, an empty or repeated client, and\n`unrestricted` are refused.", - "items": { - "minLength": 1, - "type": "string" - }, - "minItems": 1, - "type": "array", - "uniqueItems": true + "description": "The clients whose access tokens are admitted. Required in every\nfile: `from-package` admits the requester clients of the package's access\nprofiles, and a list of at least one distinct client must cover them. An\nomitted or empty list, an empty or repeated client, and `unrestricted` are\nrefused.", + "oneOf": [ + { + "const": "from-package", + "type": "string" + }, + { + "items": { + "minLength": 1, + "type": "string" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + } + ] }, "assertionIssuers": { "additionalProperties": { diff --git a/products/platform/scripts/check-config-conformance.py b/products/platform/scripts/check-config-conformance.py index 2b731ea0ed..6c19214fe2 100755 --- a/products/platform/scripts/check-config-conformance.py +++ b/products/platform/scripts/check-config-conformance.py @@ -563,7 +563,7 @@ class Row: "crates/registry-messaging/src/config.rs", "OidcConfig", "clients", - "OidcClientsConfig", + "OidcPackageClientsConfig", ), RustBlock( "crates/registry-messaging/src/config.rs", From c7c01bd2c77bd1bba1d6d000db4b82def76eb0c0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 05:02:18 +0100 Subject: [PATCH 031/136] chore(ci): run each product's provisioning journey against the TLS PostgreSQL lane The journeys provision a database and split roles, apply as the owner and serve as the runtime role. They need a server they can verify, so they run in the contracts-journeys lane beside the provisioning suite, and a change to a product's provision command, journey or migrations selects that lane. The Messaging lane's broad messagingctl run skips the journey. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 26 ++++- .github/scripts/test_ci_changes.py | 151 +++++++++++++++++++++++++++++ .github/workflows/ci.yml | 46 ++++++++- 3 files changed, 221 insertions(+), 2 deletions(-) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index b0dbcefc7f..8308df282a 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -607,6 +607,25 @@ # spread across parallel `postgres:i/N` shard lanes — the runner's owned # target lists cover every test exactly once across the shard set. BREG_POSTGRES_SHARDS = 3 +# The packages whose provisioning journey runs against the contracts-journeys +# lane's TLS-only PostgreSQL service, and the inputs that select that lane. +PROVISION_JOURNEY_PACKAGES = ( + "registry-bregctl", + "registry-caseworkctl", + "registry-coordinator", + "registry-documentsctl", + "registry-messagingctl", + "registry-schedulingctl", +) +PROVISION_JOURNEY_INPUTS = ( + *(f"crates/{package}/src/provision.rs" for package in PROVISION_JOURNEY_PACKAGES), + *(f"crates/{package}/tests/provision*.rs" for package in PROVISION_JOURNEY_PACKAGES), + "crates/registry-casework/migrations/**", + "crates/registry-documents/migrations/**", + "crates/registry-messaging/migrations/**", + "crates/registry-scheduling/migrations/**", +) + BREG_CONTRACTS_LANES = ( "contracts", "contracts-journeys", @@ -1671,7 +1690,12 @@ def classify( # joins only the breg_contracts output: breg_integration and # casework_postgres read the selection above, so the provisioning crate # on its own does not select them. - provision_postgres = "registry-platform-provision" in affected + # Each product's provisioning journey runs in the same lane after the + # suite, so a product's provision command, its journey or its migrations + # select the lane too. + provision_postgres = "registry-platform-provision" in affected or any( + matches(path, *PROVISION_JOURNEY_INPUTS) for path in paths + ) outputs = { "full_sweep": full_sweep, diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index cb41dab10b..6ce2f89968 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -38,6 +38,7 @@ ADAPTER_PACKAGES, MESSAGING_PACKAGES, MESSAGING_TUTORIAL_INPUTS, + PROVISION_JOURNEY_PACKAGES, RENDER_TUTORIAL_INPUTS, SCHEDULING_TUTORIAL_INPUTS, STACK_CLIENT_PACKAGES, @@ -119,6 +120,46 @@ def provision_test_variables() -> set[str]: ) +PROVISION_JOURNEY_STEP = "Product provisioning PostgreSQL journeys" + + +def provision_journeys() -> dict[str, tuple[str, tuple[str, ...]]]: + """Each product's provisioning journey: package, test target and tests. + + A journey is an integration test target that reads the shared provisioning + test environment. Its tests are every test in a file gated on + postgres-test as a whole, or the tests after the first postgres-test gate + in a file that also holds ungated command tests. + """ + + journeys = {} + for target in sorted(Path("crates").glob("*/tests/*.rs")): + package = target.parts[1] + text = target.read_text(encoding="utf-8") + if package == "registry-platform-provision" or "provision_test_env" not in text: + continue + gate = '#![cfg(feature = "postgres-test")]' + if gate not in text: + text = text[text.index('#[cfg(feature = "postgres-test")]') :] + tests = re.findall( + r"#\[(?:tokio::)?test[^\]]*\]\s*(?:#\[[^\]]*\]\s*)*(?:async\s+)?fn\s+(\w+)", + text, + ) + journeys[package] = (target.stem, tuple(tests)) + return journeys + + +def cargo_test_commands(run: str) -> list[str]: + """Each cargo test command in a run script, continuation lines joined.""" + + commands = [] + for line in run.replace("\\\n", " ").splitlines(): + for segment in re.split(r"\||&&|;", line): + if "cargo test" in segment: + commands.append(" ".join(segment.split())) + return commands + + def journey_products() -> dict[str, Any]: """The journeys' product column, read from its checked-in table.""" @@ -4396,6 +4437,116 @@ def test_contracts_journeys_lane_runs_the_provisioning_postgres_suite( self.assertIn("org.registrystack.ci.postgres-service", stop_run) self.assertIn('docker rm --force "${CONTAINER_ID}"', stop_run) + def test_product_provisioning_changes_select_the_tls_postgres_lane(self) -> None: + # A package that adds a journey adds itself to the classifier's list. + journeys = provision_journeys() + self.assertEqual(set(PROVISION_JOURNEY_PACKAGES), set(journeys)) + edgeless = Workspace(without_dependency_edges(self.metadata)) + paths = [ + *(f"crates/{package}/src/provision.rs" for package in journeys), + *(f"crates/{package}/tests/{target}.rs" for package, (target, _) in journeys.items()), + "crates/registry-casework/migrations/0001_review_baseline.sql", + "crates/registry-documents/migrations/0001_documents.sql", + "crates/registry-messaging/migrations/0001_messaging.sql", + "crates/registry-scheduling/migrations/0001_scheduling.sql", + ] + for graph, workspace in (("real", self.workspace), ("edgeless", edgeless)): + for path in paths: + for event, outputs in ( + ("pull_request", classify(workspace, (path,), pull_request=True)), + ("merge_group", classify(workspace, (path,))), + ): + with self.subTest(graph=graph, path=path, event=event): + self.assertTrue(outputs["breg_contracts"]) + self.assertIn( + PROVISION_POSTGRES_LANE, outputs["breg_contracts_lanes"] + ) + + def test_contracts_journeys_lane_runs_each_product_provisioning_journey( + self, + ) -> None: + steps = self.workflow_jobs["breg-contracts"]["steps"] + names = [step.get("name") for step in steps] + suite = names.index("Provisioning PostgreSQL suite") + journey = names.index(PROVISION_JOURNEY_STEP) + stop = names.index("Stop PostgreSQL 16 for the provisioning floor test") + self.assertLess(suite, journey) + self.assertLess(journey, stop) + step = steps[journey] + self.assertEqual(f"matrix.lane == '{PROVISION_POSTGRES_LANE}'", step["if"]) + + # The journeys read the two variables of the shared test helper, and + # the URL verifies the server certificate and its host name. + run = step["run"] + self.assertRegex( + run, + r'(?m)^export PROVISION_TEST_DATABASE_URL="postgresql://breg:breg_test@' + r'localhost:\$\{DATABASE_PORT\}/postgres\?sslmode=verify-full"$', + ) + self.assertRegex(run, r"(?m)^export PROVISION_TEST_DATABASE_CA=\S") + + journeys = provision_journeys() + command = folded_command(step) + for package, (target, _) in journeys.items(): + with self.subTest(package=package): + self.assertIn( + f"cargo test --locked -p {package} --features postgres-test " + f'--test {target} | tee "${{RUNNER_TEMP}}/provision-journey-{package}.log"', + command, + ) + # A run that selected no test still exits 0, so every log needs a pass + # count, no ignored test, and the journey's own line. + self.assertIn(f"for package in {' '.join(journeys)}; do", command) + self.assertIn( + "grep -Eq '^test result: ok\\. [1-9][0-9]* passed; 0 failed; 0 ignored' " + '"${log}"', + command, + ) + self.assertIn( + "grep -Eq '^test ([a-z_]+::)?provision_then_apply_then_serve_with_[a-z_]+ " + "\\.\\.\\. ok$' \"${log}\"", + command, + ) + + def test_other_postgres_steps_leave_the_provisioning_journeys_to_the_tls_lane( + self, + ) -> None: + # Product PostgreSQL lanes serve plaintext, and the journeys refuse a + # server they cannot verify. A command there that runs a journey + # package's every test target skips the journey's tests. + journeys = provision_journeys() + sources = [] + for workflow in sorted(Path(".github/workflows").glob("*.yml")): + jobs = yaml.safe_load(workflow.read_text(encoding="utf-8"))["jobs"] + for job_name, job in jobs.items(): + for step in job.get("steps", []): + if step.get("name") != PROVISION_JOURNEY_STEP: + source = f"{workflow.name}:{job_name}:{step.get('name')}" + sources.append((source, step.get("run", ""))) + for script in sorted(Path("products").glob("*/scripts/*.sh")): + sources.append((str(script), script.read_text(encoding="utf-8"))) + + checked = 0 + for source, run in sources: + for command in cargo_test_commands(run): + for package, (target, tests) in journeys.items(): + if not re.search(rf"-p {re.escape(package)}(?=\s|$)", command): + continue + if "postgres-test" not in command: + continue + with self.subTest(source=source, package=package): + self.assertNotIn(f"--test {target} ", f"{command} ") + selectors = re.findall( + r"--(?:test|lib|bins?|examples?|doc)(?=\s|$)", command + ) + every_target = "--tests" in command or "--all-targets" in command + if every_target or not selectors: + checked += 1 + for test in tests: + self.assertIn(f"--skip {test}", command) + # The Messaging lane's messagingctl run is one such command. + self.assertGreaterEqual(checked, 1) + def edit_lock_package(text: str, name: str, **fields: str) -> str: """Return the lockfile with one uniquely named package's fields replaced.""" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a8a19c89da..84c2fc4fa5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1439,7 +1439,11 @@ jobs: - name: Verify messagingctl messages commands env: MESSAGING_TEST_DATABASE_URL: postgresql://messaging:messaging_test@localhost:${{ job.services.postgres.ports['5432'] }}/messaging - run: cargo test --locked -p registry-messagingctl --features postgres-test --tests + # The provisioning journey needs a TLS server and runs in the + # contracts-journeys lane. + run: >- + cargo test --locked -p registry-messagingctl --features postgres-test --tests + -- --skip provision_then_apply_then_serve_with_split_roles - name: Send one email and one SMS through messagingctl dev env: MESSAGINGCTL_BIN: ${{ github.workspace }}/target/debug/messagingctl @@ -1995,6 +1999,46 @@ jobs: grep -Eq '^test result: ok\. [1-9][0-9]* passed; 0 failed; 0 ignored' "${RUNNER_TEMP}/provision-postgres-${target}.log" || { echo "::error::expected the provisioning PostgreSQL ${target} tests to pass with no test ignored"; exit 1; } done + - name: Product provisioning PostgreSQL journeys + if: matrix.lane == 'contracts-journeys' + shell: bash + env: + DATABASE_PORT: ${{ job.services.postgres.ports['5432'] }} + run: | + set -euo pipefail + if [[ ! "${DATABASE_PORT}" =~ ^[0-9]+$ ]]; then + echo "::error::the provisioning journeys need the port of the TLS PostgreSQL service" + exit 1 + fi + if [[ ! -s "${BREG_TEST_TLS_CA_PEM_PATH}" ]]; then + echo "::error::the provisioning journeys need the CA file ${BREG_TEST_TLS_CA_PEM_PATH}" + exit 1 + fi + # Each journey provisions its product's database and roles on the + # TLS-only service, applies as the owner role and serves as the + # runtime role. + export PROVISION_TEST_DATABASE_URL="postgresql://breg:breg_test@localhost:${DATABASE_PORT}/postgres?sslmode=verify-full" + export PROVISION_TEST_DATABASE_CA="${BREG_TEST_TLS_CA_PEM_PATH}" + cargo test --locked -p registry-bregctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-bregctl.log" + cargo test --locked -p registry-caseworkctl --features postgres-test --test provision \ + | tee "${RUNNER_TEMP}/provision-journey-registry-caseworkctl.log" + cargo test --locked -p registry-coordinator --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-coordinator.log" + cargo test --locked -p registry-documentsctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-documentsctl.log" + cargo test --locked -p registry-messagingctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-messagingctl.log" + cargo test --locked -p registry-schedulingctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-schedulingctl.log" + # A run that selected no test still exits 0, so every log needs a + # pass count, no ignored test, and the journey's own line. + for package in registry-bregctl registry-caseworkctl registry-coordinator registry-documentsctl registry-messagingctl registry-schedulingctl; do + log="${RUNNER_TEMP}/provision-journey-${package}.log" + grep -Eq '^test result: ok\. [1-9][0-9]* passed; 0 failed; 0 ignored' "${log}" || { echo "::error::expected the ${package} provisioning journey tests to pass with no test ignored"; exit 1; } + grep -Eq '^test ([a-z_]+::)?provision_then_apply_then_serve_with_[a-z_]+ \.\.\. ok$' "${log}" || { echo "::error::expected the ${package} provisioning journey to run and pass"; exit 1; } + done + - name: Stop PostgreSQL 16 for the provisioning floor test if: always() && matrix.lane == 'contracts-journeys' && steps.provision-postgres-16.outputs.container_id != '' env: From 7e9121fbeced9461fd5c1cda17960692e56f0c4d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 05:12:11 +0100 Subject: [PATCH 032/136] feat: count and log every refused request in Coordinator, BReg and Casework feat(coordinator): count and log every refused caller under the check that refused it Each refusal answers as before and is now counted in coordinator_request_refusals_total{check} and written as one request refused line with the trace id. Policy denials after authentication and refused signed event deliveries are counted too. Loopback hosts follow the shared rule. feat(breg): count and log every refused request under the check that refused it Each refusal answers as before and is now counted in breg_request_refusals_total{check}, published at zero for every check, and written as one request refused line with the trace id. That line replaces the authentication line that named a stage. feat(casework): count and log every refused request under the check that refused it Each refusal answers as before and is now counted in casework_request_refusals_total{check} and written as one request refused line with the trace id. A static key set refusal names the broken rule under the key set code, and a review completion destination accepts any loopback literal in plain http. Signed-off-by: Jeremi Joslin --- crates/registry-breg/Cargo.toml | 9 +- crates/registry-breg/src/api/context.rs | 6 +- crates/registry-breg/src/api/mod.rs | 42 +- crates/registry-breg/src/auth.rs | 199 +++-- crates/registry-breg/src/correlation.rs | 17 + crates/registry-breg/src/metrics.rs | 72 +- .../tests/authentication_refusals.rs | 829 ++++++++++++++++++ .../tests/golden/authentication_refusals.json | 288 ++++++ .../tests/golden/metrics-scrape-sampled.txt | 47 + .../tests/golden/metrics-scrape-unsampled.txt | 47 + crates/registry-breg/tests/http_auth.rs | 27 +- .../tests/token_characterisation.rs | 90 +- crates/registry-casework/Cargo.toml | 4 +- crates/registry-casework/src/auth.rs | 516 ++++++----- .../registry-casework/src/auth/delegated.rs | 152 +--- crates/registry-casework/src/config.rs | 115 ++- crates/registry-casework/src/http.rs | 501 +++++++++-- .../src/http/source_credentials.rs | 28 +- crates/registry-casework/src/metrics.rs | 75 +- .../tests/golden/refusal_responses.json | 403 +++++++++ .../tests/human_identity_auth.rs | 28 +- .../registry-casework/tests/refusal_golden.rs | 556 ++++++++++++ .../tests/token_characterisation.rs | 57 +- crates/registry-coordinator/Cargo.toml | 4 +- crates/registry-coordinator/src/access.rs | 100 ++- .../src/access/token_characterisation.rs | 50 +- crates/registry-coordinator/src/cli.rs | 8 +- crates/registry-coordinator/src/completion.rs | 66 +- crates/registry-coordinator/src/decision.rs | 8 +- crates/registry-coordinator/src/error.rs | 13 + .../registry-coordinator/src/event_trigger.rs | 23 +- .../src/event_trigger_tests.rs | 86 +- .../registry-coordinator/src/external_http.rs | 8 +- crates/registry-coordinator/src/http.rs | 347 +++++++- crates/registry-coordinator/src/metrics.rs | 46 +- crates/registry-coordinator/src/runtime.rs | 33 +- crates/registry-coordinator/src/store.rs | 7 +- .../src/content/docs/operate/breg-monitor.mdx | 24 + .../src/content/docs/operate/casework.mdx | 15 + .../src/content/docs/security/coordinator.mdx | 26 +- products/breg/CHANGELOG.md | 7 + products/casework/CHANGELOG.md | 14 + products/coordinator/CHANGELOG.md | 12 + 43 files changed, 4316 insertions(+), 689 deletions(-) create mode 100644 crates/registry-breg/tests/authentication_refusals.rs create mode 100644 crates/registry-breg/tests/golden/authentication_refusals.json create mode 100644 crates/registry-casework/tests/golden/refusal_responses.json create mode 100644 crates/registry-casework/tests/refusal_golden.rs diff --git a/crates/registry-breg/Cargo.toml b/crates/registry-breg/Cargo.toml index 38c108bf58..3938916f16 100644 --- a/crates/registry-breg/Cargo.toml +++ b/crates/registry-breg/Cargo.toml @@ -328,13 +328,13 @@ registry-platform-canonical-json.workspace = true registry-platform-calendar.workspace = true registry-manifest-core.workspace = true registry-platform-audit = { workspace = true, optional = true } -registry-platform-authcommon = { workspace = true, optional = true } +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"], optional = true } registry-platform-buildinfo = { workspace = true, optional = true } registry-platform-config.workspace = true registry-platform-crypto = { workspace = true, optional = true } registry-platform-dispatch = { workspace = true, features = ["postgres"], optional = true } registry-platform-hooks = { workspace = true, features = ["rhai"] } -registry-platform-httpsec = { workspace = true, features = ["server"], optional = true } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"], optional = true } registry-platform-httputil = { workspace = true, optional = true } registry-platform-metrics = { workspace = true, optional = true } registry-platform-objectstore = { workspace = true, optional = true } @@ -511,6 +511,11 @@ name = "http_auth" path = "tests/http_auth.rs" required-features = ["runtime"] +[[test]] +name = "authentication_refusals" +path = "tests/authentication_refusals.rs" +required-features = ["runtime"] + [[test]] name = "http_read_only" path = "tests/http_read_only.rs" diff --git a/crates/registry-breg/src/api/context.rs b/crates/registry-breg/src/api/context.rs index 86174dc862..a214692c46 100644 --- a/crates/registry-breg/src/api/context.rs +++ b/crates/registry-breg/src/api/context.rs @@ -106,7 +106,11 @@ impl axum::extract::FromRequestParts for Authenticated { .get::() .cloned() .map(Self) - .ok_or_else(crate::auth::authentication_refused) + .ok_or_else(|| { + crate::auth::authentication_refused( + registry_platform_authcommon::FailedCheck::CredentialMissing, + ) + }) } } diff --git a/crates/registry-breg/src/api/mod.rs b/crates/registry-breg/src/api/mod.rs index f06dced295..bfea094a6e 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -21,9 +21,7 @@ use std::sync::Arc; use axum::body::{to_bytes, Body}; use axum::extract::{Path, RawQuery, State}; -use axum::http::header::{ - ACCEPT, AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_MATCH, LINK, VARY, -}; +use axum::http::header::{ACCEPT, CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_MATCH, LINK, VARY}; use axum::http::{HeaderMap, HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, patch, post}; @@ -75,6 +73,7 @@ use crate::problem_location::{BatchItemMember, RequestLocation}; use crate::query as strict_query; use crate::query_binding::CursorBindingQuery; use crate::record_profile::{self, RecordRepresentation}; +use registry_platform_authcommon::FailedCheck; use uuid::Uuid; use crate::artifacts::{ @@ -312,19 +311,21 @@ async fn review_completion( body: Body, ) -> Response { let Some(receiver) = service.review_completions.as_ref() else { - return concealed(); - }; - let Some(authorization) = single_header(&headers, AUTHORIZATION.as_str()) else { - return review_completion_refused(); + return crate::correlation::note_refusal( + fixed_problem(ProblemCode::ResourceNotFound), + FailedCheck::Visibility, + ); }; - let Ok(token) = registry_platform_authcommon::parse_bearer_token(authorization) else { - return review_completion_refused(); + let token = match crate::auth::bearer_token(&headers) { + Ok(token) => token, + Err(check) => return review_completion_refused(check), }; - let Some(recipient) = single_header(&headers, REVIEW_COMPLETION_RECIPIENT_HEADER) else { - return review_completion_refused(); + let recipient = match recipient_binding(&headers) { + Ok(recipient) => recipient, + Err(check) => return review_completion_refused(check), }; let Some((authority, recovery_days)) = receiver.authority(token, recipient) else { - return review_completion_refused(); + return review_completion_refused(FailedCheck::SharedSecret); }; if !single_content_type(&headers, "application/json") { return unsupported_media_type(); @@ -387,8 +388,21 @@ mod review_completion_tests { } } -fn review_completion_refused() -> Response { - fixed_problem(ProblemCode::AuthenticationRefused) +/// The recipient the completion names, or the check the header failed: absent +/// is a missing credential, repeated or unreadable is a malformed one. +fn recipient_binding(headers: &HeaderMap) -> Result<&str, FailedCheck> { + let mut values = headers.get_all(REVIEW_COMPLETION_RECIPIENT_HEADER).iter(); + let Some(value) = values.next() else { + return Err(FailedCheck::CredentialMissing); + }; + if values.next().is_some() { + return Err(FailedCheck::CredentialMalformed); + } + value.to_str().map_err(|_| FailedCheck::CredentialMalformed) +} + +fn review_completion_refused(check: FailedCheck) -> Response { + crate::correlation::note_refusal(fixed_problem(ProblemCode::AuthenticationRefused), check) } async fn health() -> Response { diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index 4cfab7bc98..a23c2a03a7 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -13,7 +13,9 @@ use axum::http::header::AUTHORIZATION; use axum::http::{Request, StatusCode}; use axum::middleware::Next; use axum::response::Response; -use registry_platform_authcommon::{parse_bearer_token, validate_compact_access_token}; +use registry_platform_authcommon::{ + parse_bearer_token, validate_compact_access_token, BearerParseError, FailedCheck, +}; use registry_platform_oidc::{ actor_kind, grant_claims, is_access_token_typ_pair, Audience, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, @@ -161,6 +163,28 @@ pub enum AuthenticationError { InvalidClaims, } +impl AuthenticationError { + /// Pair the failure with the check that produced it. The check is + /// operator-side only: it reaches the refusal counter and log line, never + /// the response. + fn because(self, check: FailedCheck) -> Refusal { + Refusal { error: self, check } + } +} + +/// A closed request failure and the check that failed. Every refusal built in +/// this module names its check, so none reaches the recording layer without +/// one. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct Refusal { + error: AuthenticationError, + check: FailedCheck, +} + +fn invalid_claims(check: FailedCheck) -> Refusal { + AuthenticationError::InvalidClaims.because(check) +} + /// Production OIDC verifier plus the only claim mapping allowed to construct /// [`VerifiedRequestClaims`]. pub struct RegistryAuthenticator { @@ -183,14 +207,6 @@ pub struct RegistryAuthenticator { } impl RegistryAuthenticator { - pub(crate) fn record_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Header, - "BReg authentication refused" - ); - } - /// Bind one exact platform verifier profile and one exact authority mapping /// to the immutable compiled Registry served by this process. pub fn new( @@ -229,16 +245,20 @@ impl RegistryAuthenticator { &self, token: &str, ) -> Result { + self.authenticate_checked(token) + .await + .map_err(|refusal| refusal.error) + } + + /// [`Self::authenticate`], with the check that refused the token. + pub(crate) async fn authenticate_checked( + &self, + token: &str, + ) -> Result { validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::MalformedCredential + AuthenticationError::MalformedCredential.because(FailedCheck::CredentialMalformed) })?; let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "BReg authentication refused" - ); // UnknownKid precedes signature verification and also covers denied // keys. It cannot establish rotation, regardless of the key source. if matches!(error, OidcError::UnknownKid) @@ -251,10 +271,10 @@ impl RegistryAuthenticator { check issuer key configuration and key policy before changing trust" ); } - AuthenticationError::VerificationRefused + AuthenticationError::VerificationRefused.because(error.failed_check()) })?; if !accepted_audience(verified.claims.aud.as_ref(), &self.audience) { - return Err(AuthenticationError::InvalidClaims); + return Err(invalid_claims(FailedCheck::TokenAudience)); } let claims = &verified.claims.extra; @@ -267,22 +287,25 @@ impl RegistryAuthenticator { subject.as_ref() } else { claims.get(&self.principal_claim) - })?; + }) + .map_err(|error| error.because(FailedCheck::TokenClaims))?; let purpose = self .purpose_claim .as_deref() .map(|name| optional_direct_string(claims.get(name))) - .transpose()? + .transpose() + .map_err(|error| error.because(FailedCheck::TokenClaims))? .flatten(); if verified.scopes.len() > MAX_SCOPE_VALUES { - return Err(AuthenticationError::InvalidClaims); + return Err(invalid_claims(FailedCheck::TokenClaims)); } let scopes = verified .scopes .iter() .cloned() .map(validate_scope) - .collect::, _>>()?; + .collect::, _>>() + .map_err(|error| error.because(FailedCheck::TokenClaims))?; let direct_claims = self .direct_claims .iter() @@ -296,19 +319,21 @@ impl RegistryAuthenticator { mapped_claim(value, expectation).map(|value| (name.clone(), value)) }) }) - .collect::, _>>()?; + .collect::, _>>() + .map_err(|error| error.because(FailedCheck::TokenClaims))?; let requester_client = verified .matched_client_id() - .map_err(|_| AuthenticationError::InvalidClaims)? + .map_err(|_| invalid_claims(FailedCheck::TokenClient))? .map(str::to_owned); - let actor_subject = optional_actor_subject(claims.get("act"), &self.issuer)?; + let actor_subject = optional_actor_subject(claims.get("act"), &self.issuer) + .map_err(|error| error.because(FailedCheck::Delegation))?; if let Some(actor) = actor_subject.as_deref() { let client = requester_client .as_deref() - .ok_or(AuthenticationError::InvalidClaims)?; + .ok_or_else(|| invalid_claims(FailedCheck::TokenClient))?; if self.trusted_actors.get(client).map(String::as_str) != Some(actor) { - return Err(AuthenticationError::InvalidClaims); + return Err(invalid_claims(FailedCheck::Delegation)); } } // A token exchange copies the subject's claims, so a kind claim on a @@ -318,10 +343,10 @@ impl RegistryAuthenticator { registry_platform_oidc::ActorKind::Agent } else { if !claims.contains_key(&self.contextual_claims.actor_kind) { - return Err(AuthenticationError::MissingActorKind); + return Err(AuthenticationError::MissingActorKind.because(FailedCheck::ActorKind)); } actor_kind(&verified.claims, &self.contextual_claims) - .map_err(|_| AuthenticationError::InvalidClaims)? + .map_err(|_| invalid_claims(FailedCheck::ActorKind))? }); // The person is named by the configured principal claim, the same // claim every access profile reads. A review authority compares this @@ -337,25 +362,26 @@ impl RegistryAuthenticator { }; let now = SystemTime::now() .duration_since(UNIX_EPOCH) - .map_err(|_| AuthenticationError::InvalidClaims)? + .map_err(|_| invalid_claims(FailedCheck::TokenTime))? .as_secs(); let grant = grant_claims(&verified.claims, &self.contextual_claims, now) - .map_err(|_| AuthenticationError::InvalidClaims)?; + .map_err(|_| invalid_claims(FailedCheck::TaskGrantClaims))?; if let Some(grant) = &grant { grant .verify_context(&verified, &self.audience) - .map_err(|_| AuthenticationError::InvalidClaims)?; + .map_err(|_| invalid_claims(FailedCheck::TaskGrantClaims))?; if !task_grant_token_lifetime_is_short( verified.claims.iat, verified.claims.exp, now, self.leeway, ) { - return Err(AuthenticationError::InvalidClaims); + return Err(invalid_claims(FailedCheck::TaskGrantLifetime)); } } let grant_subjects = if grant.is_some() { - bounded_identity(claims.get("identity"))? + bounded_identity(claims.get("identity")) + .map_err(|error| error.because(FailedCheck::TaskGrantClaims))? } else { BTreeMap::new() }; @@ -372,7 +398,8 @@ impl RegistryAuthenticator { mapped_claim(value, expectation).map(|value| (name.clone(), value)) }) }) - .collect::, _>>()? + .collect::, _>>() + .map_err(|error| error.because(FailedCheck::TaskGrantClaims))? } else { direct_claims }; @@ -401,7 +428,7 @@ impl RegistryAuthenticator { }) .and_then(|claims| claims.with_human_identity(human_identity)) .and_then(|claims| claims.with_consent_claims(recipients, &self.consent_decisions)) - .map_err(|_| AuthenticationError::InvalidClaims) + .map_err(|_| invalid_claims(FailedCheck::TokenClaims)) } } @@ -470,45 +497,48 @@ pub(crate) async fn authenticate_request( ) -> Response { request.extensions_mut().remove::(); let token = match bearer_token(request.headers()) { - Ok(Some(token)) => token, - Ok(None) | Err(_) => { - authenticator.record_header_refusal(); - return authentication_refused(); - } + Ok(token) => token, + Err(check) => return authentication_refused(check), }; - let claims = match authenticator.authenticate(token).await { + let claims = match authenticator.authenticate_checked(token).await { Ok(claims) => claims, - Err(AuthenticationError::MissingActorKind) => { - // A caller can replay such a credential, so the warning is bounded - // the same way as an unknown key identifier. - if admit_refusal_warning(&authenticator.last_actor_kind_warning, Instant::now()) { - tracing::warn!( - target: "registry_breg::auth", - message = "verified credential is missing the configured actor-kind claim" - ); + Err(refusal) => { + if refusal.error == AuthenticationError::MissingActorKind { + // A caller can replay such a credential, so the warning is bounded + // the same way as an unknown key identifier. + if admit_refusal_warning(&authenticator.last_actor_kind_warning, Instant::now()) { + tracing::warn!( + target: "registry_breg::auth", + message = "verified credential is missing the configured actor-kind claim" + ); + } } - return authentication_refused(); + return authentication_refused(refusal.check); } - Err(_) => return authentication_refused(), }; request.extensions_mut().insert(claims); next.run(request).await } -fn bearer_token(headers: &axum::http::HeaderMap) -> Result, AuthenticationError> { +/// The one bearer credential on a request, or the check it failed. A request +/// with no credential, or one in another scheme, names the missing +/// credential. A repeated or unreadable header, or a bearer that is not one +/// well-formed token, names the malformed credential. +pub(crate) fn bearer_token(headers: &axum::http::HeaderMap) -> Result<&str, FailedCheck> { let mut values = headers.get_all(AUTHORIZATION).iter(); let Some(value) = values.next() else { - return Ok(None); + return Err(FailedCheck::CredentialMissing); }; if values.next().is_some() { - return Err(AuthenticationError::MalformedCredential); + return Err(FailedCheck::CredentialMalformed); } let value = value .to_str() - .map_err(|_| AuthenticationError::MalformedCredential)?; - parse_bearer_token(value) - .map(Some) - .map_err(|_| AuthenticationError::MalformedCredential) + .map_err(|_| FailedCheck::CredentialMalformed)?; + parse_bearer_token(value).map_err(|error| match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) } fn validate_verifier_profile( @@ -956,12 +986,17 @@ fn mapped_scalar_claim( Ok(value) } -pub(crate) fn authentication_refused() -> Response { - crate::correlation::problem_response( - StatusCode::UNAUTHORIZED, - "Unauthorized", - "The bearer credential is missing or refused.", - "authentication.refused", +/// The 401 for a missing or refused credential. The answer is the same for +/// every check, so a caller learns nothing about which one failed. +pub(crate) fn authentication_refused(check: FailedCheck) -> Response { + crate::correlation::note_refusal( + crate::correlation::problem_response( + StatusCode::UNAUTHORIZED, + "Unauthorized", + "The bearer credential is missing or refused.", + "authentication.refused", + ), + check, ) } @@ -969,6 +1004,40 @@ pub(crate) fn authentication_refused() -> Response { mod tests { use super::*; + #[test] + fn a_bearer_names_the_check_its_header_failed() { + let headers = |values: &[&'static str]| { + let mut headers = axum::http::HeaderMap::new(); + for value in values { + headers.append(AUTHORIZATION, axum::http::HeaderValue::from_static(value)); + } + headers + }; + assert_eq!(bearer_token(&headers(&["Bearer a.b.c"])), Ok("a.b.c")); + for (values, check) in [ + (&[][..], FailedCheck::CredentialMissing), + (&["Basic abc"][..], FailedCheck::CredentialMissing), + ( + &["Bearer a", "Bearer b"][..], + FailedCheck::CredentialMalformed, + ), + (&["Bearer a"][..], FailedCheck::CredentialMalformed), + (&["Bearer"][..], FailedCheck::CredentialMalformed), + (&["Bearer a b"][..], FailedCheck::CredentialMalformed), + ] { + assert_eq!(bearer_token(&headers(values)), Err(check), "{values:?}"); + } + let mut unreadable = axum::http::HeaderMap::new(); + unreadable.insert( + AUTHORIZATION, + axum::http::HeaderValue::from_bytes(b"Bearer \xff").unwrap(), + ); + assert_eq!( + bearer_token(&unreadable), + Err(FailedCheck::CredentialMalformed) + ); + } + #[test] fn refusal_warnings_recover_poisoned_timestamps_and_preserve_rate_limits() { let last_warning = Mutex::new(None); diff --git a/crates/registry-breg/src/correlation.rs b/crates/registry-breg/src/correlation.rs index 470e37782b..5855fea092 100644 --- a/crates/registry-breg/src/correlation.rs +++ b/crates/registry-breg/src/correlation.rs @@ -9,6 +9,7 @@ use axum::http::header::{CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE}; use axum::http::{HeaderMap, Request, StatusCode}; use axum::middleware::Next; use axum::response::Response; +use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote}; use registry_platform_httpsec::{Problem, ProblemBody, TraceContext, TraceId}; use serde_json::Value; use uuid::Uuid; @@ -118,6 +119,15 @@ pub(crate) fn problem_response( response } +/// Name the check a refusal failed. The member rides in the response +/// extensions to [`finish_response`], which counts it and writes the one +/// bounded log line. It is never serialized, so the answer's bytes do not +/// change. +pub(crate) fn note_refusal(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + /// Build one public problem with a safe action field path. /// /// The field path is produced only from fixed envelope members or compiled @@ -435,6 +445,13 @@ pub(crate) fn finish_response( ); } correlation.apply_trace(response.headers_mut()); + if let Some(note) = response.extensions().get::().copied() { + record_refusal!( + crate::metrics::process_refusal_recorder(), + note, + trace_id = correlation.trace_id() + ); + } let status = status_class(response.status()); let problem_code = problem.as_ref().map_or("none", |problem| problem.code); diff --git a/crates/registry-breg/src/metrics.rs b/crates/registry-breg/src/metrics.rs index 21b50966c3..a3473f8262 100644 --- a/crates/registry-breg/src/metrics.rs +++ b/crates/registry-breg/src/metrics.rs @@ -13,7 +13,9 @@ //! status label is one of three coarse classes. Request paths, query values, //! principals, record identifiers, and problem codes never become labels, so //! a caller cannot write arbitrary text into a series and the series count is -//! bounded by the route table regardless of traffic. The pool gauges are +//! bounded by the route table regardless of traffic. The refusal counter +//! `breg_request_refusals_total` carries one `check` label from the closed +//! `FailedCheck` set. The pool gauges are //! republished from the live pool at scrape time and carry only a fixed state //! label. //! @@ -38,7 +40,7 @@ use std::{ collections::BTreeMap, sync::{ atomic::{AtomicU64, Ordering}, - Arc, Mutex, + Arc, Mutex, OnceLock, }, time::{Duration, Instant}, }; @@ -52,6 +54,7 @@ use axum::{ Router, }; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ sample_error_class, Exposition, HistogramSnapshot, MetricKind, ScrapeDeadline, SumCountOrder, CLASS_NO_TIME_LEFT, CLASS_POOL, CONTENT_TYPE as METRICS_MEDIA_TYPE, @@ -156,9 +159,12 @@ const DURATION_BUCKETS: [f64; 9] = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1. /// Series are keyed only by the closed label set described on this module, so /// the registry is bounded by the route table regardless of traffic and needs /// no eviction. -#[derive(Default)] pub struct Metrics { series: Mutex>, + /// The refusal counter this registry publishes as + /// `breg_request_refusals_total`. A served registry shares the process + /// recorder that the request boundary counts into. + refusals: Arc, /// The pool the metrics scrape handler samples immediately before each /// render. `None` for registries that are never served on the metrics /// listener (for example, a focused unit test). @@ -177,6 +183,36 @@ pub struct Metrics { sample_failures: [AtomicU64; SampleKind::ALL.len()], } +/// The process-wide refusal recorder: the one counter family and the one log +/// budget that every refused request in this process shares, whichever router +/// served it. It is built once, from a closed label space the enum owns, so +/// construction cannot fail. +pub(crate) fn process_refusal_recorder() -> &'static Arc { + static RECORDER: OnceLock> = OnceLock::new(); + RECORDER.get_or_init(|| Arc::new(new_refusal_recorder())) +} + +fn new_refusal_recorder() -> RefusalRecorder { + RefusalRecorder::new("breg").expect("the refusal counter's closed label space is valid") +} + +impl Default for Metrics { + /// A registry with a private refusal counter, for tests that read a + /// deterministic exposition. A served registry is built by + /// [`Metrics::new`]. + fn default() -> Self { + Self { + series: Mutex::default(), + refusals: Arc::new(new_refusal_recorder()), + pool: None, + workers: Vec::new(), + queue_sample: tokio::sync::Mutex::new(()), + active_package_digest: None, + sample_failures: Default::default(), + } + } +} + /// A background worker reported by `breg_worker_last_success_age_seconds`. /// /// The worker label is one of these fixed values, so the series count is @@ -289,14 +325,20 @@ impl Metrics { pub(crate) fn new(pool: RuntimePool) -> Self { Self { pool: Some(pool), + refusals: Arc::clone(process_refusal_recorder()), ..Self::default() } } + /// A registry without a pool that publishes the process refusal counter, + /// so a test can read what the request boundary counted. #[doc(hidden)] #[must_use] pub fn without_pool_for_test() -> Self { - Self::default() + Self { + refusals: Arc::clone(process_refusal_recorder()), + ..Self::default() + } } #[cfg(feature = "postgres-test")] @@ -631,6 +673,7 @@ impl Metrics { 1_u8, ); } + self.refusals.counter().write(&mut out).expect(DECLARATION); out.finish() } @@ -1288,6 +1331,27 @@ mod tests { use std::collections::BTreeSet; use tower::util::ServiceExt; + #[test] + fn the_refusal_counter_declares_every_check_and_publishes_it_at_zero() { + use registry_platform_authcommon::FailedCheck; + let rendered = Metrics::default().render(None); + for check in FailedCheck::ALL { + assert!( + rendered.contains(&format!( + "breg_request_refusals_total{{check=\"{}\"}} 0\n", + check.as_str() + )), + "{} is declared", + check.as_str() + ); + } + let recorder = new_refusal_recorder(); + for check in FailedCheck::ALL { + let _ = recorder.record(check); + assert_eq!(recorder.counter().get(&[check.as_str()]), Some(1)); + } + } + #[test] fn duration_buckets_are_cumulative_and_carry_an_infinite_bound() { let metrics = Metrics::default(); diff --git a/crates/registry-breg/tests/authentication_refusals.rs b/crates/registry-breg/tests/authentication_refusals.rs new file mode 100644 index 0000000000..a33012650a --- /dev/null +++ b/crates/registry-breg/tests/authentication_refusals.rs @@ -0,0 +1,829 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Every authentication refusal answers with the fixed 401 problem, counts +//! once under `breg_request_refusals_total{check}`, and writes one value-free +//! `request refused` line that names the check. +//! +//! The recorder is process-wide and admits five log lines per check per +//! minute, so this file drives every case from one test and keeps each check +//! under that bound. +//! +//! `tests/golden/authentication_refusals.json` freezes the status, the +//! headers that matter and the body (minus `traceId`) of each answer. +//! `REGISTRY_BREG_WRITE_GOLDEN=1` rewrites it. A change to the file in a +//! review is a change to a public response. + +#![cfg(feature = "runtime")] + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::body::{to_bytes, Body}; +use axum::http::header::AUTHORIZATION; +use axum::http::{HeaderValue, Request}; +use jsonwebtoken::jwk::JwkSet; +use jsonwebtoken::Algorithm; +use registry_breg::api::{ + authenticated_router, router, HeldReadResponse, HttpService, ReadRuntimeIdentity, + ReadServiceError, ReadinessProbe, RecordReadRequest, RecordReadService, ServiceFuture, +}; +use registry_breg::auth::{AuthorityClaimConfig, RegistryAuthenticator}; +use registry_breg::cursor::CursorCodec; +use registry_breg::metrics::{metrics_app, Metrics}; +use registry_breg::postgres::{ConnectionConfig, PoolBounds}; +use registry_breg::review_store::{ + ReviewAuthorityClient, ReviewAuthorityRegistry, ReviewCompletionReceiver, +}; +use registry_breg::{compile_project, parse_project_yaml, CompileProfile, CompiledRegistry}; +use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_oidc::{ClaimNames, JwksFetcher, JwksFetcherConfig, TokenVerifierConfig}; +use registry_platform_testing::{ + fixtures, oidc_verifier_config, sign_ed25519_compact_jwt, MockIdp, +}; +use registry_review_client::{ReviewClient, ReviewClientConfig}; +use serde_json::{json, Value}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber; +use zeroize::Zeroizing; + +const AUDIENCE: &str = "urn:example:breg"; +const PRINCIPAL: &str = "principal-value-never-rendered"; +const ACTOR_ID: &str = "00000000-0000-4000-8000-0000000000aa"; +const RECORD_ID: &str = "00000000-0000-4000-8000-000000000001"; +const GOLDEN: &str = "tests/golden/authentication_refusals.json"; + +const PROJECT: &str = r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {id: refusal-recording, version: 0.1.0, defaultLanguage: en, canonicalBaseIri: https://authoring.example.test} +recordTypes: + case: + primaryDataset: test-dataset + route: cases + mutationMode: mutable + tombstone: false + classification: public + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + - {id: tenant, type: string, required: true, maximumLength: 100, classification: internal} +datasets: + test-dataset: {} + +accessProfiles: + public: + default: true + principalClaim: registry_principal + requiredScopes: [registry.read] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} +"#; + +const CONTEXTUAL_PROJECT: &str = r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {id: refusal-recording-contextual, version: 0.1.0, defaultLanguage: en, canonicalBaseIri: https://authoring.example.test} +recordTypes: + case: + primaryDataset: test-dataset + route: cases + mutationMode: mutable + tombstone: false + classification: public + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + - {id: tenant, type: string, required: true, maximumLength: 100, classification: internal} +datasets: + test-dataset: {} + +accessProfiles: + standing-agent: + principalClaim: sub + requiredScopes: unrestricted + actorKind: agent + requesterClients: [agent-client] + requiredPurposes: [citizen-self-service] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} + delegated-agent: + default: true + principalClaim: sub + requiredScopes: unrestricted + actorKind: agent + requesterClients: [agent-client] + requiredPurposes: [record-review] + taskGrant: {sourceIssuer: https://casework.example} + permissions: + records: + - recordType: case + operations: [get] + readableFields: [label] + rowBoundaries: + - {field: tenant, claim: tenant_claim, operator: equals} +"#; + +struct EmptyReads; + +impl RecordReadService for EmptyReads { + fn get( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } + + fn list( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result> { + Box::pin(async { + Ok(HeldReadResponse::from_json(&json!({"items": []})).expect("fixture serializes")) + }) + } + + fn lookup( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } +} + +struct Ready; + +impl ReadinessProbe for Ready { + fn is_ready(&self) -> ServiceFuture<'_, bool> { + Box::pin(async { true }) + } +} + +fn compiled(source: &str) -> Arc { + let project = parse_project_yaml(source.as_bytes()).expect("project parses"); + Arc::new(compile_project(&project, &[], CompileProfile::Authoring).expect("project compiles")) +} + +fn service(registry: Arc) -> HttpService { + HttpService::new( + registry, + ReadRuntimeIdentity { + package_revision: "package-refusal-test".to_owned(), + schema_fingerprint: "schema-refusal-test".to_owned(), + }, + Arc::new(EmptyReads), + Arc::new(Ready), + Arc::new( + CursorCodec::new( + Zeroizing::new(vec![0x43; 32]), + std::time::Duration::from_secs(300), + ) + .expect("test cursor key is valid"), + ), + ) +} + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock") + .as_secs() +} + +fn key_source(idp: &MockIdp) -> Arc { + Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::dev(), + )) +} + +struct Harness { + app: axum::Router, + idp: MockIdp, +} + +impl Harness { + async fn plain() -> Self { + let registry = compiled(PROJECT); + let idp = MockIdp::start().await; + let authenticator = RegistryAuthenticator::new( + ®istry, + oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]), + key_source(&idp), + AuthorityClaimConfig::new("registry_principal", None), + ) + .expect("authentication config is valid"); + let app = authenticated_router(Arc::new(service(registry)), Arc::new(authenticator)); + Self { app, idp } + } + + async fn contextual() -> Self { + let registry = compiled(CONTEXTUAL_PROJECT); + let idp = MockIdp::start().await; + let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); + verifier.allowed_clients = vec!["agent-client".to_owned()]; + let claims = AuthorityClaimConfig::new("sub", Some("registry_purpose".to_owned())) + .with_contextual_claims( + ClaimNames::default(), + BTreeMap::from([("agent-client".to_owned(), ACTOR_ID.to_owned())]), + ); + let authenticator = + RegistryAuthenticator::new(®istry, verifier, key_source(&idp), claims) + .expect("contextual authentication config is valid"); + let app = authenticated_router(Arc::new(service(registry)), Arc::new(authenticator)); + Self { app, idp } + } + + fn signed(&self, mut claims: Value, kid: &str) -> String { + let now = unix_now(); + let object = claims.as_object_mut().expect("claims are an object"); + object + .entry("iss") + .or_insert_with(|| json!(self.idp.issuer())); + object.entry("iat").or_insert_with(|| json!(now)); + object.entry("nbf").or_insert_with(|| json!(now)); + object.entry("exp").or_insert_with(|| json!(now + 900)); + sign_ed25519_compact_jwt(fixtures::ED25519_PRIVATE_JWK, "JWT", kid, claims) + } + + fn token(&self, claims: Value) -> String { + self.signed(claims, "registry-platform-testing-ed25519-1") + } +} + +fn valid_claims() -> Value { + json!({ + "aud": AUDIENCE, + "registry_actor_kind": "service", + "registry_principal": PRINCIPAL, + "scope": "registry.read", + }) +} + +fn delegated_grant_claims(now: u64) -> Value { + json!({ + "aud": AUDIENCE, + "sub": PRINCIPAL, + "registry_principal": PRINCIPAL, + "azp": "agent-client", + "registry_actor_kind": "agent", + "registry_purpose": "record-review", + "request_purpose": "record-review", + "registry_grant_id": "00000000-0000-4000-8000-0000000000bf", + "registry_approver": "h:synthetic-approver", + "registry_grant_source_issuer": "https://casework.example", + "registry_grant_client": "agent-client", + "registry_grant_resource": AUDIENCE, + "registry_grant_exp": now + 600, + "registry_grant_bounds": {"type":"breg","permissions":[{"collection":"cases","operations":["get"]}]}, + "identity": {"tenant_claim": "tenant-from-approved-identity"} + }) +} + +fn standing_agent_claims(act: Value) -> Value { + json!({ + "aud": AUDIENCE, + "sub": PRINCIPAL, + "azp": "agent-client", + "registry_actor_kind": "agent", + "registry_purpose": "citizen-self-service", + "act": act + }) +} + +fn read_request(path: &str, authorization: &[&str]) -> Request { + let mut request = Request::builder() + .uri(path) + .body(Body::empty()) + .expect("request"); + for value in authorization { + request.headers_mut().append( + AUTHORIZATION, + HeaderValue::from_str(value).expect("header value"), + ); + } + request +} + +fn completion_request(authorization: Option<&str>, recipient: Option<&str>) -> Request { + let mut request = Request::builder() + .method("POST") + .uri("/v1/review-completions") + .body(Body::empty()) + .expect("completion request"); + if let Some(value) = authorization { + request + .headers_mut() + .insert(AUTHORIZATION, HeaderValue::from_str(value).expect("header")); + } + if let Some(value) = recipient { + request.headers_mut().insert( + "registry-recipient-binding", + HeaderValue::from_str(value).expect("header"), + ); + } + request +} + +/// The review-completion router: a receiver with one authority and a pool +/// that never connects. +fn completion_app() -> axum::Router { + let registry = compiled(PROJECT); + let authenticator = Arc::new( + RegistryAuthenticator::new( + ®istry, + TokenVerifierConfig::access_token_profile( + "https://issuer.example.test", + vec![AUDIENCE.to_owned()], + vec![Algorithm::EdDSA], + vec!["at+jwt".to_owned()], + ), + Arc::new(JwksFetcher::new_static( + JwkSet { keys: Vec::new() }, + JwksFetcherConfig::defaults(), + )), + AuthorityClaimConfig::new("registry_principal", None), + ) + .expect("authentication config is valid"), + ); + let bounds = PoolBounds::new( + 1, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(50), + ) + .expect("pool bounds are valid"); + let certificate = rcgen::generate_simple_self_signed(vec!["db.example.invalid".to_owned()]) + .expect("test CA is valid"); + let pool = ConnectionConfig::require_tls_with_custom_ca( + "postgresql://registry_runtime@db.example.invalid/registry", + certificate.cert.der(), + bounds, + ) + .expect("test connection configuration is valid") + .build_pool() + .expect("test pool builds"); + let review_client = ReviewClient::new(ReviewClientConfig::new( + "https://review.example.invalid/" + .parse() + .expect("reserved HTTPS URL"), + )) + .expect("review client builds"); + let authority = Arc::new( + ReviewAuthorityClient::new( + "casework-a".to_owned(), + review_client, + Arc::new( + registry_platform_httputil::StaticToken::new("outgoing-token".to_owned()) + .expect("outgoing token is valid"), + ), + "producer-profile".to_owned(), + "producer-a".to_owned(), + 7, + Some(Zeroizing::new("completion-secret".to_owned())), + Some("registry-a".to_owned()), + ) + .expect("review authority is valid"), + ); + let authorities = Arc::new( + ReviewAuthorityRegistry::new(BTreeMap::from([("casework-a".to_owned(), authority)])) + .expect("review authority registry is valid"), + ); + let receiver = Arc::new(ReviewCompletionReceiver::new(pool, authorities)); + let service = Arc::new(service(registry).with_review_completions(receiver)); + authenticated_router(service, authenticator) +} + +#[derive(Clone, Default)] +struct CapturedLogs(Arc>>); + +impl std::io::Write for CapturedLogs { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 + .lock() + .expect("captured log buffer") + .extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for CapturedLogs { + type Writer = Self; + + fn make_writer(&'writer self) -> Self::Writer { + self.clone() + } +} + +impl CapturedLogs { + fn subscriber(&self) -> tracing::Dispatch { + let writer = self.clone(); + tracing::Dispatch::new( + tracing_subscriber::fmt() + .json() + .without_time() + .with_ansi(false) + .with_writer(writer) + .finish(), + ) + } + + fn events(&self) -> Vec { + let bytes = self.0.lock().expect("captured log buffer").clone(); + String::from_utf8(bytes) + .expect("log lines are UTF-8") + .lines() + .map(|line| serde_json::from_str(line).expect("JSON log line")) + .collect() + } +} + +/// The counter, read the way an operator reads it: from the metrics listener. +async fn refusal_counts() -> BTreeMap { + let response = metrics_app(Arc::new(Metrics::without_pool_for_test())) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .expect("scrape request"), + ) + .await + .expect("metrics respond"); + let bytes = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("metrics body"); + let text = String::from_utf8(bytes.to_vec()).expect("metrics are UTF-8"); + let mut counts = BTreeMap::new(); + for line in text.lines() { + if let Some(rest) = line.strip_prefix("breg_request_refusals_total{check=\"") { + let (label, value) = rest.split_once("\"} ").expect("sample line"); + counts.insert(label.to_owned(), value.parse().expect("counter value")); + } + } + counts +} + +struct Observed { + name: &'static str, + expected_check: &'static str, + answer: Value, + counted: BTreeMap, + refusal_lines: Vec, + log_text: String, +} + +async fn observe( + name: &'static str, + expected_check: &'static str, + app: &axum::Router, + request: Request, +) -> Observed { + let captured = CapturedLogs::default(); + let before = refusal_counts().await; + let response = app + .clone() + .oneshot(request) + .with_subscriber(captured.subscriber()) + .await + .expect("router responds"); + let after = refusal_counts().await; + let status = response.status().as_u16(); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("ASCII header").to_owned()) + }; + let content_type = header("content-type"); + let cache_control = header("cache-control"); + let www_authenticate = header("www-authenticate"); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("response body"); + let mut body: Value = serde_json::from_slice(&bytes).expect("problem body is JSON"); + assert!( + body.as_object_mut() + .expect("problem body is an object") + .remove("traceId") + .is_some_and(|trace| trace.as_str().is_some_and(|id| id.len() == 32)), + "{name}: the problem carries the request trace id" + ); + let counted = after + .iter() + .filter_map(|(label, value)| { + let delta = value - before.get(label).copied().unwrap_or(0); + (delta > 0).then(|| (label.clone(), delta)) + }) + .collect(); + let events = captured.events(); + let log_text = events.iter().map(Value::to_string).collect::(); + let refusal_lines = events + .into_iter() + .filter(|event| event["fields"]["message"] == "request refused") + .collect(); + Observed { + name, + expected_check, + answer: json!({ + "status": status, + "contentType": content_type, + "cacheControl": cache_control, + "wwwAuthenticate": www_authenticate, + "body": body, + }), + counted, + refusal_lines, + log_text, + } +} + +#[tokio::test] +async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wire() { + let record = format!("/v1/records/cases/{RECORD_ID}"); + let mut observed = Vec::new(); + + let plain = Harness::plain().await; + let valid = plain.idp.mint_token(valid_claims()); + let mut tampered = valid.clone(); + tampered.pop(); + tampered.push(if valid.ends_with('A') { 'B' } else { 'A' }); + let now = unix_now(); + let mut wrong_audience = valid_claims(); + wrong_audience["aud"] = json!("urn:example:another-resource"); + let mut expired = valid_claims(); + expired["iat"] = json!(now - 7200); + expired["nbf"] = json!(now - 7200); + expired["exp"] = json!(now - 3600); + let mut wrong_issuer = valid_claims(); + wrong_issuer["iss"] = json!("https://issuer-canary.example.test"); + let mut no_actor_kind = valid_claims(); + no_actor_kind + .as_object_mut() + .expect("claims are an object") + .remove("registry_actor_kind"); + let mut object_principal = valid_claims(); + object_principal["registry_principal"] = json!({"value": PRINCIPAL}); + let bearer = |token: &str| format!("Bearer {token}"); + + for (name, check, request) in [ + ( + "no-authorization-header", + "credential-missing", + read_request(&record, &[]), + ), + ( + "basic-scheme", + "credential-missing", + read_request(&record, &["Basic canary-basic-secret"]), + ), + ( + "repeated-authorization-header", + "credential-malformed", + read_request( + &record, + &["Bearer canary-one.two.three", "Bearer canary-four.five.six"], + ), + ), + ( + "double-space-separator", + "credential-malformed", + read_request(&record, &["Bearer canary-double-space"]), + ), + ( + "token-not-compact", + "credential-malformed", + read_request(&record, &["Bearer canary-not-compact"]), + ), + ( + "tampered-signature", + "token-signature", + read_request(&record, &[&bearer(&tampered)]), + ), + ( + "wrong-audience", + "token-audience", + read_request(&record, &[&bearer(&plain.token(wrong_audience))]), + ), + ( + "expired-token", + "token-time", + read_request(&record, &[&bearer(&plain.token(expired))]), + ), + ( + "unknown-key-id", + "token-key", + read_request( + &record, + &[&bearer(&plain.signed(valid_claims(), "kid-canary-unknown"))], + ), + ), + ( + "wrong-issuer", + "token-issuer", + read_request(&record, &[&bearer(&plain.token(wrong_issuer))]), + ), + ( + "missing-actor-kind", + "actor-kind", + read_request(&record, &[&bearer(&plain.token(no_actor_kind))]), + ), + ( + "principal-claim-is-an-object", + "token-claims", + read_request(&record, &[&bearer(&plain.token(object_principal))]), + ), + ] { + observed.push(observe(name, check, &plain.app, request).await); + } + + // The low-level router has no bearer layer, so a route that reads claims + // finds none. + let unauthenticated = router(Arc::new(service(compiled(PROJECT)))); + observed.push( + observe( + "extractor-without-authentication-context", + "credential-missing", + &unauthenticated, + read_request("/v1/registry", &[]), + ) + .await, + ); + + let contextual = Harness::contextual().await; + let agent_path = format!("{record}?accessProfile=standing-agent"); + let grant_path = format!("{record}?accessProfile=delegated-agent"); + let untrusted_actor = contextual.token(standing_agent_claims( + json!({"sub": "00000000-0000-4000-8000-0000000000ff", "iss": contextual.idp.issuer()}), + )); + let mut actor_without_client = + standing_agent_claims(json!({"sub": ACTOR_ID, "iss": contextual.idp.issuer()})); + actor_without_client + .as_object_mut() + .expect("claims are an object") + .remove("azp"); + let mut long_grant = delegated_grant_claims(now); + long_grant["iat"] = json!(now); + long_grant["exp"] = json!(now + 901); + let mut partial_grant = delegated_grant_claims(now); + partial_grant["iat"] = json!(now); + partial_grant["exp"] = json!(now + 600); + partial_grant["registry_grant_bounds"] = json!("not-an-object"); + for (name, check, request) in [ + ( + "actor-is-not-the-trusted-actor", + "delegation", + read_request(&agent_path, &[&bearer(&untrusted_actor)]), + ), + ( + "actor-without-a-matched-client", + "token-client", + read_request( + &agent_path, + &[&bearer(&contextual.token(actor_without_client))], + ), + ), + ( + "task-grant-token-issued-for-too-long", + "task-grant-lifetime", + read_request(&grant_path, &[&bearer(&contextual.token(long_grant))]), + ), + ( + "task-grant-claims-malformed", + "task-grant-claims", + read_request(&grant_path, &[&bearer(&contextual.token(partial_grant))]), + ), + ] { + observed.push(observe(name, check, &contextual.app, request).await); + } + + let completions = completion_app(); + for (name, check, request) in [ + ( + "review-completion-without-authorization", + "credential-missing", + completion_request(None, Some("registry-a")), + ), + ( + "review-completion-with-two-authorization-headers", + "credential-malformed", + { + let mut request = + completion_request(Some("Bearer completion-secret"), Some("registry-a")); + request.headers_mut().append( + AUTHORIZATION, + HeaderValue::from_static("Bearer canary-second-header"), + ); + request + }, + ), + ( + "review-completion-without-recipient", + "credential-missing", + completion_request(Some("Bearer completion-secret"), None), + ), + ( + "review-completion-wrong-credential", + "shared-secret", + completion_request(Some("Bearer invalid-credential-canary"), Some("registry-a")), + ), + ( + "review-completion-wrong-recipient", + "shared-secret", + completion_request( + Some("Bearer completion-secret"), + Some("wrong-recipient-canary"), + ), + ), + ] { + observed.push(observe(name, check, &completions, request).await); + } + + // The answers, frozen. + let answers: BTreeMap<&str, &Value> = observed + .iter() + .map(|case| (case.name, &case.answer)) + .collect(); + let golden_path = format!("{}/{GOLDEN}", env!("CARGO_MANIFEST_DIR")); + if std::env::var_os("REGISTRY_BREG_WRITE_GOLDEN").is_some() { + let mut text = serde_json::to_string_pretty(&answers).expect("answers serialize"); + text.push('\n'); + std::fs::write(&golden_path, text).expect("golden file is writable"); + } else { + let frozen: Value = serde_json::from_str( + &std::fs::read_to_string(&golden_path).expect("golden file exists"), + ) + .expect("golden file is JSON"); + assert_eq!( + serde_json::to_value(&answers).expect("answers serialize"), + frozen, + "an authentication refusal changed on the wire" + ); + } + + // The recording: one count, one line, no caller value. + let mut used: BTreeSet<&str> = BTreeSet::new(); + for case in &observed { + used.insert(case.expected_check); + assert_eq!( + case.counted, + BTreeMap::from([(case.expected_check.to_owned(), 1)]), + "{}: the refusal counts once under its check", + case.name + ); + assert_eq!( + case.refusal_lines.len(), + 1, + "{}: one refusal line", + case.name + ); + let line = &case.refusal_lines[0]; + assert_eq!(line["level"], "INFO", "{}", case.name); + let fields = line["fields"].as_object().expect("line fields"); + assert_eq!(fields["decision"], "refused", "{}", case.name); + assert_eq!(fields["failed_check"], case.expected_check, "{}", case.name); + assert_eq!(fields["suppressed"], 0, "{}", case.name); + assert!( + fields["trace_id"] + .as_str() + .is_some_and(|id| id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())), + "{}: the line carries the request trace id", + case.name + ); + let keys: BTreeSet<&str> = fields.keys().map(String::as_str).collect(); + assert_eq!( + keys, + BTreeSet::from([ + "decision", + "failed_check", + "message", + "suppressed", + "trace_id" + ]), + "{}: the line carries only the fixed fields", + case.name + ); + for canary in [ + "canary", + PRINCIPAL, + "agent-client", + "completion-secret", + "registry-a", + "Bearer", + ] { + assert!( + !case.log_text.contains(canary), + "{}: the log exposed {canary}", + case.name + ); + } + } + assert!( + used.len() >= 14, + "the cases cover every authentication check" + ); +} diff --git a/crates/registry-breg/tests/golden/authentication_refusals.json b/crates/registry-breg/tests/golden/authentication_refusals.json new file mode 100644 index 0000000000..72591b6a59 --- /dev/null +++ b/crates/registry-breg/tests/golden/authentication_refusals.json @@ -0,0 +1,288 @@ +{ + "actor-is-not-the-trusted-actor": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "actor-without-a-matched-client": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "basic-scheme": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "double-space-separator": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "expired-token": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "extractor-without-authentication-context": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "missing-actor-kind": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "no-authorization-header": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "principal-claim-is-an-object": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "repeated-authorization-header": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "review-completion-with-two-authorization-headers": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "review-completion-without-authorization": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "review-completion-without-recipient": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "review-completion-wrong-credential": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "review-completion-wrong-recipient": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "tampered-signature": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-claims-malformed": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-token-issued-for-too-long": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "token-not-compact": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "unknown-key-id": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "wrong-audience": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + }, + "wrong-issuer": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 401, + "wwwAuthenticate": null + } +} diff --git a/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt b/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt index 498b49e2f3..b5ffbf23b0 100644 --- a/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt +++ b/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt @@ -137,3 +137,50 @@ breg_metrics_sample_failures_total{sample="ingestion-run"} 0 # HELP breg_active_package_info The package this process verified at startup, by digest. # TYPE breg_active_package_info gauge breg_active_package_info{package_digest="sha256:abababababababababababababababababababababababababababababababab"} 1 +# HELP breg_request_refusals_total Requests refused, by the check that failed. +# TYPE breg_request_refusals_total counter +breg_request_refusals_total{check="credential-missing"} 0 +breg_request_refusals_total{check="credential-malformed"} 0 +breg_request_refusals_total{check="token-algorithm"} 0 +breg_request_refusals_total{check="token-type"} 0 +breg_request_refusals_total{check="token-key"} 0 +breg_request_refusals_total{check="token-signature"} 0 +breg_request_refusals_total{check="token-issuer"} 0 +breg_request_refusals_total{check="token-audience"} 0 +breg_request_refusals_total{check="token-time"} 0 +breg_request_refusals_total{check="token-client"} 0 +breg_request_refusals_total{check="token-assertion-issuer"} 0 +breg_request_refusals_total{check="token-claims"} 0 +breg_request_refusals_total{check="actor-kind"} 0 +breg_request_refusals_total{check="delegation"} 0 +breg_request_refusals_total{check="sender-constraint"} 0 +breg_request_refusals_total{check="key-source-unavailable"} 0 +breg_request_refusals_total{check="shared-secret"} 0 +breg_request_refusals_total{check="one-time-credential"} 0 +breg_request_refusals_total{check="delivery-signature"} 0 +breg_request_refusals_total{check="delivery-freshness"} 0 +breg_request_refusals_total{check="delivery-binding"} 0 +breg_request_refusals_total{check="host-origin"} 0 +breg_request_refusals_total{check="scope"} 0 +breg_request_refusals_total{check="access-profile"} 0 +breg_request_refusals_total{check="requester-client"} 0 +breg_request_refusals_total{check="purpose"} 0 +breg_request_refusals_total{check="operation"} 0 +breg_request_refusals_total{check="disclosure"} 0 +breg_request_refusals_total{check="subject-selector"} 0 +breg_request_refusals_total{check="revision-pin"} 0 +breg_request_refusals_total{check="acquisition-channel"} 0 +breg_request_refusals_total{check="source-authority"} 0 +breg_request_refusals_total{check="separation-of-duties"} 0 +breg_request_refusals_total{check="task-grant-missing"} 0 +breg_request_refusals_total{check="task-grant-claims"} 0 +breg_request_refusals_total{check="task-grant-expired"} 0 +breg_request_refusals_total{check="task-grant-binding"} 0 +breg_request_refusals_total{check="task-grant-scope"} 0 +breg_request_refusals_total{check="task-grant-lifetime"} 0 +breg_request_refusals_total{check="task-grant-status"} 0 +breg_request_refusals_total{check="row-boundary"} 0 +breg_request_refusals_total{check="ownership"} 0 +breg_request_refusals_total{check="visibility"} 0 +breg_request_refusals_total{check="action-guard"} 0 +breg_request_refusals_total{check="rate-limit"} 0 diff --git a/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt b/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt index 50e7ca19df..f469ffcaa8 100644 --- a/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt +++ b/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt @@ -108,3 +108,50 @@ breg_metrics_sample_failures_total{sample="ingestion-run"} 0 # HELP breg_active_package_info The package this process verified at startup, by digest. # TYPE breg_active_package_info gauge breg_active_package_info{package_digest="sha256:abababababababababababababababababababababababababababababababab"} 1 +# HELP breg_request_refusals_total Requests refused, by the check that failed. +# TYPE breg_request_refusals_total counter +breg_request_refusals_total{check="credential-missing"} 0 +breg_request_refusals_total{check="credential-malformed"} 0 +breg_request_refusals_total{check="token-algorithm"} 0 +breg_request_refusals_total{check="token-type"} 0 +breg_request_refusals_total{check="token-key"} 0 +breg_request_refusals_total{check="token-signature"} 0 +breg_request_refusals_total{check="token-issuer"} 0 +breg_request_refusals_total{check="token-audience"} 0 +breg_request_refusals_total{check="token-time"} 0 +breg_request_refusals_total{check="token-client"} 0 +breg_request_refusals_total{check="token-assertion-issuer"} 0 +breg_request_refusals_total{check="token-claims"} 0 +breg_request_refusals_total{check="actor-kind"} 0 +breg_request_refusals_total{check="delegation"} 0 +breg_request_refusals_total{check="sender-constraint"} 0 +breg_request_refusals_total{check="key-source-unavailable"} 0 +breg_request_refusals_total{check="shared-secret"} 0 +breg_request_refusals_total{check="one-time-credential"} 0 +breg_request_refusals_total{check="delivery-signature"} 0 +breg_request_refusals_total{check="delivery-freshness"} 0 +breg_request_refusals_total{check="delivery-binding"} 0 +breg_request_refusals_total{check="host-origin"} 0 +breg_request_refusals_total{check="scope"} 0 +breg_request_refusals_total{check="access-profile"} 0 +breg_request_refusals_total{check="requester-client"} 0 +breg_request_refusals_total{check="purpose"} 0 +breg_request_refusals_total{check="operation"} 0 +breg_request_refusals_total{check="disclosure"} 0 +breg_request_refusals_total{check="subject-selector"} 0 +breg_request_refusals_total{check="revision-pin"} 0 +breg_request_refusals_total{check="acquisition-channel"} 0 +breg_request_refusals_total{check="source-authority"} 0 +breg_request_refusals_total{check="separation-of-duties"} 0 +breg_request_refusals_total{check="task-grant-missing"} 0 +breg_request_refusals_total{check="task-grant-claims"} 0 +breg_request_refusals_total{check="task-grant-expired"} 0 +breg_request_refusals_total{check="task-grant-binding"} 0 +breg_request_refusals_total{check="task-grant-scope"} 0 +breg_request_refusals_total{check="task-grant-lifetime"} 0 +breg_request_refusals_total{check="task-grant-status"} 0 +breg_request_refusals_total{check="row-boundary"} 0 +breg_request_refusals_total{check="ownership"} 0 +breg_request_refusals_total{check="visibility"} 0 +breg_request_refusals_total{check="action-guard"} 0 +breg_request_refusals_total{check="rate-limit"} 0 diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index dbbb383b92..563e270002 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -47,7 +47,7 @@ use zeroize::Zeroizing; const AUDIENCE: &str = "urn:example:breg"; #[tokio::test] -async fn compact_token_admission_logs_one_value_free_header_diagnostic() { +async fn compact_token_admission_refuses_malformed_credentials_and_writes_no_line_itself() { use registry_platform_testing::{malformed_access_token_fixtures, CapturedDiagnosticLogs}; use tracing::instrument::WithSubscriber; let captured = CapturedDiagnosticLogs::default(); @@ -71,7 +71,9 @@ async fn compact_token_admission_logs_one_value_free_header_diagnostic() { )); } } - captured.assert_one_value_free_header_diagnostic(&tokens); + // The counted refusal and its one bounded line belong to the request + // boundary, which `tests/authentication_refusals.rs` drives. + assert_eq!(captured.text(), "", "admission writes no line of its own"); } #[tokio::test] @@ -1976,13 +1978,24 @@ async fn malformed_or_duplicate_bearer_is_refused_before_record_io() { assert_eq!(body_json(response).await["code"], "authentication.refused"); assert_eq!(harness.records.calls.load(Ordering::SeqCst), before); let rendered = captured.text(); - let diagnostics = rendered + // The process-wide recorder admits a bounded number of lines per + // check, and other tests in this process spend that budget, so the + // exact line count is asserted in `tests/authentication_refusals.rs`. + let refusals = rendered .lines() - .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) - .filter(|event| event["fields"]["message"] == "BReg authentication refused") + .map(|line| serde_json::from_str::(line).expect("JSON log line")) + .filter(|event| event["fields"]["message"] == "request refused") .collect::>(); - assert_eq!(diagnostics.len(), 1); - assert_eq!(diagnostics[0]["fields"]["stage"], "header"); + assert!(refusals.len() <= 1); + for refusal in &refusals { + assert!( + matches!( + refusal["fields"]["failed_check"].as_str(), + Some("credential-missing" | "credential-malformed") + ), + "{refusal}" + ); + } assert!(!rendered.contains("canary")); assert!(!rendered.contains("Bearer")); } diff --git a/crates/registry-breg/tests/token_characterisation.rs b/crates/registry-breg/tests/token_characterisation.rs index b8bf3a809b..b7e32fe313 100644 --- a/crates/registry-breg/tests/token_characterisation.rs +++ b/crates/registry-breg/tests/token_characterisation.rs @@ -6,7 +6,9 @@ //! a runtime file parsed by `parse_runtime_config`, as at startup. The key set //! is the signer's static public key set. A token that authenticates is sent //! through the authenticated router to a compiled access profile, so a profile -//! refusal is observed where a request meets it. +//! refusal is observed where a request meets it. A token the verifier refuses +//! is sent through the router too, and the check it failed is read from +//! `breg_request_refusals_total`, the counter an operator reads. #![cfg(feature = "runtime")] @@ -22,16 +24,16 @@ use registry_breg::api::{ }; use registry_breg::auth::{AuthenticationConfigError, AuthenticationError, RegistryAuthenticator}; use registry_breg::cursor::CursorCodec; +use registry_breg::metrics::{metrics_app, Metrics}; use registry_breg::runtime_config::parse_runtime_config; use registry_breg::{compile_project, parse_project_yaml, CompileProfile}; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; use registry_platform_testing::{ - Against, CapturedDiagnosticLogs, ClaimValue, Configuration, FixtureCase, Outcome, Stage, - TokenCorpus, TokenFixture, TokenSigner, + Against, ClaimValue, Configuration, FixtureCase, Outcome, Stage, TokenCorpus, TokenFixture, + TokenSigner, }; use serde_json::{json, Value}; use tower::ServiceExt as _; -use tracing::instrument::WithSubscriber; use zeroize::Zeroizing; const ISSUER: &str = "https://issuer.example.test"; @@ -260,18 +262,16 @@ async fn observe(case: FixtureCase) -> Outcome { Err(error) => panic!("the authentication block is invalid for the project: {error}"), }; - let logs = CapturedDiagnosticLogs::default(); let token = case.token.expose(); - let claims = authenticator - .authenticate(token) - .with_subscriber(logs.subscriber()) - .await; + let claims = authenticator.authenticate(token).await; let claims = match claims { Ok(claims) => claims, Err( AuthenticationError::VerificationRefused | AuthenticationError::MalformedCredential, ) => { - return logged_stage(&logs).map_or(Outcome::Unknown, Outcome::Refused); + return refused_stage(®istry, &authenticator, token) + .await + .map_or(Outcome::Unknown, Outcome::Refused); } Err(AuthenticationError::MissingActorKind | AuthenticationError::InvalidClaims) => { return Outcome::Refused(Stage::Claims); @@ -291,30 +291,62 @@ async fn observe(case: FixtureCase) -> Outcome { } } -/// The stage of the one value-free diagnostic a refusal logged, when there is -/// exactly one. -fn logged_stage(logs: &CapturedDiagnosticLogs) -> Option { - let text = logs.text(); - let stages: Vec = text - .lines() - .filter_map(|line| serde_json::from_str::(line).ok()) - .filter_map(|line| line["fields"]["stage"].as_str().map(str::to_owned)) +/// The stage a refused token failed at: the check the request boundary counted +/// when the token was sent through the router, mapped onto the corpus's +/// stages. `None` when the boundary counted nothing or something else. +async fn refused_stage( + registry: &Arc, + authenticator: &Arc, + token: &str, +) -> Option { + let before = refusal_counts().await; + request_record(registry, authenticator, token, "reader").await; + let after = refusal_counts().await; + let counted: Vec<&str> = after + .iter() + .filter(|(check, count)| **count > before.get(*check).copied().unwrap_or(0)) + .map(|(check, _)| check.as_str()) .collect(); - match stages.as_slice() { - [stage] => Some( - format!("refused/{stage}") - .parse::() - .ok() - .and_then(|outcome| match outcome { - Outcome::Refused(stage) => Some(stage), - _ => None, - }) - .expect("the logged stage is a known stage"), - ), + match counted.as_slice() { + ["credential-malformed"] => Some(Stage::Header), + ["token-algorithm"] => Some(Stage::Algorithm), + ["token-type"] => Some(Stage::TokenType), + ["token-key"] => Some(Stage::Key), + ["token-signature"] => Some(Stage::Signature), + ["token-issuer"] => Some(Stage::Issuer), + ["token-audience"] => Some(Stage::Audience), + ["token-time"] => Some(Stage::Time), + ["token-client" | "token-assertion-issuer"] => Some(Stage::Client), + ["key-source-unavailable"] => Some(Stage::Unavailable), _ => None, } } +/// The refusal counter as the metrics listener serves it. +async fn refusal_counts() -> std::collections::BTreeMap { + let response = metrics_app(Arc::new(Metrics::without_pool_for_test())) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .expect("scrape request"), + ) + .await + .expect("the metrics listener responds"); + let bytes = axum::body::to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("metrics body"); + String::from_utf8(bytes.to_vec()) + .expect("metrics are UTF-8") + .lines() + .filter_map(|line| line.strip_prefix("breg_request_refusals_total{check=\"")) + .map(|rest| { + let (check, count) = rest.split_once("\"} ").expect("sample line"); + (check.to_owned(), count.parse().expect("counter value")) + }) + .collect() +} + /// The actor kind in a `VerifiedRequestClaims` debug rendering, which prints /// the kind and redacts every value. fn actor_kind_of(rendered: &str) -> String { diff --git a/crates/registry-casework/Cargo.toml b/crates/registry-casework/Cargo.toml index b0e7cf2fff..36d40f4e34 100644 --- a/crates/registry-casework/Cargo.toml +++ b/crates/registry-casework/Cargo.toml @@ -44,11 +44,11 @@ registry-casework-breg.workspace = true registry-platform-canonical-json.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-dispatch = { workspace = true, features = ["postgres"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-oidc.workspace = true registry-platform-httputil.workspace = true registry-platform-metrics.workspace = true diff --git a/crates/registry-casework/src/auth.rs b/crates/registry-casework/src/auth.rs index 8eb4aef4ca..76f44f7b14 100644 --- a/crates/registry-casework/src/auth.rs +++ b/crates/registry-casework/src/auth.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use registry_casework_core::{ AccessProfile, ActorContext, CaseworkActsAs, CaseworkProject, IssuerPrincipal, }; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; use registry_platform_oidc::{JwksFetcher, TokenVerifier, TokenVerifierConfig}; use serde_json::Value; use thiserror::Error; @@ -28,14 +28,6 @@ pub struct CaseworkAuthenticator { } impl CaseworkAuthenticator { - pub(crate) fn record_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Header, - "Casework authentication refused" - ); - } - /// Constructs an authenticator from a project already validated by /// [`CaseworkProject::load`] or [`CaseworkProject::check`]. #[must_use] @@ -103,50 +95,61 @@ impl CaseworkAuthenticator { source: &str, provider: &str, ) -> Result<(), AuthenticationError> { - validate_compact_access_token(source).map_err(|_| AuthenticationError::Refused)?; + validate_compact_access_token(source) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; let source_verifier = self .source_verifiers .get(provider) - .ok_or(AuthenticationError::Refused)?; + .ok_or(AuthenticationError::Refused(FailedCheck::AccessProfile))?; let primary = self .verifier .verify(casework) .await - .map_err(|_| AuthenticationError::Refused)?; + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; let secondary = source_verifier .verify(source) .await - .map_err(|_| AuthenticationError::Refused)?; + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; for verified in [&primary, &secondary] { if !matches!( verified.claims.aud, Some(registry_platform_oidc::Audience::One(_)) - ) || verified.claims.sub.as_deref().is_none_or(str::is_empty) - || verified - .claims - .extra - .get("registry_actor_kind") - .and_then(Value::as_str) - != Some("human") + ) { + return Err(AuthenticationError::Refused(FailedCheck::TokenAudience)); + } + if verified.claims.sub.as_deref().is_none_or(str::is_empty) { + return Err(AuthenticationError::Refused(FailedCheck::TokenClaims)); + } + if verified + .claims + .extra + .get("registry_actor_kind") + .and_then(Value::as_str) + != Some("human") || verified .claims .extra .get(&self.human_identity.claim) .and_then(Value::as_str) != Some(self.human_identity.value.as_str()) - || verified.claims.extra.contains_key("act") - || verified - .claims - .extra - .keys() - .any(|key| key.starts_with("registry_grant_")) { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::ActorKind)); + } + if verified.claims.extra.contains_key("act") { + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); + } + if verified + .claims + .extra + .keys() + .any(|key| key.starts_with("registry_grant_")) + { + return Err(AuthenticationError::Refused(FailedCheck::TaskGrantClaims)); } } if primary.claims.iss != secondary.claims.iss || primary.claims.sub != secondary.claims.sub { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::TokenClaims)); } Ok(()) } @@ -166,38 +169,45 @@ impl CaseworkAuthenticator { scope: &str, kind: registry_platform_oidc::ActorKind, ) -> Result { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Casework authentication refused" - ); - AuthenticationError::Refused - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; if !matches!( verified.claims.aud.as_ref(), Some(registry_platform_oidc::Audience::One(_)) ) && !matches!(verified.claims.aud.as_ref(), Some(registry_platform_oidc::Audience::Many(values)) if values.len() == 1) - || verified.claims.extra.contains_key("act") - || !verified.scopes.iter().any(|value| value == scope) - || verified.matched_client_id().ok().flatten().is_none() - || registry_platform_oidc::actor_kind( - &verified.claims, - ®istry_platform_oidc::ClaimNames::default(), - ) - .ok() - != Some(kind) - || verified - .claims - .extra - .keys() - .any(|key| key.starts_with("registry_grant_")) { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::TokenAudience)); + } + if verified.claims.extra.contains_key("act") { + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); + } + if !verified.scopes.iter().any(|value| value == scope) { + return Err(AuthenticationError::Refused(FailedCheck::Scope)); + } + if verified.matched_client_id().ok().flatten().is_none() { + return Err(AuthenticationError::Refused(FailedCheck::TokenClient)); + } + if registry_platform_oidc::actor_kind( + &verified.claims, + ®istry_platform_oidc::ClaimNames::default(), + ) + .ok() + != Some(kind) + { + return Err(AuthenticationError::Refused(FailedCheck::ActorKind)); + } + if verified + .claims + .extra + .keys() + .any(|key| key.starts_with("registry_grant_")) + { + return Err(AuthenticationError::Refused(FailedCheck::TaskGrantClaims)); } Ok(verified) } @@ -207,46 +217,49 @@ impl CaseworkAuthenticator { token: &str, selected_profile: &str, ) -> Result { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Casework authentication refused" - ); - AuthenticationError::Refused - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; let matched_client = verified .matched_client_id() - .map_err(|_| AuthenticationError::Refused)?; - if self.delegated_staff_readers.values().any(|reader| { - matched_client == Some(reader.client.as_str()) - && (verified.claims.extra.contains_key("act") - || verified - .scopes - .iter() - .any(|scope| scope == &reader.required_scope)) - }) { - return Err(AuthenticationError::Refused); + .map_err(|_| AuthenticationError::Refused(FailedCheck::TokenClient))?; + for reader in self.delegated_staff_readers.values() { + if matched_client != Some(reader.client.as_str()) { + continue; + } + if verified.claims.extra.contains_key("act") { + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); + } + if verified + .scopes + .iter() + .any(|scope| scope == &reader.required_scope) + { + return Err(AuthenticationError::Refused(FailedCheck::Scope)); + } } - let profile = self.profiles.get(selected_profile).ok_or_else(|| { - self.profile_diagnostic(); - AuthenticationError::Profile - })?; + let profile = self + .profiles + .get(selected_profile) + .ok_or(AuthenticationError::Profile(FailedCheck::AccessProfile))?; let requires_person = profile.acts_as != CaseworkActsAs::Requester || self.initiator_profiles.contains(&profile.id); - if requires_person - && (verified.claims.extra.contains_key("act") - || verified - .claims - .extra - .keys() - .any(|key| key.starts_with("registry_grant_"))) - { - return Err(AuthenticationError::Refused); + if requires_person { + if verified.claims.extra.contains_key("act") { + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); + } + if verified + .claims + .extra + .keys() + .any(|key| key.starts_with("registry_grant_")) + { + return Err(AuthenticationError::Refused(FailedCheck::TaskGrantClaims)); + } } let actual_scopes: BTreeSet<_> = verified.scopes.iter().map(String::as_str).collect(); if !profile @@ -254,13 +267,7 @@ impl CaseworkAuthenticator { .iter() .all(|scope| actual_scopes.contains(scope.as_str())) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Scope, - "Casework authentication profile refused", - remedy = "check authentication.oidc.scopeClaim and accessProfiles requiredScopes" - ); - return Err(AuthenticationError::Profile); + return Err(AuthenticationError::Profile(FailedCheck::Scope)); } if requires_person { let human_identity = verified @@ -269,13 +276,9 @@ impl CaseworkAuthenticator { .get(&self.human_identity.claim) .and_then(Value::as_str) .filter(|value| !value.is_empty()) - .ok_or_else(|| { - self.profile_diagnostic(); - AuthenticationError::NotHuman - })?; + .ok_or(AuthenticationError::NotHuman(FailedCheck::ActorKind))?; if human_identity != self.human_identity.value { - self.profile_diagnostic(); - return Err(AuthenticationError::NotHuman); + return Err(AuthenticationError::NotHuman(FailedCheck::ActorKind)); } } let principal = if profile.principal_claim == "sub" { @@ -288,12 +291,12 @@ impl CaseworkAuthenticator { .and_then(Value::as_str) } .filter(|value| !value.is_empty()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; let issuer = verified .claims .iss .filter(|issuer| !issuer.is_empty()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; Ok(ActorContext { principal: IssuerPrincipal { issuer, @@ -303,15 +306,6 @@ impl CaseworkAuthenticator { role: profile.acts_as, }) } - - fn profile_diagnostic(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Profile, - "Casework authentication profile refused", - remedy = "check selected accessProfiles and authentication.oidc.humanIdentity profile category" - ); - } } impl std::fmt::Debug for CaseworkAuthenticator { @@ -329,16 +323,32 @@ impl std::fmt::Debug for CaseworkAuthenticator { } } +/// Why authentication refused a request. Each variant names the check that +/// failed, which goes to the operator's counter and log and never to the +/// caller. #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] - Refused, + Refused(FailedCheck), #[error("the selected Casework profile was refused")] - Profile, + Profile(FailedCheck), #[error("the verified identity is not a human session")] - NotHuman, + NotHuman(FailedCheck), #[error("the verified identity claims are invalid")] - Claims, + Claims(FailedCheck), +} + +impl AuthenticationError { + /// The check the request failed. + #[must_use] + pub const fn failed_check(self) -> FailedCheck { + match self { + Self::Refused(check) + | Self::Profile(check) + | Self::NotHuman(check) + | Self::Claims(check) => check, + } + } } #[cfg(test)] @@ -359,7 +369,7 @@ mod tests { const SECRET: &[u8] = b"01234567890123456789012345678901"; #[tokio::test] - async fn equivalent_profile_refusals_share_one_bounded_value_free_diagnostic() { + async fn equivalent_profile_refusals_name_their_check_and_write_no_log_line() { use tracing::instrument::WithSubscriber; #[derive(Clone)] struct Writer(Arc>>); @@ -405,7 +415,7 @@ mod tests { .with_subscriber(subscriber.clone()) .await .unwrap_err(), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::AccessProfile) ); for kind in [None, Some(""), Some("canary-private-actor")] { let mut claims = base.clone(); @@ -418,15 +428,13 @@ mod tests { .with_subscriber(subscriber.clone()) .await .unwrap_err(), - AuthenticationError::NotHuman + AuthenticationError::NotHuman(FailedCheck::ActorKind) ); } + // Recording belongs to the HTTP boundary, which counts and logs each + // refusal once by its check. The authenticator writes nothing. let rendered = String::from_utf8(output.lock().unwrap().clone()).unwrap(); - assert_eq!(rendered.lines().count(), 1); - assert!(rendered.contains("profile")); - assert!(rendered.contains("authentication.oidc.humanIdentity")); - assert!(!rendered.contains("canary-private")); - assert!(!rendered.contains(&credential)); + assert!(rendered.is_empty(), "{rendered}"); } fn project() -> CaseworkProject { @@ -636,6 +644,75 @@ mod tests { .is_err()); } + #[tokio::test] + async fn separate_human_source_refusals_name_the_check_that_failed() { + let auth = authenticator(BTreeMap::new()).with_human_source_audiences(BTreeMap::from([( + "registry".into(), + "urn:breg:source".into(), + )])); + let primary_claims = json!({"sub":"same-human", "client_id":CLIENT, "registry_actor_kind":"human", "human_session":"yes"}); + let source_claims = json!({"aud":"urn:breg:source", "sub":"same-human", "client_id":"source-client", "registry_actor_kind":"human", "human_session":"yes"}); + let primary = token(primary_claims.clone()); + let auth = { + let mut auth = auth; + auth.human_identity = HumanIdentityConfig { + claim: "human_session".into(), + value: "yes".into(), + }; + auth + }; + auth.verify_human_source_pair(&primary, &token(source_claims.clone()), "registry") + .await + .expect("the pair is the same human"); + assert_eq!( + auth.verify_human_source_pair(&primary, &token(source_claims.clone()), "unknown") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::AccessProfile) + ); + assert_eq!( + auth.verify_human_source_pair(&primary, "not-a-token", "registry") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); + for (patch, expected) in [ + (json!({"sub":"another-human"}), FailedCheck::TokenClaims), + (json!({"aud":AUDIENCE}), FailedCheck::TokenAudience), + ( + json!({"aud":["urn:breg:source"]}), + FailedCheck::TokenAudience, + ), + ( + json!({"iss":"https://other.example.test"}), + FailedCheck::TokenIssuer, + ), + ( + json!({"registry_actor_kind":"service"}), + FailedCheck::ActorKind, + ), + (json!({"human_session":"no"}), FailedCheck::ActorKind), + (json!({"act":{"sub":"agent"}}), FailedCheck::Delegation), + ( + json!({"registry_grant_id":"grant"}), + FailedCheck::TaskGrantClaims, + ), + ] { + let mut claims = source_claims.clone(); + claims + .as_object_mut() + .unwrap() + .extend(patch.as_object().unwrap().clone()); + assert_eq!( + auth.verify_human_source_pair(&primary, &token(claims), "registry") + .await + .unwrap_err(), + AuthenticationError::Refused(expected), + "{patch}" + ); + } + } + #[tokio::test] async fn separate_human_source_refusals_never_log_credentials_or_subjects() { use tracing::instrument::WithSubscriber; @@ -730,7 +807,10 @@ mod tests { let result = authenticator .authenticate_task_client(&disallowed, "task-grant", ActorKind::Service) .await; - assert!(matches!(result, Err(AuthenticationError::Refused))); + assert_eq!( + result.unwrap_err(), + AuthenticationError::Refused(FailedCheck::TokenAssertionIssuer) + ); let allowed = token(json!({ "azp": CLIENT, @@ -833,39 +913,46 @@ mod tests { .await .expect("the exact delegated reader is accepted"); assert_eq!(reader.principal_for_test().subject, "officer-7"); - assert!(matches!( - auth.authenticate(&credential, "staff").await, - Err(AuthenticationError::Refused) - )); - assert!(matches!( - auth.authenticate(&credential, "requester-overlap").await, - Err(AuthenticationError::Refused) - )); + assert_eq!( + auth.authenticate(&credential, "staff").await.unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); + assert_eq!( + auth.authenticate(&credential, "requester-overlap") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); let delegated_actor_without_reader_scope = delegated_token(json!({ "scope": "casework:staff" })); - assert!(matches!( + assert_eq!( auth.authenticate(&delegated_actor_without_reader_scope, "requester-overlap") - .await, - Err(AuthenticationError::Refused) - )); + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); let second_policy = delegated_token(json!({ "scope": "casework:staff casework:other-delegated-read" })); - assert!(matches!( - auth.authenticate(&second_policy, "requester-overlap").await, - Err(AuthenticationError::Refused) - )); + assert_eq!( + auth.authenticate(&second_policy, "requester-overlap") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); let stripped = token(json!({ "azp": CLIENT, "sub": "officer-7", "scope": "casework:staff casework:staff:delegated-read", "registry_actor_kind": "service" })); - assert!(matches!( - auth.authenticate(&stripped, "requester-overlap").await, - Err(AuthenticationError::Refused) - )); + assert_eq!( + auth.authenticate(&stripped, "requester-overlap") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Scope) + ); let credential = delegated_token(json!({"aud": [AUDIENCE]})); auth.authenticate_staff_read(&credential, "staff-mcp", Some("review-agent")) .await @@ -888,35 +975,35 @@ mod tests { for (claims, expected) in [ ( json!({"act":{"iss":ISSUER,"sub":"other"}}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::Delegation), ), ( json!({"act":{"iss":ISSUER,"sub":"registry-mcp","act":{"sub":"nested"}}}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::Delegation), ), ( json!({"scope":"casework:staff:delegated-read"}), - AuthenticationError::Profile, + AuthenticationError::Profile(FailedCheck::Scope), ), ( json!({"scope":"casework:staff"}), - AuthenticationError::Profile, + AuthenticationError::Profile(FailedCheck::Scope), ), ( json!({"scope":"casework:staff casework:staff casework:staff:delegated-read"}), - AuthenticationError::Profile, + AuthenticationError::Profile(FailedCheck::Scope), ), ( json!({"iat":now,"exp":now+301}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::TokenTime), ), ( json!({"registry_grant_id":"not-allowed"}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::TaskGrantClaims), ), ( json!({"aud":[AUDIENCE, AUDIENCE]}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::TokenAudience), ), ] { let credential = delegated_token(claims); @@ -928,11 +1015,12 @@ mod tests { ); } let credential = delegated_token(json!({})); - assert!(matches!( + assert_eq!( auth.authenticate_staff_read(&credential, "staff-mcp", Some("other-source")) - .await, - Err(AuthenticationError::Profile) - )); + .await + .unwrap_err(), + AuthenticationError::Profile(FailedCheck::AccessProfile) + ); } #[tokio::test] @@ -956,20 +1044,21 @@ mod tests { json!({"sub":"other-gateway"}), json!({"sub":"registry-mcp","act":{"sub":"prior-gateway"}}), ] { - assert!(matches!( + assert_eq!( auth.authenticate_staff_read( &delegated_token(json!({"act":act})), "staff-mcp", Some("review-agent"), ) - .await, - Err(AuthenticationError::Refused) - )); + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); } } #[tokio::test] - async fn delegated_staff_read_negative_cases_have_value_free_stage_diagnostics() { + async fn delegated_staff_read_negative_cases_name_their_check_and_write_no_log_line() { use registry_platform_testing::CapturedDiagnosticLogs; use tracing::instrument::WithSubscriber; @@ -979,7 +1068,6 @@ mod tests { policy: &'static str, source_profile: Option<&'static str>, expected_error: AuthenticationError, - expected_stage: &'static str, default_off: bool, } @@ -1008,8 +1096,7 @@ mod tests { credential: without_act, policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Refused, - expected_stage: "client", + expected_error: AuthenticationError::Refused(FailedCheck::Delegation), default_off: false, }, NegativeCase { @@ -1017,8 +1104,7 @@ mod tests { credential: delegated_token(json!({"azp": "canary-wrong-client"})), policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Refused, - expected_stage: "client", + expected_error: AuthenticationError::Refused(FailedCheck::TokenAssertionIssuer), default_off: false, }, NegativeCase { @@ -1028,8 +1114,7 @@ mod tests { })), policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Refused, - expected_stage: "client", + expected_error: AuthenticationError::Refused(FailedCheck::TokenAssertionIssuer), default_off: false, }, NegativeCase { @@ -1037,8 +1122,7 @@ mod tests { credential: delegated_token(json!({"registry_actor_kind": "service"})), policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::NotHuman, - expected_stage: "profile", + expected_error: AuthenticationError::NotHuman(FailedCheck::ActorKind), default_off: false, }, NegativeCase { @@ -1046,8 +1130,7 @@ mod tests { credential: missing_iat, policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Refused, - expected_stage: "time", + expected_error: AuthenticationError::Refused(FailedCheck::TokenTime), default_off: false, }, NegativeCase { @@ -1055,8 +1138,7 @@ mod tests { credential: delegated_token(json!({"sub": "canary-unknown-policy"})), policy: "canary-unknown-policy", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Profile, - expected_stage: "profile", + expected_error: AuthenticationError::Profile(FailedCheck::AccessProfile), default_off: false, }, NegativeCase { @@ -1064,8 +1146,7 @@ mod tests { credential: delegated_token(json!({"sub": "canary-default-off"})), policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Profile, - expected_stage: "profile", + expected_error: AuthenticationError::Profile(FailedCheck::AccessProfile), default_off: true, }, NegativeCase { @@ -1073,8 +1154,7 @@ mod tests { credential: delegated_token(json!({"sub": "canary-source-profile"})), policy: "staff-mcp", source_profile: Some("canary-unlisted-source"), - expected_error: AuthenticationError::Profile, - expected_stage: "profile", + expected_error: AuthenticationError::Profile(FailedCheck::AccessProfile), default_off: false, }, ]; @@ -1090,33 +1170,15 @@ mod tests { .with_subscriber(captured.subscriber()) .await; assert_eq!(result.unwrap_err(), case.expected_error, "{}", case.name); - let rendered = captured.text(); - let entries = rendered - .lines() - .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) - .collect::>(); - assert_eq!(entries.len(), 1, "{}: {rendered}", case.name); - assert_eq!( - entries[0]["fields"]["message"], "Casework delegated staff authentication refused", - "{}", - case.name - ); - assert_eq!( - entries[0]["fields"]["stage"], case.expected_stage, - "{}", - case.name - ); - assert!(!rendered.contains("canary"), "{}: {rendered}", case.name); - assert!( - !rendered.contains(&case.credential), - "{}: credential reached diagnostic", - case.name - ); + // Recording belongs to the HTTP boundary. The authenticator + // writes nothing, whatever the credential carries. + assert_eq!(captured.text(), "", "{}", case.name); } } #[tokio::test] - async fn compact_token_admission_logs_one_value_free_header_diagnostic() { + async fn compact_token_admission_refuses_a_malformed_token_as_malformed_and_writes_no_log_line() + { use registry_platform_testing::{malformed_access_token_fixtures, CapturedDiagnosticLogs}; use tracing::instrument::WithSubscriber; let captured = CapturedDiagnosticLogs::default(); @@ -1125,25 +1187,27 @@ mod tests { let auth = authenticator(BTreeMap::new()); for _ in 0..3 { for token in &tokens { - assert!(matches!( + assert_eq!( auth.authenticate(token, "requester") .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - assert!(matches!( + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); + assert_eq!( auth.authenticate_task_client( token, "casework:grants:status", ActorKind::Service ) .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); } } - captured.assert_one_value_free_header_diagnostic(&tokens); + assert_eq!(captured.text(), ""); } #[tokio::test] @@ -1190,31 +1254,31 @@ mod tests { let auth = &auth; async move { auth.authenticate(&token, "staff").await } }, - |error| matches!(error, AuthenticationError::Refused), + |error| matches!(error, AuthenticationError::Refused(_)), ) .await; // A valid symmetric JWT is outside the asymmetric production baseline. let token = self::token( json!({"azp":CLIENT,"scope":"casework:staff","registry_actor_kind":"human"}), ); - assert!(matches!( - auth.authenticate(&token, "staff").await, - Err(AuthenticationError::Refused) - )); + assert_eq!( + auth.authenticate(&token, "staff").await.unwrap_err(), + AuthenticationError::Refused(FailedCheck::TokenAlgorithm) + ); let mut wrong_actor = claims.clone(); wrong_actor["registry_actor_kind"] = json!("canary-invalid-actor"); let token = sign(wrong_actor, "at+jwt"); - assert!(matches!( - auth.authenticate(&token, "staff").await, - Err(AuthenticationError::NotHuman) - )); + assert_eq!( + auth.authenticate(&token, "staff").await.unwrap_err(), + AuthenticationError::NotHuman(FailedCheck::ActorKind) + ); let mut missing = claims.clone(); missing["scope"] = json!(""); let token = sign(missing, "at+jwt"); - assert!(matches!( - auth.authenticate(&token, "staff").await, - Err(AuthenticationError::Profile) - )); + assert_eq!( + auth.authenticate(&token, "staff").await.unwrap_err(), + AuthenticationError::Profile(FailedCheck::Scope) + ); } } } diff --git a/crates/registry-casework/src/auth/delegated.rs b/crates/registry-casework/src/auth/delegated.rs index 124c9cfc58..a5e3463ed5 100644 --- a/crates/registry-casework/src/auth/delegated.rs +++ b/crates/registry-casework/src/auth/delegated.rs @@ -168,82 +168,51 @@ fn delegated_recheck( } impl CaseworkAuthenticator { - fn delegated_staff_refusal( - &self, - stage: registry_platform_oidc::AuthenticationStage, - error: AuthenticationError, - ) -> AuthenticationError { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - stage, - "Casework delegated staff authentication refused", - remedy = "check delegatedStaffReaders and authentication.oidc client, assertion, actor, scope and lifetime bindings" - ); - error - } - pub(crate) async fn authenticate_staff_read( &self, token: &str, policy_id: &str, source_profile: Option<&str>, ) -> Result { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Casework delegated staff authentication refused" - ); - AuthenticationError::Refused - })?; - let binding = self.delegated_staff_readers.get(policy_id).ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Profile, - ) - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; + let binding = self + .delegated_staff_readers + .get(policy_id) + .ok_or(AuthenticationError::Profile(FailedCheck::AccessProfile))?; let profile = self .profiles .get(&binding.profile) .filter(|profile| profile.acts_as == CaseworkActsAs::Staff) - .ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Profile, - ) - })?; + .ok_or(AuthenticationError::Profile(FailedCheck::AccessProfile))?; if source_profile.is_some_and(|source| { !binding .source_profiles .iter() .any(|allowed| allowed == source) }) { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Profile, - )); + return Err(AuthenticationError::Profile(FailedCheck::AccessProfile)); } - let matched_client = verified.matched_client_id().map_err(|_| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Client, - AuthenticationError::Refused, - ) - })?; - if matched_client != Some(binding.client.as_str()) - || verified - .claims - .extra - .get(ASSERTION_ISSUER_CLAIM) - .and_then(Value::as_str) - != Some(binding.assertion_issuer.as_str()) + let matched_client = verified + .matched_client_id() + .map_err(|_| AuthenticationError::Refused(FailedCheck::TokenClient))?; + if matched_client != Some(binding.client.as_str()) { + return Err(AuthenticationError::Refused(FailedCheck::TokenClient)); + } + if verified + .claims + .extra + .get(ASSERTION_ISSUER_CLAIM) + .and_then(Value::as_str) + != Some(binding.assertion_issuer.as_str()) { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Client, - AuthenticationError::Refused, + return Err(AuthenticationError::Refused( + FailedCheck::TokenAssertionIssuer, )); } if verified @@ -252,10 +221,7 @@ impl CaseworkAuthenticator { .keys() .any(|key| key.starts_with("registry_grant_")) { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Refused, - )); + return Err(AuthenticationError::Refused(FailedCheck::TaskGrantClaims)); } let audience = match verified.claims.aud.as_ref() { Some(Audience::One(audience)) if audience == &self.audience => audience.clone(), @@ -264,30 +230,19 @@ impl CaseworkAuthenticator { { audiences[0].clone() } - _ => { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Audience, - AuthenticationError::Refused, - )) - } + _ => return Err(AuthenticationError::Refused(FailedCheck::TokenAudience)), }; - let issuer = verified.claims.iss.as_deref().ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Issuer, - AuthenticationError::Refused, - ) - })?; + let issuer = verified + .claims + .iss + .as_deref() + .ok_or(AuthenticationError::Refused(FailedCheck::TokenClaims))?; let subject = verified .claims .sub .as_deref() .filter(|subject| !subject.is_empty()) - .ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Claims, - ) - })?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; let expires_at = match (verified.claims.iat, verified.claims.exp) { (Some(issued_at), Some(expires_at)) if issued_at >= 0 @@ -298,21 +253,13 @@ impl CaseworkAuthenticator { { expires_at } - _ => { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Time, - AuthenticationError::Refused, - )) - } + _ => return Err(AuthenticationError::Refused(FailedCheck::TokenTime)), }; let act = strict_actor( verified.claims.extra.get("act"), issuer, &binding.actor_subject, - ) - .map_err(|error| { - self.delegated_staff_refusal(registry_platform_oidc::AuthenticationStage::Client, error) - })?; + )?; let actual_scopes = verified.scopes.iter().cloned().collect::>(); let mut expected_scopes = profile .required_scopes @@ -323,10 +270,7 @@ impl CaseworkAuthenticator { if !expected_scopes.is_subset(&actual_scopes) || actual_scopes.len() != verified.scopes.len() { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Scope, - AuthenticationError::Profile, - )); + return Err(AuthenticationError::Profile(FailedCheck::Scope)); } if verified .claims @@ -335,10 +279,7 @@ impl CaseworkAuthenticator { .and_then(Value::as_str) != Some(self.human_identity.value.as_str()) { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::NotHuman, - )); + return Err(AuthenticationError::NotHuman(FailedCheck::ActorKind)); } let principal = if profile.principal_claim == "sub" { Some(subject) @@ -350,12 +291,7 @@ impl CaseworkAuthenticator { .and_then(Value::as_str) } .filter(|value| !value.is_empty()) - .ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Claims, - ) - })?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; Ok(DelegatedStaffReader { actor: ActorContext { principal: IssuerPrincipal { @@ -388,20 +324,20 @@ fn strict_actor( ) -> Result<(String, String), AuthenticationError> { let object = value .and_then(Value::as_object) - .ok_or(AuthenticationError::Refused)?; + .ok_or(AuthenticationError::Refused(FailedCheck::Delegation))?; if object.contains_key("act") { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); } if let Some(issuer) = object.get("iss") { if issuer.as_str() != Some(expected_issuer) { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); } } let subject = object .get("sub") .and_then(Value::as_str) .filter(|value| *value == expected_subject) - .ok_or(AuthenticationError::Refused)?; + .ok_or(AuthenticationError::Refused(FailedCheck::Delegation))?; Ok((expected_issuer.to_owned(), subject.to_owned())) } diff --git a/crates/registry-casework/src/config.rs b/crates/registry-casework/src/config.rs index 3945fa6251..b2efe6488d 100644 --- a/crates/registry-casework/src/config.rs +++ b/crates/registry-casework/src/config.rs @@ -21,9 +21,11 @@ pub use registry_platform_config::{ OidcIssuerConfig, PrivateListenerConfig as ListenerConfig, SecretProvidersConfig, TlsTermination, }; +use registry_platform_httputil::loopback; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifierConfig, }; use registry_platform_yaml::{escape_pointer_segment, Diagnostic, Report, RetiredApiVersion}; use serde::{Deserialize, Deserializer}; @@ -1738,8 +1740,13 @@ impl RuntimeConfig { &error, )) })?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| RuntimeConfigError::Oidc)?; + let jwks = + parse_static_jwks(document.expose_secret()).map_err(|error| match error { + OidcError::StaticKeySet(refusal) => { + RuntimeConfigError::OidcJwksSecret(refusal.to_string()) + } + _ => RuntimeConfigError::Oidc, + })?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -1906,7 +1913,9 @@ fn valid_review_completion_url(raw: &str) -> bool { } match url.scheme() { "https" => url.host_str().is_some(), - "http" => matches!(url.host_str(), Some("127.0.0.1" | "::1" | "[::1]")), + "http" => url + .host_str() + .is_some_and(|host| loopback::loopback_literal(host).is_some()), _ => false, } } @@ -2112,6 +2121,7 @@ fn stand_in_for(pointer: &str) -> &'static str { mod tests { use super::*; use jsonwebtoken::Algorithm; + use registry_platform_authcommon::FailedCheck; use registry_platform_config::write_package; use serde_json::json; @@ -2214,6 +2224,87 @@ mod tests { }) } + /// Resolve the verifier of a runtime file whose static key set is `document`. + async fn verifier_for_static_key_set( + document: &serde_json::Value, + ) -> Result<(), RuntimeConfigError> { + use std::os::unix::fs::PermissionsExt as _; + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = root.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let file = secrets.join("jwks"); + std::fs::write(&file, document.to_string()).unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut value = operator_value(root.path(), root.path()); + value["authentication"]["oidc"]["jwksSource"] = + json!({"type":"static", "documentRef":"secret:file/jwks"}); + let config = read_operator(&value, root.path()); + let resolver = + SecretResolver::new([registry_platform_config::SecretProvider::File], &secrets) + .unwrap(); + config.oidc_verifier(&resolver).await.map(|_| ()) + } + + fn public_rsa_key(kid: &str) -> serde_json::Value { + json!({"kty":"RSA","kid":kid,"alg":"RS256","n":"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw","e":"AQAB"}) + } + + #[tokio::test] + async fn a_static_key_set_with_unknown_public_members_loads() { + let mut key = public_rsa_key("signing-1"); + key["ext"] = json!(true); + key["x5c"] = json!(["MIIB"]); + key["x5t"] = json!("thumbprint"); + key["use"] = json!("sig"); + key["key_ops"] = json!(["verify"]); + let mut encryption = public_rsa_key("encryption-1"); + encryption["use"] = json!("enc"); + let document = json!({"keys": [key, encryption], "issuer": "an unknown top-level member"}); + verifier_for_static_key_set(&document) + .await + .expect("members the validator does not name are ignored"); + } + + #[tokio::test] + async fn a_static_key_set_with_a_private_member_is_refused_with_its_text() { + let mut key = public_rsa_key("signing-1"); + key["d"] = json!("canary-private-exponent"); + let error = verifier_for_static_key_set(&json!({"keys": [key]})) + .await + .expect_err("a private member is refused"); + assert_eq!(error.code(), "casework.runtime.unreadable-jwks-secret"); + let rendered = error.to_string(); + assert!(rendered.contains("private-key member \"d\""), "{rendered}"); + assert!(!rendered.contains("canary"), "{rendered}"); + assert!(!rendered.contains("signing-1"), "{rendered}"); + } + + #[test] + fn a_review_completion_destination_may_use_http_only_on_a_loopback_address() { + for admitted in [ + "https://completion.example.test/reviews", + "http://127.0.0.1:9000/reviews", + "http://127.0.0.2/reviews", + "http://[::1]:9000/reviews", + "http://[::ffff:127.0.0.1]/reviews", + ] { + assert!(valid_review_completion_url(admitted), "{admitted}"); + } + for refused in [ + "http://localhost/reviews", + "http://LOCALHOST:9000/reviews", + "http://localhost./reviews", + "http://app.localhost/reviews", + "http://10.0.0.1/reviews", + "http://0.0.0.0/reviews", + "http://completion.example.test/reviews", + "http://127.0.0.1@example.test/reviews", + ] { + assert!(!valid_review_completion_url(refused), "{refused}"); + } + } + #[test] fn metrics_listener_wildcard_needs_container_private_exposure() { let directory = tempfile::tempdir().unwrap(); @@ -2574,10 +2665,10 @@ mod tests { let mut value = operator_value(directory.path(), directory.path()); value["authentication"]["oidc"]["revokedKeyIds"] = json!(["signing-1"]); let refused = verify_under_operator_profile(&value, "signing-1", 300).await; - assert!(matches!( - refused, - Err(crate::auth::AuthenticationError::Refused) - )); + assert_eq!( + refused.unwrap_err(), + crate::auth::AuthenticationError::Refused(FailedCheck::TokenKey) + ); verify_under_operator_profile(&value, "signing-2", 300) .await .expect("a key not on the list still verifies"); @@ -2592,10 +2683,10 @@ mod tests { .await .expect("a token within the bound verifies"); let refused = verify_under_operator_profile(&value, "signing-1", 301).await; - assert!(matches!( - refused, - Err(crate::auth::AuthenticationError::Refused) - )); + assert_eq!( + refused.unwrap_err(), + crate::auth::AuthenticationError::Refused(FailedCheck::TokenTime) + ); } #[test] diff --git a/crates/registry-casework/src/http.rs b/crates/registry-casework/src/http.rs index 0b9b4419df..6ed29a0a8c 100644 --- a/crates/registry-casework/src/http.rs +++ b/crates/registry-casework/src/http.rs @@ -12,7 +12,9 @@ use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::{Json, Router}; use registry_casework_core::*; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, record_refusal, BearerParseError, FailedCheck, RefusalNote, RefusalRecorder, +}; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, FrameworkRejection, ProblemBody, TraceContext, @@ -79,6 +81,13 @@ pub struct HttpState { } pub fn router(state: HttpState) -> Router { + router_with_recorder(state, crate::metrics::refusal_recorder()) +} + +/// The router, counting and logging every refusal through `recorder`. A test +/// passes its own recorder to read what a request counted. A service uses +/// [`router`], whose recorder feeds the metrics scrape. +pub fn router_with_recorder(state: HttpState, recorder: Arc) -> Router { let review = Router::new() .route("/v1/review-requests", post(create_review_request)) .route("/v1/review-results", get(review_result_feed)) @@ -205,16 +214,29 @@ pub fn router(state: HttpState) -> Router { post(preview_caseload_move), ) .route("/v1/directory/caseload/apply", post(apply_caseload_move)); - http_edge(app, Some(state.clone())) + http_edge_recording(app, Some(state.clone()), Arc::clone(&recorder)) .merge(contract_edge( review, HttpContract::Review, Some(state.clone()), + recorder, )) .with_state(state) } +#[cfg(test)] fn http_edge(router: Router, source_state: Option) -> Router +where + S: Clone + Send + Sync + 'static, +{ + http_edge_recording(router, source_state, crate::metrics::refusal_recorder()) +} + +fn http_edge_recording( + router: Router, + source_state: Option, + recorder: Arc, +) -> Router where S: Clone + Send + Sync + 'static, { @@ -222,6 +244,7 @@ where router.fallback(route_not_found), HttpContract::Casework, source_state, + recorder, ) } @@ -229,6 +252,7 @@ fn contract_edge( router: Router, contract: HttpContract, source_state: Option, + recorder: Arc, ) -> Router where S: Clone + Send + Sync + 'static, @@ -244,7 +268,10 @@ where } else { router }; + // The one recording point: it sits outside the admission layer, so a + // refusal from either is counted once, inside the request's trace scope. router + .layer(middleware::from_fn_with_state(recorder, record_refusals)) .layer(request_body_limit_default()) .layer(middleware::from_fn(move |request, next| { http_boundary(contract, request, next) @@ -252,6 +279,23 @@ where .layer(security_headers(CspBuilder::restrictive()).without_hsts()) } +/// Counts and logs the refusal a response carries in its extensions. The +/// extension is never serialized, so the answer's bytes are unchanged. +async fn record_refusals( + State(recorder): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::().copied() { + match REQUEST_TRACE.try_with(|trace| trace.trace_id.clone()) { + Ok(trace_id) => record_refusal!(recorder, note, trace_id = &trace_id), + Err(_) => record_refusal!(recorder, note), + } + } + response +} + async fn http_boundary( contract: HttpContract, request: axum::http::Request, @@ -1437,18 +1481,14 @@ async fn task_client( ) -> Result { if headers.contains_key(CASEWORK_PROFILE_HEADER) || headers.contains_key(SOURCE_PROFILE_HEADER) { - return Err(HttpError::AuthenticationRefused); + return Err(HttpError::AuthenticationRefused(FailedCheck::AccessProfile)); } - let raw = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .ok_or_else(|| header_authentication_refused(state))?; - let token = parse_bearer_token(raw).map_err(|_| header_authentication_refused(state))?; + let token = bearer_credential(headers)?; state .authenticator .authenticate_task_client(token, scope, kind) .await - .map_err(|_| HttpError::AuthenticationRefused) + .map_err(|error| HttpError::AuthenticationRefused(error.failed_check())) } async fn task_assertion( RequestState(state): RequestState, @@ -1487,23 +1527,13 @@ async fn authenticate<'a>( state: &HttpState, headers: &'a HeaderMap, ) -> Result<(registry_casework_core::ActorContext, &'a str), HttpError> { - let authorization = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .ok_or_else(|| header_authentication_refused(state))?; - let token = - parse_bearer_token(authorization).map_err(|_| header_authentication_refused(state))?; + let token = bearer_credential(headers)?; let profile = profile_header(headers, HttpContract::current().profile_header())?; let actor = state .authenticator .authenticate(token, profile) .await - .map_err(|error| match error { - AuthenticationError::Refused => HttpError::AuthenticationRefused, - AuthenticationError::Profile => HttpError::ProfileNotAuthorized, - AuthenticationError::NotHuman => HttpError::ProfileNotHuman, - AuthenticationError::Claims => HttpError::AuthenticationRefused, - })?; + .map_err(HttpError::from)?; Ok((actor, token)) } @@ -1513,33 +1543,39 @@ async fn authenticate_delegated_staff_read<'a>( source_profile: Option<&str>, ) -> Result<(crate::auth::delegated::DelegatedStaffReader, &'a str), HttpError> { if headers.contains_key(CASEWORK_PROFILE_HEADER) { - return Err(HttpError::ProfileNotAuthorized); + return Err(HttpError::ProfileNotAuthorized(FailedCheck::AccessProfile)); } - let authorization = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .ok_or_else(|| header_authentication_refused(state))?; - let token = - parse_bearer_token(authorization).map_err(|_| header_authentication_refused(state))?; + let token = bearer_credential(headers)?; let policy = profile_header(headers, DELEGATED_READER_HEADER)?; let reader = state .authenticator .authenticate_staff_read(token, policy, source_profile) .await - .map_err(|error| match error { - AuthenticationError::Refused | AuthenticationError::Claims => { - HttpError::AuthenticationRefused - } - AuthenticationError::Profile | AuthenticationError::NotHuman => { - HttpError::ProfileNotAuthorized - } - })?; + .map_err(HttpError::DelegatedStaff)?; Ok((reader, token)) } -fn header_authentication_refused(state: &HttpState) -> HttpError { - state.authenticator.record_header_refusal(); - HttpError::AuthenticationRefused +/// The bearer token of a request, or the refusal that names why there is +/// none: no header, a scheme other than Bearer, or a value that is not a +/// well-formed bearer credential. +fn bearer_credential(headers: &HeaderMap) -> Result<&str, HttpError> { + let Some(value) = headers.get(AUTHORIZATION) else { + return Err(HttpError::AuthenticationRefused( + FailedCheck::CredentialMissing, + )); + }; + let value = value + .to_str() + .map_err(|_| HttpError::AuthenticationRefused(FailedCheck::CredentialMalformed))?; + parse_bearer_token(value).map_err(bearer_refusal) +} + +/// The refusal for an `Authorization` value that is not a bearer credential. +fn bearer_refusal(error: BearerParseError) -> HttpError { + HttpError::AuthenticationRefused(match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) } fn source_profile(headers: &HeaderMap) -> Result<&str, HttpError> { @@ -1643,11 +1679,16 @@ fn if_match_with_minimum(headers: &HeaderMap, minimum: i64) -> Result for HttpError { fn from(e: StoreError) -> Self { match e { @@ -1681,8 +1725,8 @@ impl From for HttpError { StoreError::CursorExpired => Self::CursorExpired, StoreError::CursorInvalid => Self::CursorInvalid, StoreError::IdempotencyExpired => Self::IdempotencyExpired, - StoreError::NotFound => Self::NotFound, - StoreError::Forbidden => Self::Forbidden, + StoreError::NotFound => Self::NotFound(FailedCheck::Visibility), + StoreError::Forbidden => Self::Forbidden(FailedCheck::Operation), StoreError::Conflict => Self::PreconditionFailed, StoreError::AlreadyClaimed | StoreError::NotHolder => Self::ReviewTaskNotHeld, StoreError::IdempotencyConflict => Self::IdempotencyKeyReused, @@ -1701,8 +1745,8 @@ impl From for HttpError { fn from(e: ServiceError) -> Self { match e { ServiceError::Store(e) => e.into(), - ServiceError::NotFound => Self::NotFound, - ServiceError::Forbidden => Self::Forbidden, + ServiceError::NotFound => Self::NotFound(FailedCheck::Visibility), + ServiceError::Forbidden => Self::Forbidden(FailedCheck::Operation), ServiceError::ReviewValidation(e) => Self::Validation(e), ServiceError::Configuration => Self::Internal, ServiceError::Context(ReviewContextError::VersionMismatch) => { @@ -1715,15 +1759,15 @@ impl From for HttpError { ServiceError::Context( ReviewContextError::Invalid | ReviewContextError::Unsupported, ) => Self::SourceBadGateway, - ServiceError::Context(_) => Self::NotFound, + ServiceError::Context(_) => Self::NotFound(FailedCheck::Visibility), } } } impl From for HttpError { fn from(e: ReviewRuntimeError) -> Self { match e { - ReviewRuntimeError::NotFound => Self::NotFound, - ReviewRuntimeError::Forbidden => Self::Forbidden, + ReviewRuntimeError::NotFound => Self::NotFound(FailedCheck::Visibility), + ReviewRuntimeError::Forbidden => Self::Forbidden(FailedCheck::Operation), ReviewRuntimeError::SubmissionConflict => Self::ReviewSubmissionConflict, ReviewRuntimeError::ResultExpired => Self::ReviewResultExpired, ReviewRuntimeError::TaskNotHeld => Self::ReviewTaskNotHeld, @@ -1751,14 +1795,107 @@ impl From for HttpError { } } } +impl From for HttpError { + fn from(error: AuthenticationError) -> Self { + match error { + AuthenticationError::Refused(check) | AuthenticationError::Claims(check) => { + Self::AuthenticationRefused(check) + } + AuthenticationError::Profile(check) => Self::ProfileNotAuthorized(check), + AuthenticationError::NotHuman(check) => Self::ProfileNotHuman(check), + } + } +} + +/// Operator hint on a scope refusal. +const SCOPE_REMEDY: &str = "check authentication.oidc.scopeClaim and accessProfiles requiredScopes"; +/// Operator hint on a refusal of the selected profile or of a person's session. +const PROFILE_REMEDY: &str = + "check selected accessProfiles and authentication.oidc.humanIdentity profile category"; +/// Operator hint on a delegated staff read refused by its configured bindings. +const DELEGATED_STAFF_REMEDY: &str = "check delegatedStaffReaders and authentication.oidc client, assertion, actor, scope and lifetime bindings"; + impl HttpError { + /// The check a refused request failed, for the operator's counter and + /// log line. `None` for an answer that is not an authentication or + /// authorization refusal. Never written to a response. + #[deny(clippy::wildcard_enum_match_arm)] + fn failed_check(&self) -> Option { + match self { + Self::AuthenticationRefused(check) + | Self::ProfileNotAuthorized(check) + | Self::ProfileNotHuman(check) + | Self::Forbidden(check) + | Self::NotFound(check) => Some(*check), + Self::DelegatedStaff(error) => Some(error.failed_check()), + Self::ReviewDistinctApproverRequired | Self::ReviewInitiatorExcluded => { + Some(FailedCheck::SeparationOfDuties) + } + Self::PreconditionFailed + | Self::PreconditionRequired + | Self::IdempotencyKeyReused + | Self::IdempotencyExpired + | Self::Invalid + | Self::LimitOutOfRange + | Self::ServiceUnavailable + | Self::SourceProfileNotApplicable + | Self::SourceProfileRequired + | Self::SourceBadGateway + | Self::SourceVersionMismatch + | Self::SourceVersionUnavailable + | Self::ReviewInitiatorRequired + | Self::ReviewResultExpired + | Self::ReviewSubmissionConflict + | Self::ReviewTaskNotHeld + | Self::ReviewPolicyMismatch + | Self::ReviewQueryTooBroad + | Self::CursorInvalid + | Self::CursorExpired + | Self::Absence(_) + | Self::Internal + | Self::Validation(_) => None, + } + } + + /// The fixed operator hint that goes with the refusal, if there is one. + fn remedy(&self) -> Option<&'static str> { + match self { + Self::ProfileNotAuthorized(FailedCheck::Scope) => Some(SCOPE_REMEDY), + Self::ProfileNotAuthorized(FailedCheck::AccessProfile) + | Self::ProfileNotHuman(FailedCheck::ActorKind) => Some(PROFILE_REMEDY), + Self::DelegatedStaff(error) => matches!( + error.failed_check(), + FailedCheck::AccessProfile + | FailedCheck::TokenAssertionIssuer + | FailedCheck::TokenClient + | FailedCheck::TaskGrantClaims + | FailedCheck::TokenAudience + | FailedCheck::TokenClaims + | FailedCheck::TokenTime + | FailedCheck::Delegation + | FailedCheck::Scope + | FailedCheck::ActorKind + ) + .then_some(DELEGATED_STAFF_REMEDY), + _ => None, + } + } + fn problem(&self) -> ProblemCode { match self { - Self::AuthenticationRefused => ProblemCode::AuthenticationRefused, - Self::ProfileNotAuthorized => ProblemCode::ProfileNotAuthorized, - Self::ProfileNotHuman => ProblemCode::ProfileNotHuman, - Self::Forbidden => ProblemCode::OperationNotAuthorized, - Self::NotFound => ProblemCode::RequestNotFound, + Self::AuthenticationRefused(_) => ProblemCode::AuthenticationRefused, + Self::ProfileNotAuthorized(_) => ProblemCode::ProfileNotAuthorized, + Self::ProfileNotHuman(_) => ProblemCode::ProfileNotHuman, + Self::DelegatedStaff(error) => match error { + AuthenticationError::Refused(_) | AuthenticationError::Claims(_) => { + ProblemCode::AuthenticationRefused + } + AuthenticationError::Profile(_) | AuthenticationError::NotHuman(_) => { + ProblemCode::ProfileNotAuthorized + } + }, + Self::Forbidden(_) => ProblemCode::OperationNotAuthorized, + Self::NotFound(_) => ProblemCode::RequestNotFound, Self::PreconditionFailed => ProblemCode::PreconditionFailed, Self::PreconditionRequired => ProblemCode::PreconditionRequired, Self::IdempotencyKeyReused => ProblemCode::IdempotencyKeyReused, @@ -1797,7 +1934,18 @@ impl IntoResponse for HttpError { Self::Validation(v) => Some(v), _ => None, }; - problem_response(self.problem(), None, validation) + let note = self.failed_check().map(|check| { + let note = RefusalNote::new(check); + match self.remedy() { + Some(remedy) => note.with_remedy(remedy), + None => note, + } + }); + let mut response = problem_response(self.problem(), None, validation); + if let Some(note) = note { + response.extensions_mut().insert(note); + } + response } } @@ -1955,6 +2103,7 @@ mod tests { Router::new().route("/review", post(selected_profile)), HttpContract::Review, None, + crate::metrics::refusal_recorder(), ), ); for (path, selected, other, base) in [ @@ -2058,6 +2207,7 @@ mod tests { ), HttpContract::Review, None, + crate::metrics::refusal_recorder(), ); for (method, path, media, body, expected) in [ ( @@ -2414,7 +2564,9 @@ mod tests { .route( "/authentication", axum::routing::get(|| async { - Err::(HttpError::AuthenticationRefused) + Err::(HttpError::AuthenticationRefused( + FailedCheck::TokenSignature, + )) }), ) .route( @@ -2649,4 +2801,237 @@ mod tests { ); } } + + fn refusing_router(recorder: Arc) -> Router { + let answer = |error: fn() -> HttpError| { + axum::routing::get(move || async move { Err::(error()) }) + }; + http_edge_recording( + Router::new() + .route( + "/signature", + answer(|| HttpError::AuthenticationRefused(FailedCheck::TokenSignature)), + ) + .route( + "/scope", + answer(|| HttpError::ProfileNotAuthorized(FailedCheck::Scope)), + ) + .route( + "/not-human", + answer(|| HttpError::ProfileNotHuman(FailedCheck::ActorKind)), + ) + .route( + "/delegated", + answer(|| { + HttpError::DelegatedStaff(AuthenticationError::Profile( + FailedCheck::AccessProfile, + )) + }), + ) + .route( + "/forbidden", + answer(|| HttpError::Forbidden(FailedCheck::Operation)), + ) + .route( + "/concealed", + answer(|| HttpError::NotFound(FailedCheck::Visibility)), + ) + .route( + "/distinct", + answer(|| HttpError::ReviewDistinctApproverRequired), + ) + .route("/excluded", answer(|| HttpError::ReviewInitiatorExcluded)) + .route("/invalid", answer(|| HttpError::Invalid)) + .route("/outage", answer(|| HttpError::ServiceUnavailable)), + None, + recorder, + ) + } + + async fn refused(app: &Router, path: &str) -> StatusCode { + app.clone() + .oneshot( + Request::builder() + .uri(path) + .header("traceparent", TRACEPARENT) + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response") + .status() + } + + fn recorder() -> Arc { + Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")) + } + + #[tokio::test] + async fn each_refusal_is_counted_once_under_its_own_check() { + let recorder = recorder(); + let app = refusing_router(Arc::clone(&recorder)); + for (path, status, check) in [ + ("/signature", 401, "token-signature"), + ("/scope", 403, "scope"), + ("/not-human", 403, "actor-kind"), + ("/delegated", 403, "access-profile"), + ("/forbidden", 403, "operation"), + ("/concealed", 404, "visibility"), + ("/distinct", 403, "separation-of-duties"), + ("/excluded", 403, "separation-of-duties"), + ] { + let before = recorder.counter().get(&[check]).expect("a declared check"); + assert_eq!(refused(&app, path).await.as_u16(), status, "{path}"); + assert_eq!( + recorder.counter().get(&[check]), + Some(before + 1), + "{path} counts under {check}" + ); + } + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, 8, "no other check moved"); + } + + #[tokio::test] + async fn an_answer_that_is_not_a_refusal_is_not_counted() { + let recorder = recorder(); + let app = refusing_router(Arc::clone(&recorder)); + assert_eq!(refused(&app, "/invalid").await, StatusCode::BAD_REQUEST); + assert_eq!( + refused(&app, "/outage").await, + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!(refused(&app, "/unrouted").await, StatusCode::NOT_FOUND); + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, 0); + } + + #[tokio::test] + async fn a_refusal_logs_one_value_free_line_with_its_check_remedy_and_trace() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + + let app = refusing_router(recorder()); + let captured = CapturedDiagnosticLogs::default(); + let subscriber = captured.subscriber(); + for path in ["/scope", "/delegated", "/signature"] { + refused(&app, path) + .with_subscriber(subscriber.clone()) + .await; + } + let lines: Vec = captured + .text() + .lines() + .map(|line| serde_json::from_str(line).expect("a JSON log line")) + .collect(); + assert_eq!(lines.len(), 3, "{}", captured.text()); + for (line, check, remedy) in [ + (&lines[0], "scope", Some(SCOPE_REMEDY)), + (&lines[1], "access-profile", Some(DELEGATED_STAFF_REMEDY)), + (&lines[2], "token-signature", None), + ] { + let fields = &line["fields"]; + assert_eq!(fields["message"], "request refused"); + assert_eq!(fields["decision"], "refused"); + assert_eq!(fields["failed_check"], check); + assert_eq!(fields["suppressed"], 0); + assert_eq!(fields["trace_id"], "0123456789abcdef0123456789abcdef"); + assert_eq!( + fields.get("remedy").and_then(|value| value.as_str()), + remedy + ); + assert_eq!( + fields.as_object().expect("fields").len(), + if remedy.is_some() { 6 } else { 5 }, + "{line}" + ); + } + } + + #[tokio::test] + async fn a_flood_of_one_check_logs_five_lines_and_counts_every_refusal() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + + let recorder = recorder(); + let app = refusing_router(Arc::clone(&recorder)); + let captured = CapturedDiagnosticLogs::default(); + let subscriber = captured.subscriber(); + for _ in 0..20 { + refused(&app, "/signature") + .with_subscriber(subscriber.clone()) + .await; + } + assert_eq!(recorder.counter().get(&["token-signature"]), Some(20)); + assert_eq!(captured.text().lines().count(), 5, "{}", captured.text()); + } + + #[test] + fn an_authentication_error_maps_to_the_answer_it_always_had() { + for (error, problem) in [ + ( + AuthenticationError::Refused(FailedCheck::TokenKey), + ProblemCode::AuthenticationRefused, + ), + ( + AuthenticationError::Claims(FailedCheck::TokenClaims), + ProblemCode::AuthenticationRefused, + ), + ( + AuthenticationError::Profile(FailedCheck::Scope), + ProblemCode::ProfileNotAuthorized, + ), + ( + AuthenticationError::NotHuman(FailedCheck::ActorKind), + ProblemCode::ProfileNotHuman, + ), + ] { + assert_eq!(HttpError::from(error).problem(), problem); + } + // The delegated staff read answers a person's refusal as a profile one. + assert_eq!( + HttpError::DelegatedStaff(AuthenticationError::NotHuman(FailedCheck::ActorKind)) + .problem(), + ProblemCode::ProfileNotAuthorized + ); + } + + #[test] + fn a_bearer_header_is_missing_when_absent_or_not_bearer_and_malformed_otherwise() { + let check = |value: Option<&str>| { + let mut headers = HeaderMap::new(); + if let Some(value) = value { + headers.insert(AUTHORIZATION, value.parse().expect("a header value")); + } + match bearer_credential(&headers) { + Err(HttpError::AuthenticationRefused(check)) => check, + other => panic!("expected a refusal, got {other:?}"), + } + }; + assert_eq!(check(None), FailedCheck::CredentialMissing); + assert_eq!(check(Some("Basic abc")), FailedCheck::CredentialMissing); + assert_eq!(check(Some("Bearer")), FailedCheck::CredentialMalformed); + assert_eq!(check(Some("Bearer a b")), FailedCheck::CredentialMalformed); + assert_eq!(check(Some("Bearer a")), FailedCheck::CredentialMalformed); + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, "Bearer token".parse().unwrap()); + assert_eq!(bearer_credential(&headers).unwrap(), "token"); + let mut unreadable = HeaderMap::new(); + unreadable.insert( + AUTHORIZATION, + axum::http::HeaderValue::from_bytes(b"Bearer \xff").unwrap(), + ); + assert!(matches!( + bearer_credential(&unreadable), + Err(HttpError::AuthenticationRefused( + FailedCheck::CredentialMalformed + )) + )); + } } diff --git a/crates/registry-casework/src/http/source_credentials.rs b/crates/registry-casework/src/http/source_credentials.rs index 59c09335c3..f6613f56fd 100644 --- a/crates/registry-casework/src/http/source_credentials.rs +++ b/crates/registry-casework/src/http/source_credentials.rs @@ -126,12 +126,13 @@ pub(super) async fn boundary( /// answers as not found. fn conceal_target_error(target: Target, error: HttpError) -> HttpError { match (target, error) { + (Target::Task(_) | Target::Request(_), HttpError::NotFound(check)) => { + HttpError::NotFound(check) + } ( Target::Task(_) | Target::Request(_), - HttpError::AuthenticationRefused - | HttpError::NotFound - | HttpError::SourceProfileNotApplicable, - ) => HttpError::NotFound, + HttpError::AuthenticationRefused(_) | HttpError::SourceProfileNotApplicable, + ) => HttpError::NotFound(FailedCheck::Visibility), (_, error) => error, } } @@ -148,9 +149,9 @@ async fn admit( ) -> Result, HttpError> { let target = target(method, path).ok_or(HttpError::Invalid)?; let source = parse_bearer_token(single_header(headers, SOURCE_AUTHORIZATION_HEADER)?) - .map_err(|_| HttpError::AuthenticationRefused)?; + .map_err(bearer_refusal)?; registry_platform_authcommon::validate_compact_access_token(source) - .map_err(|_| HttpError::AuthenticationRefused)?; + .map_err(|_| HttpError::AuthenticationRefused(FailedCheck::CredentialMalformed))?; single_header(headers, AUTHORIZATION.as_str())?; single_header(headers, CASEWORK_PROFILE_HEADER)?; if !headers.contains_key(SOURCE_PROFILE_HEADER) { @@ -162,7 +163,7 @@ async fn admit( } let (actor, primary) = authenticate(state, headers).await?; if actor.role == CaseworkActsAs::Requester { - return Err(HttpError::ProfileNotAuthorized); + return Err(HttpError::ProfileNotAuthorized(FailedCheck::AccessProfile)); } let Some(provider) = state .service @@ -186,12 +187,13 @@ async fn admit( .authenticator .verify_human_source_pair(primary, source, &provider) .await - .map_err(|_| conceal_target_error(target, HttpError::AuthenticationRefused))?; - let original = state - .service - .providers - .get(&provider) - .ok_or_else(|| conceal_target_error(target, HttpError::AuthenticationRefused))?; + .map_err(|error| conceal_target_error(target, error.into()))?; + let original = state.service.providers.get(&provider).ok_or_else(|| { + conceal_target_error( + target, + HttpError::AuthenticationRefused(FailedCheck::AccessProfile), + ) + })?; let scoped = VerifiedSourceProvider { inner: Arc::clone(original), token: Zeroizing::new(source.to_owned()), diff --git a/crates/registry-casework/src/metrics.rs b/crates/registry-casework/src/metrics.rs index e30b08d253..17f8c9e556 100644 --- a/crates/registry-casework/src/metrics.rs +++ b/crates/registry-casework/src/metrics.rs @@ -1,12 +1,26 @@ //! Optional operator-private telemetry. Labels contain no caller or subject values. use crate::{CompletionBacklog, PostgresStore}; use axum::{extract::State, http::header::CONTENT_TYPE, routing::get, Json, Router}; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ sample_error_class, Exposition, MetricKind, ScrapeDeadline, CLASS_NO_TIME_LEFT, CONTENT_TYPE as METRICS_CONTENT_TYPE, }; use serde_json::json; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; + +/// The process's refusal recorder, shared by the HTTP boundary that counts +/// refusals and the scrape that exposes the counter. +pub(crate) fn refusal_recorder() -> Arc { + static RECORDER: OnceLock> = OnceLock::new(); + Arc::clone(RECORDER.get_or_init(|| { + Arc::new( + RefusalRecorder::new("casework") + .expect("the refusal counter declares one closed label"), + ) + })) +} + /// One sample of the database. Each part is sampled on its own, so a failing /// part leaves out only its own series. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -193,7 +207,7 @@ pub(crate) async fn begin_sample<'a>( pub async fn scrape_for_test(store: PostgresStore, deadline: ScrapeDeadline) -> String { let state = MetricsState::new(store, Vec::new(), "sha256:test".to_owned()); let readings = state.sample(deadline).await; - render(readings, &state.inner.failures) + render(readings, &state.inner.failures, &refusal_recorder()) } pub(crate) fn metrics_router(state: MetricsState) -> Router { Router::new() @@ -210,13 +224,13 @@ async fn metrics( let readings = state.readings().await; ( [(CONTENT_TYPE, METRICS_CONTENT_TYPE)], - render(readings, &state.inner.failures), + render(readings, &state.inner.failures, &refusal_recorder()), ) } /// The exposition for one scrape. A part of `readings` that could not be /// read has no series. The database counts as up when the review counts were -/// read. -fn render(readings: Readings, failures: &SampleFailures) -> String { +/// read. The refusal counter follows, one series per check. +fn render(readings: Readings, failures: &SampleFailures, refusals: &RefusalRecorder) -> String { const DECLARATION: &str = "the metric declarations are valid"; let mut out = Exposition::new(); out.header("casework_database_up", None, MetricKind::Gauge) @@ -286,14 +300,36 @@ fn render(readings: Readings, failures: &SampleFailures) -> String { ) .expect(DECLARATION); } + refusals.counter().write(&mut out).expect(DECLARATION); out.finish() } #[cfg(test)] mod tests { use super::{render, Readings, SampleFailures, SampleKind}; use crate::CompletionBacklog; + use registry_platform_authcommon::{FailedCheck, RefusalRecorder}; use registry_platform_metrics::ScrapeDeadline; + /// The refusal counter of a recorder that has counted `counted` once. + fn refusal_series(counted: Option) -> String { + let mut text = String::from( + "# HELP casework_request_refusals_total Requests refused, by the check that failed.\n\ + # TYPE casework_request_refusals_total counter\n", + ); + for check in FailedCheck::ALL { + let value = u8::from(counted == Some(check)); + text.push_str(&format!( + "casework_request_refusals_total{{check=\"{}\"}} {value}\n", + check.as_str() + )); + } + text + } + + fn recorder() -> RefusalRecorder { + RefusalRecorder::new("casework").expect("the casework recorder") + } + fn backlog() -> CompletionBacklog { CompletionBacklog { pending: 1, @@ -330,24 +366,39 @@ mod tests { review: Some([4, 9, 2]), completions: Some(backlog()), }; + let refusals = refusal_series(None); assert_eq!( - render(readings, &SampleFailures::default()), + render(readings, &SampleFailures::default(), &recorder()), format!( "{REVIEW}{COMPLETIONS}{FAILURES}\ casework_metrics_sample_failures_total{{sample=\"review\"}} 0\n\ - casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 0\n" + casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 0\n\ + {refusals}" ) ); assert_eq!( - render(Readings::default(), &SampleFailures::default()), + render(Readings::default(), &SampleFailures::default(), &recorder()), format!( "# TYPE casework_database_up gauge\ncasework_database_up 0\n{FAILURES}\ casework_metrics_sample_failures_total{{sample=\"review\"}} 0\n\ - casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 0\n" + casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 0\n\ + {refusals}" ) ); } + #[test] + fn the_scrape_lists_every_check_and_counts_a_refusal_once() { + let recorder = recorder(); + let _ = recorder.record(FailedCheck::TokenSignature); + assert_eq!( + render(Readings::default(), &SampleFailures::default(), &recorder) + .split_once("# HELP casework_request_refusals_total") + .map(|(_, series)| format!("# HELP casework_request_refusals_total{series}")), + Some(refusal_series(Some(FailedCheck::TokenSignature))) + ); + } + #[test] fn a_failed_backlog_leaves_out_only_the_completion_series() { let readings = Readings { @@ -358,11 +409,13 @@ mod tests { failures.0[SampleKind::CompletionBacklog as usize] .store(2, std::sync::atomic::Ordering::Relaxed); assert_eq!( - render(readings, &failures), + render(readings, &failures, &recorder()), format!( "{REVIEW}{FAILURES}\ casework_metrics_sample_failures_total{{sample=\"review\"}} 0\n\ - casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 2\n" + casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 2\n\ + {}", + refusal_series(None) ) ); } diff --git a/crates/registry-casework/tests/golden/refusal_responses.json b/crates/registry-casework/tests/golden/refusal_responses.json new file mode 100644 index 0000000000..cf90339a48 --- /dev/null +++ b/crates/registry-casework/tests/golden/refusal_responses.json @@ -0,0 +1,403 @@ +[ + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "no-authorization", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "basic-scheme", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "bearer-with-two-tokens", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "bearer-not-a-compact-token", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "bad-signature", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "wrong-audience", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "expired", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "missing-principal", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "act-on-officer-profile", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "grant-claims-on-officer-profile", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "unknown-profile", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "scope-missing", + "status": 403 + }, + { + "body": { + "code": "profile.not-human", + "detail": "This action is reserved for a human session.", + "status": 403, + "title": "Human session required", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-human" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "service-on-human-profile", + "status": 403 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "task-assertion-with-a-profile-header", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "task-assertion-no-authorization", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "task-assertion-bearer-not-a-compact-token", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "task-assertion-without-its-scope", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "delegated-read-with-a-profile-header", + "status": 403 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "delegated-read-no-authorization", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "delegated-read-unknown-policy", + "status": 403 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "source-bearer-with-two-tokens", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "source-bearer-not-a-compact-token", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "source-pair-on-a-requester-profile", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "source-bearer-refused-by-a-staff-profile-scope", + "status": 403 + } +] diff --git a/crates/registry-casework/tests/human_identity_auth.rs b/crates/registry-casework/tests/human_identity_auth.rs index 1d75c31ec5..f8d15638ac 100644 --- a/crates/registry-casework/tests/human_identity_auth.rs +++ b/crates/registry-casework/tests/human_identity_auth.rs @@ -7,6 +7,7 @@ use registry_casework_core::{ AccessProfile, CaseworkActsAs, CaseworkProject, InboxPolicy, ProjectIdentity, QueuePolicy, CASEWORK_API_VERSION, CASEWORK_KIND, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; use registry_platform_testing::{oidc_verifier_config, MockIdp}; @@ -56,7 +57,10 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .expect_err( "a service, missing, or non-string actor kind cannot produce an ActorContext", ); - assert_eq!(refusal, AuthenticationError::NotHuman); + assert_eq!( + refusal, + AuthenticationError::NotHuman(FailedCheck::ActorKind) + ); } let requester = authenticator @@ -81,7 +85,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&requester_with_human_assertion, human_profile) .await .expect_err("the dedicated Requester scope cannot select a human profile"), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::Scope) ); } @@ -93,7 +97,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv ) .await .expect_err("selecting Staff does not union the Requester scope or identity class"), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::Scope) ); let wrong_audience = idp.mint_token(json!({ @@ -107,7 +111,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&wrong_audience, "staff") .await .expect_err("the verifier preserves audience enforcement"), - AuthenticationError::Refused + AuthenticationError::Refused(FailedCheck::TokenAudience) ); let expired = idp.mint_token(json!({ @@ -122,7 +126,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&expired, "staff") .await .expect_err("the verifier preserves expiry enforcement"), - AuthenticationError::Refused + AuthenticationError::Refused(FailedCheck::TokenTime) ); assert_eq!( @@ -133,7 +137,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv ) .await .expect_err("the selected profile still requires its configured scope"), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::Scope) ); let missing_principal = idp.mint_token(json!({ @@ -146,7 +150,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&missing_principal, "staff") .await .expect_err("a human assertion cannot replace the configured principal claim"), - AuthenticationError::Claims + AuthenticationError::Claims(FailedCheck::TokenClaims) ); let custom_authenticator = authenticator_with_human_identity( @@ -173,7 +177,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&default_assertion_only, "staff") .await .expect_err("the default assertion cannot satisfy a custom claim contract"), - AuthenticationError::NotHuman + AuthenticationError::NotHuman(FailedCheck::ActorKind) ); idp.stop().await; @@ -208,7 +212,11 @@ async fn delegated_or_grant_bearing_tokens_are_refused_for_officer_profiles_only .authenticate(&idp.mint_token(claims), profile) .await .expect_err("delegated authority cannot enter an officer session"), - AuthenticationError::Refused + AuthenticationError::Refused(if extra.get("act").is_some() { + FailedCheck::Delegation + } else { + FailedCheck::TaskGrantClaims + }) ); } @@ -318,7 +326,7 @@ async fn same_role_profiles_on_one_principal_claim_are_selected_by_their_own_sco ) .await .expect_err("the scope of one staff profile cannot select the other"), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::Scope) ); let selected = authenticator .authenticate( diff --git a/crates/registry-casework/tests/refusal_golden.rs b/crates/registry-casework/tests/refusal_golden.rs new file mode 100644 index 0000000000..7a97bec77f --- /dev/null +++ b/crates/registry-casework/tests/refusal_golden.rs @@ -0,0 +1,556 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The authentication and profile refusals Casework answers on its HTTP +//! surface, frozen against a checked-in file. +//! +//! Each case drives the real router and records the status, the headers a +//! caller can act on, and the problem body with its `traceId` removed. A +//! change to what a caller sees changes `golden/refusal_responses.json`. +//! `REGISTRY_UPDATE_GOLDEN=1` rewrites the file, and a reviewer reads the +//! diff. +//! +//! Each case also checks what the operator sees: the refusal counts once under +//! its check, and writes one log line that names the check and nothing a +//! caller sent. +//! +//! The router's store points at a PostgreSQL address nothing listens on: +//! every case here is refused before a handler reaches the store. + +use std::path::PathBuf; +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, Response}; +use registry_casework::{ + router_with_recorder, CaseworkAuthenticator, CaseworkService, DatabaseConfig, HttpState, + HumanIdentityConfig, PostgresStore, +}; +use registry_casework_core::{ + AccessProfile, CaseworkActsAs, CaseworkProject, InboxPolicy, ProjectIdentity, QueuePolicy, + CASEWORK_API_VERSION, CASEWORK_KIND, +}; +use registry_platform_authcommon::{FailedCheck, RefusalRecorder}; +use registry_platform_config::{SecretProvider, SecretResolver}; +use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{oidc_verifier_config, CapturedDiagnosticLogs, MockIdp}; +use serde_json::{json, Map, Value}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber as _; + +const AUDIENCE: &str = "urn:test:casework"; +const PRINCIPAL: &str = "urn:test:person:refusal-golden"; +const PROFILE_HEADER: &str = "registry-casework-profile"; +const SOURCE_AUTHORIZATION_HEADER: &str = "registry-source-authorization"; +const SOURCE_PROFILE_HEADER: &str = "registry-source-profile"; +const DELEGATED_READER_HEADER: &str = "registry-casework-delegated-reader"; +const TASK_ID: &str = "00000000-0000-4000-8000-000000000001"; +const GRANT_ID: &str = "00000000-0000-4000-8000-000000000002"; + +struct Case { + name: &'static str, + /// The check the operator's counter and log line name for this refusal. + check: &'static str, + method: &'static str, + path: String, + headers: Vec<(&'static str, String)>, +} + +fn case( + name: &'static str, + check: &'static str, + method: &'static str, + path: &str, + headers: Vec<(&'static str, String)>, +) -> Case { + Case { + name, + check, + method, + path: path.to_owned(), + headers, + } +} + +fn bearer(token: &str) -> String { + format!("Bearer {token}") +} + +fn claims(scope: &str, kind: Option<&str>) -> Value { + let mut claims = json!({ + "aud": AUDIENCE, + "registry_principal": PRINCIPAL, + "scope": scope, + }); + if let Some(kind) = kind { + claims["registry_actor_kind"] = json!(kind); + } + claims +} + +fn with(mut claims: Value, extra: Value) -> Value { + claims + .as_object_mut() + .expect("claims are an object") + .extend(extra.as_object().expect("extra is an object").clone()); + claims +} + +fn cases(idp: &MockIdp) -> Vec { + let staff = idp.mint_token(claims("casework:staff", Some("human"))); + let service_on_staff = idp.mint_token(claims("casework:staff", Some("service"))); + let requester = idp.mint_token(claims("casework:request", Some("service"))); + let other_scope = idp.mint_token(claims("casework:unrelated", Some("human"))); + let wrong_audience = idp.mint_token(with( + claims("casework:staff", Some("human")), + json!({"aud": "urn:test:other-service"}), + )); + let expired = idp.mint_token(with( + claims("casework:staff", Some("human")), + json!({"exp": chrono::Utc::now().timestamp() - 120}), + )); + let no_principal = idp.mint_token(json!({ + "aud": AUDIENCE, + "scope": "casework:staff", + "registry_actor_kind": "human", + })); + let delegated = idp.mint_token(with( + claims("casework:staff", Some("human")), + json!({"act": {"sub": "agent"}}), + )); + let grant_bearing = idp.mint_token(with( + claims("casework:staff", Some("human")), + json!({"registry_grant_id": "grant"}), + )); + let mut bad_signature = staff.clone(); + let last = bad_signature.pop().expect("a token is not empty"); + bad_signature.push(if last == 'A' { 'B' } else { 'A' }); + + let list = "/v1/review-tasks"; + let as_staff = |token: &str| { + vec![ + ("authorization", bearer(token)), + (PROFILE_HEADER, "staff".to_owned()), + ] + }; + let assertion = format!("/v1/task-grants/{GRANT_ID}/assertion"); + let history = format!("/v1/review-requests/{TASK_ID}/history"); + vec![ + case( + "no-authorization", + "credential-missing", + "GET", + list, + vec![(PROFILE_HEADER, "staff".to_owned())], + ), + case( + "basic-scheme", + "credential-missing", + "GET", + list, + vec![ + ("authorization", "Basic abc".to_owned()), + (PROFILE_HEADER, "staff".to_owned()), + ], + ), + case( + "bearer-with-two-tokens", + "credential-malformed", + "GET", + list, + vec![ + ("authorization", "Bearer one two".to_owned()), + (PROFILE_HEADER, "staff".to_owned()), + ], + ), + case( + "bearer-not-a-compact-token", + "credential-malformed", + "GET", + list, + as_staff("not-a-token"), + ), + case( + "bad-signature", + "token-signature", + "GET", + list, + as_staff(&bad_signature), + ), + case( + "wrong-audience", + "token-audience", + "GET", + list, + as_staff(&wrong_audience), + ), + case("expired", "token-time", "GET", list, as_staff(&expired)), + case( + "missing-principal", + "token-claims", + "GET", + list, + as_staff(&no_principal), + ), + case( + "act-on-officer-profile", + "delegation", + "GET", + list, + as_staff(&delegated), + ), + case( + "grant-claims-on-officer-profile", + "task-grant-claims", + "GET", + list, + as_staff(&grant_bearing), + ), + case( + "unknown-profile", + "access-profile", + "GET", + list, + vec![ + ("authorization", bearer(&staff)), + (PROFILE_HEADER, "nobody".to_owned()), + ], + ), + case( + "scope-missing", + "scope", + "GET", + list, + as_staff(&other_scope), + ), + case( + "service-on-human-profile", + "actor-kind", + "GET", + list, + as_staff(&service_on_staff), + ), + case( + "task-assertion-with-a-profile-header", + "access-profile", + "POST", + &assertion, + as_staff(&staff), + ), + case( + "task-assertion-no-authorization", + "credential-missing", + "POST", + &assertion, + vec![], + ), + case( + "task-assertion-bearer-not-a-compact-token", + "credential-malformed", + "POST", + &assertion, + vec![("authorization", bearer("not-a-token"))], + ), + case( + "task-assertion-without-its-scope", + "scope", + "POST", + &assertion, + vec![("authorization", bearer(&staff))], + ), + case( + "delegated-read-with-a-profile-header", + "access-profile", + "GET", + "/v1/delegated-staff/review-tasks", + as_staff(&staff), + ), + case( + "delegated-read-no-authorization", + "credential-missing", + "GET", + "/v1/delegated-staff/review-tasks", + vec![(DELEGATED_READER_HEADER, "reader".to_owned())], + ), + case( + "delegated-read-unknown-policy", + "access-profile", + "GET", + "/v1/delegated-staff/review-tasks", + vec![ + ("authorization", bearer(&staff)), + (DELEGATED_READER_HEADER, "reader".to_owned()), + ], + ), + case( + "source-bearer-with-two-tokens", + "credential-malformed", + "GET", + &history, + vec![ + ("authorization", bearer(&staff)), + (PROFILE_HEADER, "staff".to_owned()), + (SOURCE_AUTHORIZATION_HEADER, "Bearer one two".to_owned()), + (SOURCE_PROFILE_HEADER, "review-agent".to_owned()), + ], + ), + case( + "source-bearer-not-a-compact-token", + "credential-malformed", + "GET", + &history, + vec![ + ("authorization", bearer(&staff)), + (PROFILE_HEADER, "staff".to_owned()), + (SOURCE_AUTHORIZATION_HEADER, bearer("not-a-token")), + (SOURCE_PROFILE_HEADER, "review-agent".to_owned()), + ], + ), + case( + "source-pair-on-a-requester-profile", + "access-profile", + "GET", + &history, + vec![ + ("authorization", bearer(&requester)), + (PROFILE_HEADER, "requester".to_owned()), + (SOURCE_AUTHORIZATION_HEADER, bearer(&staff)), + (SOURCE_PROFILE_HEADER, "review-agent".to_owned()), + ], + ), + case( + "source-bearer-refused-by-a-staff-profile-scope", + "scope", + "GET", + &history, + vec![ + ("authorization", bearer(&other_scope)), + (PROFILE_HEADER, "staff".to_owned()), + (SOURCE_AUTHORIZATION_HEADER, bearer(&staff)), + (SOURCE_PROFILE_HEADER, "review-agent".to_owned()), + ], + ), + ] +} + +fn profile(id: &str, scope: &str, role: CaseworkActsAs) -> AccessProfile { + AccessProfile { + id: id.to_owned(), + label: None, + description: None, + principal_claim: "registry_principal".to_owned(), + required_scopes: vec![scope.to_owned()], + acts_as: role, + } +} + +fn project() -> CaseworkProject { + let starter = CaseworkProject::from_slice(include_bytes!( + "../../../products/casework/examples/standalone-decision/casework.yaml" + )) + .expect("canonical review fixture"); + CaseworkProject { + task_templates: Vec::new(), + api_version: CASEWORK_API_VERSION.to_owned(), + kind: CASEWORK_KIND.to_owned(), + project: ProjectIdentity::new("refusal-golden-test".parse().unwrap(), "1".to_owned()), + access_profiles: vec![ + profile("staff", "casework:staff", CaseworkActsAs::Staff), + profile("requester", "casework:request", CaseworkActsAs::Requester), + ], + queues: vec![QueuePolicy { + id: "decisions".to_owned(), + label: "Decisions".to_owned(), + }], + teams: starter.teams, + context_providers: Vec::new(), + review_policies: starter.review_policies, + trusted_producers: starter.trusted_producers, + calendars: Vec::new(), + clocks: Vec::new(), + inbox: InboxPolicy::default(), + } +} + +/// A store whose pool has no server behind it. It connects only when used. +fn unconnected_store(root: &std::path::Path) -> PostgresStore { + use std::os::unix::fs::PermissionsExt as _; + let root = std::fs::canonicalize(root).expect("canonical secret root"); + let secrets_dir = root.join("secrets"); + std::fs::create_dir(&secrets_dir).expect("secret directory"); + std::fs::set_permissions(&secrets_dir, std::fs::Permissions::from_mode(0o700)) + .expect("private secret directory"); + let file = secrets_dir.join("database-url"); + std::fs::write(&file, "postgresql://casework@127.0.0.1:9/casework").expect("database url"); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)) + .expect("private database url"); + let secrets = + SecretResolver::new([SecretProvider::File], &secrets_dir).expect("secret resolver"); + PostgresStore::connect_runtime( + &DatabaseConfig { + runtime_url_ref: "secret:file/database-url".to_owned(), + migration_url_ref: "secret:file/database-url".to_owned(), + ca_bundle_ref: None, + test_only_plaintext: false, + }, + &secrets, + ) + .expect("an unconnected runtime store") +} + +fn app(idp: &MockIdp, root: &std::path::Path, recorder: Arc) -> axum::Router { + let project = project(); + let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::dev(), + )); + let authenticator = CaseworkAuthenticator::new( + &project, + oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]), + keys, + HumanIdentityConfig::default(), + ); + let service = CaseworkService::new(unconnected_store(root), project.clone(), []) + .expect("a service with no providers"); + router_with_recorder( + HttpState { + service, + authenticator: Arc::new(authenticator), + project: Arc::new(project), + }, + recorder, + ) +} + +const KEPT_HEADERS: [&str; 5] = [ + "content-type", + "www-authenticate", + "retry-after", + "cache-control", + "x-content-type-options", +]; + +async fn observe(app: &axum::Router, case: &Case) -> Value { + let mut request = Request::builder().method(case.method).uri(&case.path); + for (name, value) in &case.headers { + request = request.header(*name, value); + } + let response: Response = app + .clone() + .oneshot(request.body(Body::empty()).expect("request")) + .await + .expect("response"); + let status = response.status().as_u16(); + let mut headers = Map::new(); + for name in KEPT_HEADERS { + if let Some(value) = response.headers().get(name) { + headers.insert( + name.to_owned(), + json!(value.to_str().expect("a printable header")), + ); + } + } + let bytes = axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .expect("body"); + let mut body: Value = serde_json::from_slice(&bytes).expect("a JSON problem body"); + body.as_object_mut() + .expect("a problem object") + .remove("traceId") + .expect("every problem carries a traceId"); + json!({"name": case.name, "status": status, "headers": headers, "body": body}) +} + +fn golden_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusal_responses.json") +} + +#[tokio::test] +async fn authentication_and_profile_refusals_match_the_checked_in_answers() { + let idp = MockIdp::start().await; + let root = tempfile::tempdir().expect("temporary directory"); + let recorder = Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")); + let app = app(&idp, root.path(), Arc::clone(&recorder)); + let mut observed = Vec::new(); + let cases = cases(&idp); + let tokens: Vec = cases + .iter() + .flat_map(|case| case.headers.iter().map(|(_, value)| value.clone())) + .collect(); + for case in &cases { + let before = recorder + .counter() + .get(&[case.check]) + .expect("the check is declared"); + let logs = CapturedDiagnosticLogs::default(); + observed.push(observe(&app, case).with_subscriber(logs.subscriber()).await); + assert_eq!( + recorder.counter().get(&[case.check]), + Some(before + 1), + "{} counts once under {}", + case.name, + case.check + ); + assert_one_value_free_line(case, &logs, &tokens); + } + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, cases.len() as u64, "no refusal counted twice"); + idp.stop().await; + let observed = Value::Array(observed); + let rendered = format!("{}\n", serde_json::to_string_pretty(&observed).unwrap()); + if std::env::var_os("REGISTRY_UPDATE_GOLDEN").is_some() { + std::fs::write(golden_path(), rendered).expect("write the golden file"); + return; + } + let expected = std::fs::read_to_string(golden_path()).expect( + "tests/golden/refusal_responses.json is missing; run once with REGISTRY_UPDATE_GOLDEN=1", + ); + assert_eq!( + rendered, expected, + "a refusal answer changed; if the change is intended, rerun with REGISTRY_UPDATE_GOLDEN=1 and review the diff" + ); +} + +/// The one line a refusal wrote names the check, carries a trace id, and +/// holds no credential, claim or profile a caller sent. +fn assert_one_value_free_line(case: &Case, logs: &CapturedDiagnosticLogs, tokens: &[String]) { + let text = logs.text(); + let lines: Vec = text + .lines() + .map(|line| serde_json::from_str(line).expect("a JSON log line")) + .collect(); + assert_eq!(lines.len(), 1, "{}: {text}", case.name); + let fields = lines[0]["fields"].as_object().expect("fields"); + assert_eq!(fields["message"], "request refused", "{}", case.name); + assert_eq!(fields["decision"], "refused", "{}", case.name); + assert_eq!(fields["failed_check"], case.check, "{}", case.name); + assert_eq!(fields["suppressed"], 0, "{}", case.name); + assert_eq!( + fields["trace_id"].as_str().map(str::len), + Some(32), + "{}", + case.name + ); + for name in fields.keys() { + assert!( + [ + "message", + "decision", + "failed_check", + "suppressed", + "trace_id", + "remedy" + ] + .contains(&name.as_str()), + "{}: unexpected field {name}", + case.name + ); + } + for secret in tokens.iter().chain([&PRINCIPAL.to_owned()]) { + assert!(!text.contains(secret.as_str()), "{}: {secret}", case.name); + } +} diff --git a/crates/registry-casework/tests/token_characterisation.rs b/crates/registry-casework/tests/token_characterisation.rs index e39d93f719..bafbc2e4a8 100644 --- a/crates/registry-casework/tests/token_characterisation.rs +++ b/crates/registry-casework/tests/token_characterisation.rs @@ -11,20 +11,18 @@ use std::path::Path; use std::sync::Arc; -use registry_casework::{ - secret_resolver, AuthenticationError, CaseworkAuthenticator, RuntimeConfig, -}; +use registry_casework::{secret_resolver, CaseworkAuthenticator, RuntimeConfig}; use registry_casework_core::{ AccessProfile, CaseworkActsAs, CaseworkProject, InboxPolicy, ProjectIdentity, QueuePolicy, CASEWORK_API_VERSION, CASEWORK_KIND, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_oidc::JwksFetcher; use registry_platform_testing::{ - Against, CapturedDiagnosticLogs, ClaimValue, Configuration, FixtureCase, Outcome, Stage, - TokenCorpus, TokenFixture, TokenSigner, + Against, ClaimValue, Configuration, FixtureCase, Outcome, Stage, TokenCorpus, TokenFixture, + TokenSigner, }; use serde_json::{json, Value}; -use tracing::instrument::WithSubscriber; const ISSUER: &str = "https://issuer.example.test"; const AUDIENCE: &str = "urn:casework:test"; @@ -225,36 +223,31 @@ async fn observe(case: FixtureCase, secrets: &Secrets) -> Outcome { Against::PlainRead => "requester", Against::HumanOnlyProfile => "staff", }; - let logs = CapturedDiagnosticLogs::default(); - let result = authenticator + match authenticator .authenticate(case.token.expose(), profile) - .with_subscriber(logs.subscriber()) - .await; - match result { + .await + { Ok(_) => Outcome::Admitted(None), - Err(AuthenticationError::Claims) => Outcome::Refused(Stage::Claims), - Err( - AuthenticationError::Refused - | AuthenticationError::Profile - | AuthenticationError::NotHuman, - ) => logged_stage(&logs).map_or(Outcome::Unknown, Outcome::Refused), + Err(error) => Outcome::Refused(stage_of(error.failed_check())), } } -/// The stage of the one value-free diagnostic a refusal logged, when there is -/// exactly one. -fn logged_stage(logs: &CapturedDiagnosticLogs) -> Option { - let text = logs.text(); - let stages: Vec = text - .lines() - .filter_map(|line| serde_json::from_str::(line).ok()) - .filter_map(|line| line["fields"]["stage"].as_str().map(str::to_owned)) - .collect(); - match stages.as_slice() { - [stage] => match format!("refused/{stage}").parse::() { - Ok(Outcome::Refused(stage)) => Some(stage), - other => panic!("the logged stage is not a known stage: {other:?}"), - }, - _ => None, +/// The refusal stage the corpus names for the check a refusal failed. +fn stage_of(check: FailedCheck) -> Stage { + match check { + FailedCheck::CredentialMissing | FailedCheck::CredentialMalformed => Stage::Header, + FailedCheck::TokenAlgorithm => Stage::Algorithm, + FailedCheck::TokenType => Stage::TokenType, + FailedCheck::TokenKey => Stage::Key, + FailedCheck::TokenSignature => Stage::Signature, + FailedCheck::TokenIssuer => Stage::Issuer, + FailedCheck::TokenAudience => Stage::Audience, + FailedCheck::TokenTime => Stage::Time, + FailedCheck::TokenClient | FailedCheck::TokenAssertionIssuer => Stage::Client, + FailedCheck::Scope => Stage::Scope, + FailedCheck::AccessProfile | FailedCheck::ActorKind => Stage::Profile, + FailedCheck::KeySourceUnavailable => Stage::Unavailable, + FailedCheck::TokenClaims => Stage::Claims, + other => panic!("the corpus has no stage for the check {}", other.as_str()), } } diff --git a/crates/registry-coordinator/Cargo.toml b/crates/registry-coordinator/Cargo.toml index 35037fb3d7..029a70cf61 100644 --- a/crates/registry-coordinator/Cargo.toml +++ b/crates/registry-coordinator/Cargo.toml @@ -147,10 +147,10 @@ registry-platform-activation.workspace = true registry-platform-audit.workspace = true registry-platform-oidc.workspace = true registry-platform-provision = { workspace = true, features = ["cli"] } -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-calendar.workspace = true -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-metrics.workspace = true jsonwebtoken.workspace = true registry-platform-canonical-json.workspace = true diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index c8e05f3a53..20e8818842 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Verified access-token ownership and exact deployment policy matching. use crate::{store::Actor, CoordinatorError, Result}; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::{ JwksSource, OidcClientsConfig, OidcIssuerConfig, SecretProvidersConfig, }; @@ -397,7 +398,7 @@ impl Caller { if !self.policy.actions.contains(&action) || workflow.is_some_and(|workflow| !self.policy.workflows.iter().any(|f| f == workflow)) { - return Err(denied()); + return Err(denied(FailedCheck::Operation)); } Ok(()) } @@ -411,16 +412,37 @@ impl Caller { || !self.policy.operator || !self.policy.actions.contains(&action) { - return Err(denied()); + return Err(denied(FailedCheck::Operation)); } Ok(()) } } -fn denied() -> CoordinatorError { +/// A resolved caller for tests that need no token: the policy lists +/// `actions` on `workflows`. +#[cfg(test)] +pub(crate) fn synthetic_caller(actions: Vec, workflows: &[&str], operator: bool) -> Caller { + Caller { + actor: Actor { + issuer: "https://issuer.example".into(), + subject: "subject".into(), + client_id: "client".into(), + operator, + }, + policy: ClientPolicy { + subjects: vec!["subject".into()], + required_scopes: vec!["coordinator:operate".into()], + workflows: workflows.iter().map(|w| (*w).to_owned()).collect(), + actions, + operator, + }, + } +} +fn denied(check: FailedCheck) -> CoordinatorError { CoordinatorError::new( "access.denied", "the caller policy does not authorize this operation", ) + .failing(check) } /// The bound admission puts on a token subject, and so on every subject a /// policy may list: non-empty, at most 512 bytes, no control characters. @@ -442,7 +464,7 @@ impl Authenticator { } pub async fn authenticate(&self, token: &str) -> Result { registry_platform_authcommon::validate_compact_access_token(token) - .map_err(|_| unauthenticated())?; + .map_err(|_| unauthenticated(FailedCheck::CredentialMalformed))?; let verified = self.verifier.verify(token).await.map_err(|error| { use registry_platform_oidc::OidcError; match error { @@ -458,45 +480,48 @@ impl Authenticator { | OidcError::ConflictingEndpointConfiguration => CoordinatorError::new( "access.unavailable", "the configured verifier cannot answer", - ), - _ => unauthenticated(), + ) + .failing(FailedCheck::KeySourceUnavailable), + _ => unauthenticated(error.failed_check()), } })?; if !self.assertion_issuers && verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - return Err(unauthenticated()); + return Err(unauthenticated(FailedCheck::TokenAssertionIssuer)); } let client = verified .matched_client_id() - .map_err(|_| unauthenticated())? - .ok_or_else(unauthenticated)?; + .map_err(|_| unauthenticated(FailedCheck::TokenClient))? + .ok_or_else(|| unauthenticated(FailedCheck::TokenClient))?; let issuer = verified .claims .iss .as_deref() .filter(|s| !s.is_empty()) - .ok_or_else(unauthenticated)?; + .ok_or_else(|| unauthenticated(FailedCheck::TokenClaims))?; let subject = verified .claims .sub .as_deref() .filter(|s| admitted_subject(s)) - .ok_or_else(unauthenticated)?; + .ok_or_else(|| unauthenticated(FailedCheck::TokenClaims))?; // A token carrying `act` was issued for someone other than the client // that presents it, typically a person delegated to that client. The // Coordinator admits only a client's own identities. if verified.claims.extra.contains_key("act") { - return Err(denied()); + return Err(denied(FailedCheck::Delegation)); } let p = self .policies .get(client) .filter(|p| p.subjects.iter().any(|s| s == subject)) - .filter(|p| { - p.required_scopes - .iter() - .all(|s| verified.scopes.contains(s)) - }) - .ok_or_else(denied)?; + .ok_or_else(|| denied(FailedCheck::AccessProfile))?; + if !p + .required_scopes + .iter() + .all(|s| verified.scopes.contains(s)) + { + return Err(denied(FailedCheck::Scope)); + } Ok(Caller { actor: Actor { issuer: issuer.into(), @@ -522,11 +547,12 @@ fn access_error(field: &str, advice: &str) -> CoordinatorError { .at("runtime.yaml", crate::runtime::pointer(field)) .suggest(advice) } -fn unauthenticated() -> CoordinatorError { +pub(crate) fn unauthenticated(check: FailedCheck) -> CoordinatorError { CoordinatorError::new( "access.unauthenticated", "a verified access token is required", ) + .failing(check) } fn unique_actions<'de, D: Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { @@ -566,24 +592,7 @@ mod tests { use registry_platform_yaml::Url; fn caller(actions: Vec, workflows: &[&str], operator: bool) -> Caller { - Caller { - actor: Actor { - issuer: "https://issuer.example".into(), - subject: "subject".into(), - client_id: "client".into(), - operator, - }, - policy: ClientPolicy { - subjects: vec!["subject".into()], - required_scopes: vec!["coordinator:operate".into()], - workflows: workflows - .iter() - .map(|workflow| (*workflow).to_owned()) - .collect(), - actions, - operator, - }, - } + synthetic_caller(actions, workflows, operator) } #[test] @@ -645,4 +654,21 @@ mod tests { ["workflow-a"] ); } + + #[test] + fn a_policy_denial_after_authentication_names_the_operation_check() { + let scoped = caller(vec![Action::Status, Action::Doctor], &["workflow-a"], true); + let not_operator = caller(vec![Action::Doctor], &[], false); + for denial in [ + scoped.authorize(Action::Start, Some("workflow-a")), + scoped.authorize(Action::Status, Some("workflow-b")), + scoped.authorized_workflows(Action::Start).map(|_| ()), + scoped.authorize_deployment(Action::Status), + not_operator.authorize_deployment(Action::Doctor), + ] { + let denial = denial.unwrap_err(); + assert_eq!(denial.code, "access.denied"); + assert_eq!(denial.check, Some(FailedCheck::Operation)); + } + } } diff --git a/crates/registry-coordinator/src/access/token_characterisation.rs b/crates/registry-coordinator/src/access/token_characterisation.rs index fbfe89735e..b93c7d5baf 100644 --- a/crates/registry-coordinator/src/access/token_characterisation.rs +++ b/crates/registry-coordinator/src/access/token_characterisation.rs @@ -7,8 +7,8 @@ //! `AccessConfig::authenticator`, over a static key set holding the corpus //! signer's public keys, and presents the fixture to `Authenticator::authenticate`. //! The module sits under `access` so it can also ask the authenticator's own -//! verifier for the check that refused a token: the service answers every -//! refusal with `access.unauthenticated`, which names no check. +//! verifier for the check that refused a token and compare it with the check +//! the refusal carries. use super::*; use registry_platform_oidc::OidcError; use registry_platform_testing::{ @@ -86,13 +86,45 @@ async fn observe(authenticator: &Authenticator, token: &str) -> Outcome { match (admission, verdict) { (Ok(_), Ok(_)) => Outcome::Admitted(None), (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), - (Err(_), Err(error)) => stage_of(&error), - (Err(error), Ok(_)) => match error.code.as_str() { - "access.denied" => "refused/scope".parse().expect("result value"), - "access.unauthenticated" => "refused/claims".parse().expect("result value"), - "access.unavailable" => "refused/unavailable".parse().expect("result value"), - other => panic!("authenticate refused with the unexpected code {other}"), - }, + (Err(refusal), Err(error)) => { + assert_eq!( + refusal.check, + Some(error.failed_check()), + "the refusal names the verifier's check" + ); + stage_of(&error) + } + (Err(error), Ok(_)) => { + let (outcome, checks): (_, &[FailedCheck]) = match error.code.as_str() { + "access.denied" => ( + "refused/scope", + &[ + FailedCheck::Delegation, + FailedCheck::AccessProfile, + FailedCheck::Scope, + ], + ), + "access.unauthenticated" => ( + "refused/claims", + &[ + FailedCheck::TokenAssertionIssuer, + FailedCheck::TokenClient, + FailedCheck::TokenClaims, + ], + ), + "access.unavailable" => { + ("refused/unavailable", &[FailedCheck::KeySourceUnavailable]) + } + other => panic!("authenticate refused with the unexpected code {other}"), + }; + assert!( + error.check.is_some_and(|check| checks.contains(&check)), + "{} carries a check from {checks:?}, not {:?}", + error.code, + error.check + ); + outcome.parse().expect("result value") + } } } diff --git a/crates/registry-coordinator/src/cli.rs b/crates/registry-coordinator/src/cli.rs index 3526a4d134..55aec2e155 100644 --- a/crates/registry-coordinator/src/cli.rs +++ b/crates/registry-coordinator/src/cli.rs @@ -633,8 +633,12 @@ async fn remote( .suggest("Add --url with the Coordinator service origin, such as --url https://coordinator.example.org.") })?; let loopback = match url.host() { - Some(url::Host::Ipv4(ip)) => ip.is_loopback(), - Some(url::Host::Ipv6(ip)) => ip.is_loopback(), + Some(url::Host::Ipv4(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } + Some(url::Host::Ipv6(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } _ => false, }; if !(url.scheme() == "https" || url.scheme() == "http" && loopback) diff --git a/crates/registry-coordinator/src/completion.rs b/crates/registry-coordinator/src/completion.rs index a12923ec35..936387c9b7 100644 --- a/crates/registry-coordinator/src/completion.rs +++ b/crates/registry-coordinator/src/completion.rs @@ -5,7 +5,7 @@ //! the connection's producer credential, and only that read can settle it. use crate::{ - http::{problem, single_header}, + http::{bearer_token, problem, single_header}, metrics::AuthenticationRefusal, protocol::AdapterSet, store::Store, @@ -16,6 +16,7 @@ use axum::{ response::{IntoResponse, Response}, }; use chrono::{DateTime, Utc}; +use registry_platform_authcommon::FailedCheck; use registry_review_protocol::ReviewCompletion; use uuid::Uuid; @@ -122,19 +123,22 @@ pub(crate) fn authenticate( body: Option<&[u8]>, now: DateTime, ) -> Result<(String, Uuid), CoordinatorError> { - let refused = || { + let refused = |check: FailedCheck| { CoordinatorError::new( "access.unauthenticated", "a configured completion credential and recipient binding are required", ) + .failing(check) }; - let token = single_header(headers, header::AUTHORIZATION.as_str()) - .and_then(|value| registry_platform_authcommon::parse_bearer_token(value).ok()) - .ok_or_else(refused)?; - let recipient = single_header(headers, RECIPIENT_BINDING_HEADER).ok_or_else(refused)?; + let token = bearer_token(headers).map_err(refused)?; + if !headers.contains_key(RECIPIENT_BINDING_HEADER) { + return Err(refused(FailedCheck::CredentialMissing)); + } + let recipient = single_header(headers, RECIPIENT_BINDING_HEADER) + .ok_or_else(|| refused(FailedCheck::CredentialMalformed))?; let connection = adapters .review_completion(token, recipient) - .ok_or_else(refused)?; + .ok_or_else(|| refused(FailedCheck::SharedSecret))?; if single_header(headers, header::CONTENT_TYPE.as_str()) != Some("application/json") { return Err(CoordinatorError::new( "request.content-type-invalid", @@ -298,6 +302,54 @@ mod tests { } } + #[test] + fn a_refused_sender_names_the_check_that_failed() { + let event = Uuid::new_v4(); + let mut forged = headers(event); + forged.insert( + header::AUTHORIZATION, + HeaderValue::from_static("Bearer another-synthetic-token-0123456789"), + ); + let mut basic = headers(event); + basic.insert( + header::AUTHORIZATION, + HeaderValue::from_static("Basic c3ludGhldGlj"), + ); + let mut absent = headers(event); + absent.remove(header::AUTHORIZATION); + let mut doubled = headers(event); + doubled.append( + header::AUTHORIZATION, + HeaderValue::from_static("Bearer another-synthetic-token-0123456789"), + ); + let mut other = headers(event); + other.insert( + RECIPIENT_BINDING_HEADER, + HeaderValue::from_static("another-recipient"), + ); + let mut unbound = headers(event); + unbound.remove(RECIPIENT_BINDING_HEADER); + let mut two = headers(event); + two.append( + RECIPIENT_BINDING_HEADER, + HeaderValue::from_static(RECIPIENT), + ); + for (case, headers, check) in [ + ("forged token", forged, FailedCheck::SharedSecret), + ("another scheme", basic, FailedCheck::CredentialMissing), + ("no credential", absent, FailedCheck::CredentialMissing), + ("two credentials", doubled, FailedCheck::CredentialMalformed), + ("another recipient", other, FailedCheck::SharedSecret), + ("no recipient", unbound, FailedCheck::CredentialMissing), + ("two recipients", two, FailedCheck::CredentialMalformed), + ] { + let refusal = + authenticate(&Receiver, &headers, Some(b"{"), Utc::now()).expect_err("refused"); + assert_eq!(refusal.code, "access.unauthenticated", "{case}"); + assert_eq!(refusal.check, Some(check), "{case}"); + } + } + #[test] fn an_authenticated_event_needs_exactly_the_json_media_type() { let (event, now) = (Uuid::new_v4(), Utc::now()); diff --git a/crates/registry-coordinator/src/decision.rs b/crates/registry-coordinator/src/decision.rs index c75a87f5c5..aef7386bd6 100644 --- a/crates/registry-coordinator/src/decision.rs +++ b/crates/registry-coordinator/src/decision.rs @@ -92,8 +92,12 @@ impl DecisionConfig { pub fn findings(&self, prefix: &str) -> Vec { let loopback = match self.base_url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Ipv4(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } + Some(Host::Ipv6(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } _ => false, }; let mut errors = Vec::new(); diff --git a/crates/registry-coordinator/src/error.rs b/crates/registry-coordinator/src/error.rs index 965a82973d..acd1255c2a 100644 --- a/crates/registry-coordinator/src/error.rs +++ b/crates/registry-coordinator/src/error.rs @@ -1,4 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 +use registry_platform_authcommon::FailedCheck; use registry_platform_yaml::{Diagnostic, Report, Severity}; use std::path::{Path, PathBuf}; @@ -15,6 +16,10 @@ pub struct CoordinatorError { pub suggested_action: Option>, pub diagnostics: Box<[Diagnostic]>, pub exit_code: u8, + /// The check that refused a caller, set by the constructors of the + /// authentication, authorization and event-delivery refusals and read + /// where the refusal is answered. A fixed member, never a caller value. + pub check: Option, } impl CoordinatorError { @@ -30,6 +35,7 @@ impl CoordinatorError { "service-unavailable" | "output-unavailable" | "definition.read" => 3, _ => 1, }, + check: None, } } /// Preserve all shared-reader findings and their authored positions. @@ -62,8 +68,15 @@ impl CoordinatorError { } else { 1 }, + check: None, } } + /// Name the check that refused the caller. + #[must_use] + pub(crate) fn failing(mut self, check: FailedCheck) -> Self { + self.check = Some(check); + self + } pub(crate) fn with_exit(mut self, exit_code: u8) -> Self { self.exit_code = exit_code; self diff --git a/crates/registry-coordinator/src/event_trigger.rs b/crates/registry-coordinator/src/event_trigger.rs index 37bdb4586a..1fd94b6cf4 100644 --- a/crates/registry-coordinator/src/event_trigger.rs +++ b/crates/registry-coordinator/src/event_trigger.rs @@ -17,13 +17,14 @@ use axum::{ http::{HeaderMap, HeaderValue, Method, StatusCode}, response::{IntoResponse, Response}, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::{sha256_uri, SecretProvidersConfig, SecretReference}; use registry_platform_crypto::delivery_signature::{MAX_BODY_BYTES, MIN_HMAC_SHA256_KEY_BYTES}; use registry_platform_dispatch::idempotency_key; use registry_platform_hooks::{ receiver::{ - verify_delivery as verify_signed_delivery, DeliveryFreshness, SignedDelivery, - VerifiedDelivery, + verify_delivery as verify_signed_delivery, DeliveryFreshness, ReceiverError, + SignedDelivery, VerifiedDelivery, }, EnvelopeLimits, HookEnvelope, }; @@ -291,7 +292,14 @@ pub fn verify_delivery( skew: DELIVERY_SKEW, }, ) - .map_err(|_| unauthenticated())?; + .map_err(|error| { + unauthenticated(match error { + ReceiverError::Stale | ReceiverError::InvalidDeliveryTime => { + FailedCheck::DeliveryFreshness + } + _ => FailedCheck::DeliverySignature, + }) + })?; if content_type != "application/json" || event_source != source.source.as_ref() || trigger.source != source_name @@ -300,7 +308,7 @@ pub fn verify_delivery( || delivery_key.is_empty() || delivery_key.len() > 256 { - return Err(unauthenticated()); + return Err(unauthenticated(FailedCheck::DeliveryBinding)); } let envelope = HookEnvelope::from_canonical_bytes( body, @@ -371,13 +379,13 @@ pub async fn receive( let package = state .workflows .get(&workflow_name) - .ok_or_else(unauthenticated)?; + .ok_or_else(|| unauthenticated(FailedCheck::DeliveryBinding))?; let trigger = package .definition .workflow .event_triggers .get(&trigger_name) - .ok_or_else(unauthenticated)?; + .ok_or_else(|| unauthenticated(FailedCheck::DeliveryBinding))?; let source = state .runtime .event_sources @@ -475,11 +483,12 @@ fn body_too_large() -> CoordinatorError { ), ) } -fn unauthenticated() -> CoordinatorError { +fn unauthenticated(check: FailedCheck) -> CoordinatorError { CoordinatorError::new( "event-unauthenticated", "a fresh signed delivery from the configured event source is required", ) + .failing(check) } fn source_unavailable() -> CoordinatorError { CoordinatorError::new( diff --git a/crates/registry-coordinator/src/event_trigger_tests.rs b/crates/registry-coordinator/src/event_trigger_tests.rs index 97a92da81a..b745c786c5 100644 --- a/crates/registry-coordinator/src/event_trigger_tests.rs +++ b/crates/registry-coordinator/src/event_trigger_tests.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 use super::*; +use registry_platform_authcommon::RefusalNote; use registry_platform_canonical_json::canonicalize_json; use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields}; use serde_json::json; @@ -121,7 +122,7 @@ fn verify(body: &[u8], headers: &HeaderMap) -> Result { #[test] fn event_authentication_challenges_the_signature_transport() { - let response = event_problem(unauthenticated()); + let response = event_problem(unauthenticated(FailedCheck::DeliverySignature)); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); assert_eq!( response.headers()[axum::http::header::WWW_AUTHENTICATE], @@ -324,6 +325,89 @@ fn substituted_signature_destination_source_and_contract_are_refused() { ); } +#[test] +fn a_refused_delivery_names_the_check_that_failed() { + let value = event(); + let (body, original) = signed(&value, TARGET, 1, "delivery"); + let refusal = |headers: &HeaderMap| verify(&body, headers).err().expect("refused"); + for (name, replacement) in [ + ( + "x-registry-signature", + "v1=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + ), + ("ce-specversion", "0.3"), + ("x-registry-event-generation", "0"), + ] { + let mut headers = original.clone(); + headers.insert(name, HeaderValue::from_static(replacement)); + assert_eq!(refusal(&headers).code, "event-unauthenticated", "{name}"); + assert_eq!( + refusal(&headers).check, + Some(FailedCheck::DeliverySignature), + "{name}" + ); + } + let mut duplicate = original.clone(); + duplicate.append("ce-source", HeaderValue::from_static(BREG_SOURCE)); + assert_eq!( + refusal(&duplicate).check, + Some(FailedCheck::DeliverySignature) + ); + let wrong_target = verify_delivery( + &source(), + "registry", + &trigger(), + "record-saved", + &Method::POST, + "/different-target", + &original, + &body, + KEY, + SystemTime::now(), + ) + .err() + .expect("a signature over another target is refused"); + assert_eq!(wrong_target.check, Some(FailedCheck::DeliverySignature)); + + let mut stale = original.clone(); + stale.insert( + "x-registry-delivery-time", + HeaderValue::from_static("2020-01-01T00:00:00Z"), + ); + sign_headers(&mut stale, &body, TARGET); + assert_eq!(refusal(&stale).check, Some(FailedCheck::DeliveryFreshness)); + + // Authentic deliveries that name another source, type or schema. + for (name, replacement) in [ + ("ce-source", "urn:example:another-source"), + ("ce-type", "another-event-v1"), + ("ce-dataschema", "urn:example:another-schema"), + ] { + let mut headers = original.clone(); + headers.insert(name, HeaderValue::from_static(replacement)); + sign_headers(&mut headers, &body, TARGET); + let error = refusal(&headers); + assert_eq!(error.code, "event-unauthenticated", "{name}"); + assert_eq!(error.check, Some(FailedCheck::DeliveryBinding), "{name}"); + } +} + +#[test] +fn an_event_refusal_carries_its_check_in_the_response_extensions() { + for check in [ + FailedCheck::DeliverySignature, + FailedCheck::DeliveryFreshness, + FailedCheck::DeliveryBinding, + ] { + let response = event_problem(unauthenticated(check)); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!( + response.extensions().get::().map(|n| n.check), + Some(check) + ); + } +} + #[test] fn stale_delivery_noncanonical_body_and_header_body_disagreement_are_refused() { let value = event(); diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index ba02c61ff5..a7c34b1f37 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -102,8 +102,12 @@ impl ExternalHttpConfig { }; let base = ServiceBaseUrl::new(self.base_url.clone()); let numeric_loopback = match self.base_url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Ipv4(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } + Some(Host::Ipv6(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } _ => false, }; if base.is_err() || (self.base_url.scheme() == "http" && !numeric_loopback) { diff --git a/crates/registry-coordinator/src/http.rs b/crates/registry-coordinator/src/http.rs index 0a08d316bf..2e973d55f7 100644 --- a/crates/registry-coordinator/src/http.rs +++ b/crates/registry-coordinator/src/http.rs @@ -25,6 +25,9 @@ use axum::{ routing::{get, post}, Json, Router, }; +use registry_platform_authcommon::{ + record_refusal, BearerParseError, FailedCheck, RefusalNote, RefusalRecorder, +}; use registry_platform_httpsec::{ normalize_framework_rejection, FrameworkRejection, ProblemBody, TraceContext, }; @@ -119,6 +122,7 @@ where } } pub fn router(state: HttpState) -> Router { + let refusals = state.store.metrics().refusal_recorder().clone(); let ready_state = state.clone(); let ready_bindings = Arc::new(BindingReadiness::default()); let routes = Router::new() @@ -152,12 +156,12 @@ pub fn router(state: HttpState) -> Router { post(crate::event_trigger::receive), ) .with_state(state); - http_edge(routes, signed_events) + http_edge(routes, signed_events, refusals) } /// Every route takes at most 128 KiB, except the signed event route, which /// takes up to the Version 1 signable bound so every event a producer can sign /// reaches the verifier. -fn http_edge(router: Router, signed_events: Router) -> Router { +fn http_edge(router: Router, signed_events: Router, refusals: Arc) -> Router { let signable = crate::event_trigger::MAXIMUM_EVENT_BYTES; router .layer(DefaultBodyLimit::max(131_072)) @@ -169,6 +173,7 @@ fn http_edge(router: Router, signed_events: Router) -> Router { ) .fallback(route_not_found) .method_not_allowed_fallback(method_not_allowed) + .layer(middleware::from_fn_with_state(refusals, record_refusals)) .layer(middleware::from_fn(http_boundary)) .layer(registry_platform_httpsec::security_headers( registry_platform_httpsec::CspBuilder::deny_by_default(), @@ -187,6 +192,22 @@ async fn http_boundary(request: axum::http::Request, next: Nex .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); response } +/// The one point where a refusal is counted and logged. A refusal answer +/// carries a `RefusalNote` in its response extensions, which is not part of +/// the serialized answer. The log line carries the fixed check and the request +/// trace, so it runs inside the request's trace scope and outside any span. +async fn record_refusals( + State(refusals): State>, + request: axum::http::Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::() { + let trace = current_trace(); + record_refusal!(refusals, *note, trace_id = trace.trace_id); + } + response +} /// Framework rejections carry axum's own bodies, which no Coordinator caller /// was promised. The statuses are kept; the body becomes the vocabulary's /// `request.*` problem for that status. @@ -226,7 +247,36 @@ pub(crate) fn problem(error: CoordinatorError) -> Response { "the service answered a server problem" ); } - problem_response(problem) + let check = refusal_check(&error, problem); + let mut response = problem_response(problem); + if let Some(check) = check { + response.extensions_mut().insert(RefusalNote::new(check)); + } + response +} +/// The check that refused the caller, for the answers that refuse one: a 401 +/// or 403, a service outage of the token verifier, and a concealed run. A run +/// that is absent or not visible is one code in every store path, so the +/// member is set here. Any other refusal must carry its member from the +/// constructor; one that does not is a defect and is reported, not counted +/// under a guess. +fn refusal_check(error: &CoordinatorError, problem: ProblemCode) -> Option { + if error.check.is_some() { + return error.check; + } + match problem { + ProblemCode::RunNotVisible => Some(FailedCheck::Visibility), + ProblemCode::AuthenticationRefused + | ProblemCode::OperationNotAuthorized + | ProblemCode::EventUnauthenticated => { + tracing::error!( + code = %error.code, + "a caller refusal carries no failed check and was not counted" + ); + None + } + _ => None, + } } pub(crate) fn current_trace() -> TraceContext { REQUEST_TRACE @@ -322,16 +372,28 @@ pub(crate) async fn caller(s: &HttpState, headers: &HeaderMap) -> Result result } async fn authenticated_caller(s: &HttpState, headers: &HeaderMap) -> Result { - let token = single_header(headers, axum::http::header::AUTHORIZATION.as_str()) - .and_then(|value| registry_platform_authcommon::parse_bearer_token(value).ok()) - .ok_or_else(|| { - CoordinatorError::new( - "access.unauthenticated", - "a verified access token is required", - ) - })?; + let token = bearer_token(headers).map_err(crate::access::unauthenticated)?; s.authenticator.authenticate(token).await } +/// The bearer credential an `Authorization` header carries, or the check that +/// refuses it: no header, or not the Bearer scheme, is a missing credential. A +/// repeated, unreadable or misshapen header is a malformed one. +pub(crate) fn bearer_token(headers: &HeaderMap) -> std::result::Result<&str, FailedCheck> { + let mut values = headers.get_all(axum::http::header::AUTHORIZATION).iter(); + let Some(value) = values.next() else { + return Err(FailedCheck::CredentialMissing); + }; + if values.next().is_some() { + return Err(FailedCheck::CredentialMalformed); + } + let value = value + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + registry_platform_authcommon::parse_bearer_token(value).map_err(|error| match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) +} /// The shared probe object with the member this service has always answered. fn probe_body(shared: &str, member: &str) -> Value { let mut body: Value = serde_json::from_str(shared).expect("shared probe bodies are JSON"); @@ -674,6 +736,7 @@ mod problem_tests { }), ), Router::new(), + Arc::new(RefusalRecorder::new("coordinator").unwrap()), ) }; let traceparent = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"; @@ -725,6 +788,7 @@ mod problem_tests { "/v1/events/{workflow}/{trigger}", post(|body: axum::body::Bytes| async move { body.len().to_string() }), ), + Arc::new(RefusalRecorder::new("coordinator").unwrap()), ) }; let signable = crate::event_trigger::MAXIMUM_EVENT_BYTES; @@ -1877,3 +1941,264 @@ pub fn openapi() -> Value { admission_contracts::extend(&mut paths, &mut schemas); json!({"openapi":"3.1.0","info":{"title":"Registry Coordinator","version":env!("CARGO_PKG_VERSION"),"description":"Registry Coordinator HTTP contract. Refusals use the closed problem vocabulary."},"components":{"securitySchemes":{"bearer":{"type":"http","scheme":"bearer","bearerFormat":"JWT"},"reviewCompletion":{"type":"http","scheme":"bearer","description":"The completion credential configured for a Casework review connection, presented with its recipient binding."},"eventSource":{"type":"apiKey","in":"header","name":"X-Registry-Signature","description":"The platform v1 HMAC delivery signature, bound to the canonical envelope, signed delivery headers, HTTP method and exact request target. The configured event source key is separate from caller bearer tokens."}},"schemas":schemas},"paths":paths}) } + +#[cfg(test)] +mod refusal_recording_tests { + use super::*; + use registry_platform_metrics::Exposition; + use std::sync::Mutex; + + /// A value no refusal may carry into the counter or the log. + const CANARY: &str = "canary-subject-7f3a91"; + + #[derive(Clone, Default)] + struct Captured(Arc>>); + impl std::io::Write for Captured { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + fn exposition(recorder: &RefusalRecorder) -> String { + let mut out = Exposition::new(); + recorder.counter().write(&mut out).unwrap(); + out.finish() + } + + /// Send one request through the edge. Returns the status, the body, the + /// counter exposition and the captured log. + async fn refused(error: CoordinatorError) -> (StatusCode, Value, String, String) { + use tower::ServiceExt as _; + let recorder = Arc::new(RefusalRecorder::new("coordinator").unwrap()); + let error = Arc::new(Mutex::new(Some(error))); + let app = http_edge( + Router::new().route( + "/v1/refuse", + get(move || async move { problem(error.lock().unwrap().take().unwrap()) }), + ), + Router::new(), + recorder.clone(), + ); + let captured = Captured::default(); + let writer = captured.clone(); + let subscriber = tracing_subscriber::fmt() + .with_writer(move || writer.clone()) + .with_ansi(false) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let response = app + .oneshot( + axum::http::Request::builder() + .uri("/v1/refuse") + .header( + "traceparent", + "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", + ) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 65_536) + .await + .unwrap(); + let body = serde_json::from_slice(&bytes).unwrap(); + let log = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap(); + (status, body, exposition(&recorder), log) + } + + #[tokio::test] + async fn every_refusal_the_service_answers_is_counted_and_logged_under_its_check() { + for (error, status, code, check) in [ + ( + crate::access::unauthenticated(FailedCheck::CredentialMissing), + 401, + "authentication.refused", + "credential-missing", + ), + ( + crate::access::unauthenticated(FailedCheck::TokenSignature), + 401, + "authentication.refused", + "token-signature", + ), + ( + CoordinatorError::new("access.unavailable", CANARY) + .failing(FailedCheck::KeySourceUnavailable), + 503, + "service.unavailable", + "key-source-unavailable", + ), + ( + CoordinatorError::new("access.denied", CANARY).failing(FailedCheck::Operation), + 403, + "operation.not-authorized", + "operation", + ), + ( + CoordinatorError::new("access.denied", CANARY).failing(FailedCheck::Scope), + 403, + "operation.not-authorized", + "scope", + ), + ( + CoordinatorError::new("event-unauthenticated", CANARY) + .failing(FailedCheck::DeliverySignature), + 401, + "event.unauthenticated", + "delivery-signature", + ), + ( + // Every store path raises this one code for a run the caller + // cannot see, so the member is set where the answer is made. + CoordinatorError::new("run-absent", CANARY), + 404, + "run.not-visible", + "visibility", + ), + ] { + let (answered, body, counters, log) = refused(error).await; + assert_eq!(answered.as_u16(), status, "{check}"); + assert_eq!(body["code"], code, "{check}"); + assert_eq!(body["traceId"], "0af7651916cd43dd8448eb211c80319c"); + assert!( + counters.lines().any(|line| line + == format!("coordinator_request_refusals_total{{check=\"{check}\"}} 1")), + "{check}: {counters}" + ); + assert_eq!( + counters.lines().filter(|line| line.ends_with(" 1")).count(), + 1, + "{check}: one series moved" + ); + assert_eq!( + log.lines() + .filter(|line| line.contains("request refused")) + .count(), + 1, + "{check}: {log}" + ); + for field in [ + "request refused", + "decision=\"refused\"", + &format!("failed_check=\"{check}\""), + "suppressed=0", + "trace_id=0af7651916cd43dd8448eb211c80319c", + ] { + assert!(log.contains(field), "{check}: {field} in {log}"); + } + assert!(!log.contains(CANARY), "{check}: {log}"); + assert!(!body.to_string().contains(CANARY), "{check}"); + } + } + + #[tokio::test] + async fn an_answer_that_is_not_a_caller_refusal_is_not_counted() { + for error in [ + CoordinatorError::new("request.invalid", CANARY), + CoordinatorError::new("store-unavailable", CANARY), + ] { + let (_, _, counters, log) = refused(error).await; + assert!( + counters + .lines() + .all(|line| line.starts_with('#') || line.ends_with(" 0")), + "{counters}" + ); + assert!(!log.contains("request refused"), "{log}"); + } + } + + #[tokio::test] + async fn a_caller_refusal_without_a_check_is_reported_and_not_counted_under_a_guess() { + let (status, _, counters, log) = + refused(CoordinatorError::new("access.denied", CANARY)).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert!( + counters + .lines() + .all(|line| line.starts_with('#') || line.ends_with(" 0")), + "{counters}" + ); + assert!(log.contains("carries no failed check"), "{log}"); + assert!(!log.contains(CANARY), "{log}"); + } + + #[tokio::test] + async fn a_policy_denial_after_authentication_is_counted() { + use tower::ServiceExt as _; + // The gap the authentication counter left: `Caller::authorize` runs + // after the caller is resolved, so its denial reached no counter. + let recorder = Arc::new(RefusalRecorder::new("coordinator").unwrap()); + let app = http_edge( + Router::new().route( + "/v1/denied", + get(|| async { + let caller = + crate::access::synthetic_caller(vec![Action::Start], &["workflow"], false); + answer( + caller + .authorize(Action::Start, Some("another-workflow")) + .map(|()| json!({})), + ) + }), + ), + Router::new(), + recorder.clone(), + ); + let response = app + .oneshot( + axum::http::Request::builder() + .uri("/v1/denied") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(exposition(&recorder) + .contains("coordinator_request_refusals_total{check=\"operation\"} 1")); + } + + #[test] + fn the_authorization_header_names_a_missing_or_a_malformed_credential() { + let headers = |values: &[&'static [u8]]| { + let mut headers = HeaderMap::new(); + for value in values { + headers.append( + axum::http::header::AUTHORIZATION, + HeaderValue::from_bytes(value).unwrap(), + ); + } + headers + }; + assert_eq!( + bearer_token(&headers(&[])), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + bearer_token(&headers(&[b"Basic c3ludGhldGlj"])), + Err(FailedCheck::CredentialMissing) + ); + for malformed in [ + &[b"Bearer a-token" as &[u8], b"Bearer another-token"][..], + &[b"Bearer"], + &[b"Bearer two-spaces"], + &[b"Bearer "], + &[b"Bearer has space"], + &[b"Bearer \xff\xfe"], + ] { + assert_eq!( + bearer_token(&headers(malformed)), + Err(FailedCheck::CredentialMalformed), + "{malformed:?}" + ); + } + assert_eq!(bearer_token(&headers(&[b"Bearer a-token"])), Ok("a-token")); + } +} diff --git a/crates/registry-coordinator/src/metrics.rs b/crates/registry-coordinator/src/metrics.rs index bd6e618792..e662b15adf 100644 --- a/crates/registry-coordinator/src/metrics.rs +++ b/crates/registry-coordinator/src/metrics.rs @@ -64,6 +64,7 @@ use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE}; use axum::response::{IntoResponse, Response}; use axum::routing::get; use axum::Router; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -84,6 +85,7 @@ pub struct Metrics { attempts: CounterVec, refusals: CounterVec, sample_failures: CounterVec, + refusals_by_check: Arc, } impl fmt::Debug for Metrics { @@ -125,6 +127,7 @@ impl Default for Metrics { "sample", SampleKind::ALL.map(SampleKind::as_str), ), + refusals_by_check: Arc::new(RefusalRecorder::new("coordinator").expect(DECLARATION)), } } } @@ -318,6 +321,13 @@ impl Metrics { count(&self.refusals, &[refusal.as_str()]); } + /// Counts every refused request by the check that failed, and admits a + /// bounded number of log lines per check. + #[must_use] + pub fn refusal_recorder(&self) -> &Arc { + &self.refusals_by_check + } + /// Count one scrape-time read that failed. pub fn record_sample_failure(&self, sample: SampleKind) { count(&self.sample_failures, &[sample.as_str()]); @@ -337,6 +347,10 @@ impl Metrics { ] { counter.write(&mut out).expect(DECLARATION); } + self.refusals_by_check + .counter() + .write(&mut out) + .expect(DECLARATION); out.header( "coordinator_dispatch_jobs", Some("Steps waiting to run, running, or held unknown, sampled at scrape."), @@ -525,6 +539,7 @@ pub fn metrics_router(store: Arc) -> Router { #[cfg(test)] mod tests { use super::*; + use registry_platform_authcommon::FailedCheck; /// Every sample line the exposition carries, without its value. fn series(text: &str) -> Vec<&str> { @@ -563,6 +578,12 @@ mod tests { sample.as_str() ) })); + expected.extend(FailedCheck::ALL.map(|check| { + format!( + "coordinator_request_refusals_total{{check=\"{}\"}}", + check.as_str() + ) + })); expected.extend( ["pending", "leased", "unknown"] .map(|state| format!("coordinator_dispatch_jobs{{state=\"{state}\"}}")), @@ -621,6 +642,10 @@ mod tests { metrics.record_run_finished(RunOutcome::CancelledAfterEffect); metrics.record_step_attempt(StepAttempt::Accepted); metrics.record_authentication_refusal(AuthenticationRefusal::Policy); + assert!(metrics + .refusal_recorder() + .record(FailedCheck::Operation) + .is_some()); let text = metrics.render( Some(DispatchDepth { pending: 5, @@ -636,9 +661,18 @@ mod tests { oldest_due_age_seconds: 90, }), ); - assert_eq!( - text, - "\ + let refusals_by_check: String = std::iter::once( + "# HELP coordinator_request_refusals_total Requests refused, by the check that failed.\n# TYPE coordinator_request_refusals_total counter\n".to_owned(), + ) + .chain(FailedCheck::ALL.map(|check| { + format!( + "coordinator_request_refusals_total{{check=\"{}\"}} {}\n", + check.as_str(), + u8::from(check == FailedCheck::Operation) + ) + })) + .collect(); + let head = "\ # HELP coordinator_runs_admitted_total Runs whose admission committed. # TYPE coordinator_runs_admitted_total counter coordinator_runs_admitted_total 2 @@ -665,6 +699,8 @@ coordinator_authentication_refusals_total{reason=\"unavailable\"} 0 # TYPE coordinator_metrics_sample_failures_total counter coordinator_metrics_sample_failures_total{sample=\"dispatch-queue\"} 0 coordinator_metrics_sample_failures_total{sample=\"run-holds\"} 0 +"; + let tail = "\ # HELP coordinator_dispatch_jobs Steps waiting to run, running, or held unknown, sampled at scrape. # TYPE coordinator_dispatch_jobs gauge coordinator_dispatch_jobs{state=\"pending\"} 5 @@ -684,8 +720,8 @@ coordinator_hold_active{hold=\"admissions\"} 0 # HELP coordinator_oldest_due_age_seconds Seconds since the oldest pending job was due, or 0 when none is overdue, sampled at scrape. # TYPE coordinator_oldest_due_age_seconds gauge coordinator_oldest_due_age_seconds 90 -" - ); +"; + assert_eq!(text, format!("{head}{refusals_by_check}{tail}")); } #[test] diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index 11203b81c4..60c392205b 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -1168,8 +1168,8 @@ fn config_error(field: &str, action: &str) -> CoordinatorError { } fn is_loopback(url: &Url) -> bool { match url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Ipv4(ip)) => registry_platform_httputil::loopback::loopback_address(ip.into()), + Some(Host::Ipv6(ip)) => registry_platform_httputil::loopback::loopback_address(ip.into()), _ => false, } } @@ -1449,3 +1449,32 @@ fn serialize_database( } map.end() } + +#[cfg(test)] +mod loopback_tests { + use super::*; + + #[test] + fn loopback_endpoints_are_the_shared_numeric_literals_and_never_names() { + for loopback in [ + "http://127.0.0.1:8080", + "http://127.9.9.9:8080", + "http://[::1]:8080", + "http://[::ffff:127.0.0.1]:8080", + ] { + let url = Url::parse(loopback).unwrap(); + assert!(is_loopback(&url), "{loopback}"); + check_endpoint(&url).unwrap_or_else(|error| panic!("{loopback}: {error}")); + } + for other in [ + "http://localhost:8080", + "http://10.0.0.1:8080", + "http://[::ffff:10.0.0.1]:8080", + "http://example.test:8080", + ] { + let url = Url::parse(other).unwrap(); + assert!(!is_loopback(&url), "{other}"); + assert!(check_endpoint(&url).is_err(), "{other}: cleartext refused"); + } + } +} diff --git a/crates/registry-coordinator/src/store.rs b/crates/registry-coordinator/src/store.rs index 143da455cb..04e860d532 100644 --- a/crates/registry-coordinator/src/store.rs +++ b/crates/registry-coordinator/src/store.rs @@ -746,11 +746,10 @@ impl Store { let config: tokio_postgres::Config = database_url.parse().map_err(unavailable)?; let local = !config.get_hosts().is_empty() && config.get_hosts().iter().all(|host| match host { + // The name `localhost` is accepted without a pin: a database + // address is checked here by spelling only. tokio_postgres::config::Host::Tcp(name) => { - name == "localhost" - || name - .parse::() - .is_ok_and(|ip| ip.is_loopback()) + registry_platform_httputil::loopback::loopback_host(name).is_some() } #[cfg(unix)] tokio_postgres::config::Host::Unix(_) => true, diff --git a/docs/site/src/content/docs/operate/breg-monitor.mdx b/docs/site/src/content/docs/operate/breg-monitor.mdx index 991f8bb634..fd3fbc9f7e 100644 --- a/docs/site/src/content/docs/operate/breg-monitor.mdx +++ b/docs/site/src/content/docs/operate/breg-monitor.mdx @@ -338,6 +338,30 @@ with one of the `breg.external-refresh.*` codes in [Troubleshooting](#troublesho crates/registry-breg/src/subject_access_log.rs, run_retention(); crates/registry-platform-hooks/src/delivery/service.rs, WORKER_POLL_INTERVAL. */} +## Watch refused requests + +`breg_request_refusals_total{check}` counts every request BReg refused, by the check that refused +it, since the process started. Every `check` value is published from the first scrape at zero, so a +rate needs no `absent()` guard. A missing or refused credential, a refused token, an unreachable +key source and a refused review completion callback all count. + +Each refusal also writes one `request refused` line with `failed_check` and the request's trace id, +at most five lines per check per minute across the process. The next line for that check carries +`suppressed`, the number of refusals the minute counted but did not log, so alert on the counter, +not the log. The counter and the line carry only a fixed check name, never a token, claim, client +or subject value. Counting changes nothing the caller receives. + +A rising `credential-missing` or `credential-malformed` count usually means a caller sends no +token or a broken one. A rising `key-source-unavailable` count means BReg cannot read its signing +keys; check the issuer before the callers. + +{/* Evidence: crates/registry-breg/src/correlation.rs, finish_response(); + crates/registry-breg/src/metrics.rs, + the_refusal_counter_declares_every_check_and_publishes_it_at_zero; + crates/registry-breg/tests/authentication_refusals.rs, + every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wire; + crates/registry-platform-authcommon/src/refusal.rs, the recorder's per-check window. */} + ## Read audit records Each audit record names its schema. diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index 0656fe869f..965978a857 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -328,6 +328,7 @@ package digest the process serves, so a rollout can confirm what each process ru | `casework_completion_deliveries` | gauge | `state`: `pending`, `retrying`, `leased`, `unknown`, `dead-lettered`, `expired` | | `casework_completion_oldest_undelivered_age_seconds` | gauge | none | | `casework_metrics_sample_failures_total` | counter | `sample`: `review`, `completion-backlog` | +| `casework_request_refusals_total` | counter | `check`: the check that refused the request, every value published at zero | Every gauge except `casework_database_up` is read from the database and cached for 5 seconds. The review counts and the completion backlog are read separately, one pool connection at a time, @@ -351,6 +352,20 @@ unknown delivery has waited, or 0 when there are none. It runs from the delivery while pending, from its attempt start while leased, and from its last change once it is unknown. Dead-lettered and expired deliveries do not set it, because they stay counted until retention erases them. +`casework_request_refusals_total` counts every request the API listener refused, by the check that +refused it, since the process started: a missing or refused credential or token, an unreachable +key source, a refused delegated reviewer, and a review the caller may not act on or see. Each +refusal also writes one `request refused` line with `failed_check` and the request's trace id, at +most five lines per check per minute across the process. The next line for that check carries +`suppressed`, the number the minute counted but did not log, so alert on the counter, not the log. +Neither carries a token, claim, client or subject value, and counting changes nothing the caller +receives. + +{/* Evidence: crates/registry-casework/src/metrics.rs, refusal_recorder() and render(); + crates/registry-casework/tests/refusal_golden.rs, + authentication_and_profile_refusals_match_the_checked_in_answers; + crates/registry-platform-authcommon/src/refusal.rs, the recorder's per-check window. */} + {/* Evidence: crates/registry-casework/src/metrics.rs, metrics_router() and render(); crates/registry-casework/src/runtime/completion.rs, completion_backlog(); crates/registry-casework/tests/review_postgres.rs, the_completion_backlog_counts_every_undelivered_state_and_ages_only_work_in_flight; diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 9f5abea8e0..333d0b2120 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -38,6 +38,16 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ Admission accepts a token only when its caller policy lists the token's exact `sub`, and refuses a delegated token (COORDINATOR-INV-10). Start input is the caller's assertion: Coordinator does not compare it with the caller's `sub`. +- Coordinator counts every refusal of a caller by the check that failed, in + `coordinator_request_refusals_total{check}` on the private metrics listener. + It logs one `request refused` line with `failed_check` and the request's trace id, and at most + five lines per check per minute, with `suppressed` counting what a window held back. + The counter and the line carry only a fixed check name, never a token, claim, client, subject or + route value. + The counter covers a refused credential, a policy denial after authentication, a refused signed + event delivery or completion callback, an unreachable key source, and a run the caller cannot + see. + The older `coordinator_authentication_refusals_total{reason}` counter is unchanged. - Host users run `coordinatorctl`, which is local operator tooling for a trusted single-user machine. - PostgreSQL holds run, wait and job state. @@ -49,7 +59,15 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ crates/registry-coordinator/tests/deployment_surface.rs a_policy_admits_only_the_subjects_it_lists, a_token_carrying_act_is_refused_and_an_exchange_without_one_is_not; crates/registry-coordinator/tests/deployment_postgres.rs - start_input_is_not_bound_to_the_caller_subject. */} + start_input_is_not_bound_to_the_caller_subject; + crates/registry-coordinator/src/http.rs + every_refusal_the_service_answers_is_counted_and_logged_under_its_check, + a_policy_denial_after_authentication_is_counted, + the_authorization_header_names_a_missing_or_a_malformed_credential; + crates/registry-coordinator/src/event_trigger_tests.rs + a_refused_delivery_names_the_check_that_failed; + crates/registry-coordinator/src/completion.rs + a_refused_sender_names_the_check_that_failed. */} ## Guarantees @@ -341,8 +359,8 @@ Enforcement: deleted with the wait. Inspection adds the connection's `requestLink` with the Proposal id filled in, only for a caller already authorised to inspect the run; the id grants nothing without BReg's own grant. - The link must be `https` unless its host is a loopback IP address, the same rule as a connection - endpoint; a host name such as `localhost` is refused because name resolution is outside + The link must be `https` unless its host is a loopback IP address (`127.0.0.0/8`, `::1` or an + IPv4-mapped form of `127.0.0.0/8`), the same rule as a connection endpoint; a host name such as `localhost` is refused because name resolution is outside Coordinator's control. - The run list finds waits on one Proposal through the keyed wait commitment over the database identity and the Proposal id, so neither the database nor the list cursor holds the id in clear. diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 96b0445c0b..55aaa45563 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- BReg counts every refused request by the check that refused it, in + `breg_request_refusals_total{check}`, published at zero for every check from + the first scrape. Each refusal writes one `request refused` line with + `failed_check` and the request's trace id, at most five lines per check per + minute. That line replaces the authentication refusal line that carried a + `stage` field. Refusal statuses, headers and bodies are unchanged. + - The Rust BReg client decodes `/health` and `/ready` answers that carry members besides `status`, and ignores them. `status` is still required and checked. diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index 40ccadf9bc..0a446dedc5 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +- Casework counts every refused request by the check that refused it, in + `casework_request_refusals_total{check}` on the metrics listener, published + at zero for every check. Each refusal writes one `request refused` line with + `failed_check` and the request's trace id, at most five lines per check per + minute. That line replaces the authentication refusal line that carried a + `stage` field. Refusal statuses, headers and bodies are unchanged. +- A static key set with a private key member or a repeated member name is + refused at startup under `casework.runtime.unreadable-jwks-secret`, with the + rule it broke and the key's position, in place of + `casework.runtime-dependency.unavailable`. +- A review completion destination may use any loopback literal in plain + `http`: `127.0.0.0/8`, `::1`, or an IPv4-mapped form of `127.0.0.0/8`. The + name `localhost` stays refused. + - `GET /health` answers `{"status":"ok"}` and `GET /ready` answers `{"status":"ready"}` as `application/json`, in place of an empty 200. Both still need no token, and a service that is not ready still answers 503. diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index 4b9f4b17e3..51ab2353de 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- Coordinator counts every refused caller by the check that refused it, in + `coordinator_request_refusals_total{check}` on the metrics listener, and + writes one `request refused` line with `failed_check` and the request's + trace id, at most five lines per check per minute. A policy denial after + authentication and a refused signed event delivery are now counted and + logged too. Refusal statuses and bodies are unchanged, and + `coordinator_authentication_refusals_total{reason}` stays. +- Wherever Coordinator and `coordinatorctl` allow plaintext to a loopback + host, an IPv4-mapped loopback literal such as `[::ffff:127.0.0.1]` counts as + loopback, the same as `127.0.0.1`. A database host of `localhost` is matched + in any letter case. Host names other than `localhost` stay refused. + - `GET /health` and `GET /ready` carry the `status` member the other services answer: `{"live":true,"status":"ok"}` and `{"ready":true,"status":"ready"}`. The `live` and `ready` members stay, and From 3e37487ad1b4ced4fc6be14f55010d381fc5c1b9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 05:13:48 +0100 Subject: [PATCH 033/136] feat(adapter): grant the runtime role its payment table privileges at startup With --payments-config, the payment tables follow the facade's grant rules: the collection tables always, the disbursement tables when payments.yaml declares disbursement connections, in the facade's grant transaction or, when serving payments without a project, in a grant step of their own. A refused payments configuration grants nothing, and provider signer setup refuses before any grant. Signed-off-by: Jeremi Joslin --- .../src/payments/g2p_store.rs | 20 +- crates/registry-adapter/src/payments/http.rs | 324 ++++++---- crates/registry-adapter/src/payments/store.rs | 23 +- crates/registry-adapter/src/serve.rs | 202 ++++-- .../postgres_journal_retention_served.rs | 592 +++++++++++++++++- .../site/src/content/docs/operate/adapter.mdx | 29 +- products/adapter/CHANGELOG.md | 8 +- .../examples/payment-collections/README.md | 31 +- .../adapter/scripts/test-payment-native.mjs | 16 +- 9 files changed, 992 insertions(+), 253 deletions(-) diff --git a/crates/registry-adapter/src/payments/g2p_store.rs b/crates/registry-adapter/src/payments/g2p_store.rs index 96726c214d..a025a0e81f 100644 --- a/crates/registry-adapter/src/payments/g2p_store.rs +++ b/crates/registry-adapter/src/payments/g2p_store.rs @@ -74,6 +74,18 @@ pub enum DispatchAuthorization { Hold(G2pAttempt), } +/// The table privileges a runtime role needs for the G2P tables when +/// `payments.yaml` declares a disbursement connection. Startup checks them, +/// and `adapter serve` grants those a split runtime role lacks. +pub const RUNTIME_GRANTS: [(&str, &[&str]); 3] = [ + ("adapter_g2p_attempts", &["SELECT", "INSERT", "UPDATE"]), + ("adapter_g2p_commands", &["SELECT", "INSERT"]), + ("adapter_g2p_events", &["SELECT", "INSERT"]), +]; +/// The sequence the events table draws its identifiers from. A runtime role +/// needs USAGE on it. +pub const RUNTIME_SEQUENCE: &str = "adapter_g2p_events_sequence_seq"; + impl G2pStore { pub fn new(pool: Pool, deployment: String) -> Self { Self { pool, deployment } @@ -105,11 +117,7 @@ impl G2pStore { 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"][..]), - ] { + for (table, privileges) in RUNTIME_GRANTS { if !crate::journal::missing_table_privileges(&client, table, privileges) .await .map_err(|_| G2pError::Unavailable)? @@ -121,7 +129,7 @@ impl G2pStore { let row = client .query_one( "SELECT has_sequence_privilege(current_user, $1, 'USAGE')", - &[&"adapter_g2p_events_sequence_seq"], + &[&RUNTIME_SEQUENCE], ) .await .map_err(|_| G2pError::Unavailable)?; diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index 0356db8157..e8e11c1a6e 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -224,157 +224,194 @@ fn load_provider_packs(paths: &[PathBuf]) -> Result 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; +/// A payment configuration whose packs, mapping and credentials are settled, +/// before any database work: the caller migrates and grants, then builds the +/// router over the runtime pool. +pub(crate) struct PreparedPayments { + config: PaymentsConfig, + packs: LoadedPaymentPacks, + resolver: Arc, + authenticator: Authenticator, + g2p_provider: HttpG2pProvider, + deployment: String, +} + +impl PreparedPayments { + pub(crate) async fn prepare( + runtime: &AdapterRuntimeConfig, + path: &Path, + provider_pack_paths: &[PathBuf], + ) -> 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", + )); } - 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( + 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( + } + 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 [ - &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 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"))?; + } } - } - for connection in &config.disbursements { - 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"))?; - 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"))?; + for connection in &config.disbursements { + 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"))?; + 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() + let authenticator = crate::serve::authenticator(runtime, &resolver).await?; + // Transit signer and verifier setup reads no database, so a wrong + // socket, mount or key refuses here, before any grant. + 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 migration database unavailable"))?; - migrate(&mut client) + .map_err(|_| refused("payment disbursement authentication initialization failed"))?; + Ok(Self { + config, + packs, + resolver, + authenticator, + g2p_provider, + deployment: runtime.id.as_str().to_owned(), + }) + } + + /// Create the collection and G2P tables as the migration role. + pub(crate) async fn migrate(client: &mut deadpool_postgres::Client) -> Result<(), ServeError> { + migrate(client) .await .map_err(|_| refused("payment database migration failed"))?; - migrate_g2p(&mut client) + migrate_g2p(client) .await - .map_err(|_| refused("G2P database migration failed"))?; + .map_err(|_| refused("G2P database migration failed")) } - 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"))?; + + /// What the runtime role must hold: the collection tables, and the G2P + /// tables when a disbursement connection is declared. + pub(crate) fn requirements(&self) -> crate::serve::Requirements { + crate::serve::Requirements::payments(!self.config.disbursements.is_empty()) } - 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(g2p_provider), - ); - 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, packs.mapping)), - ) - .map_err(|_| refused("payment service was refused"))?; - let state = Arc::new(HttpState { - authenticator, - service, - g2p, - disbursements, - }); - Ok(Router::new() + + pub(crate) async fn into_router( + self, + pool: deadpool_postgres::Pool, + ) -> Result { + let Self { + config, + packs, + resolver, + authenticator, + g2p_provider, + deployment, + } = self; + let store = PaymentStore::new(pool.clone(), deployment.clone()); + store.check_privileges().await.map_err(|_| { + refused("payment runtime role lacks required table or sequence privileges") + })?; + let g2p_store = G2pStore::new(pool.clone(), deployment.clone()); + 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(g2p_provider), + ); + 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, 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)) .route( "/v1/payments/{connection}/collections/receipt", @@ -406,6 +443,7 @@ pub async fn load_router( ) .layer(DefaultBodyLimit::max(MAX_PAYMENT_BODY_BYTES)) .with_state(state)) + } } pub async fn run_only( @@ -424,8 +462,20 @@ pub async fn run_only( .map_err(|_| refused("runtime configuration was refused"))? .config; let resolver = resolver(&runtime)?; + let prepared = PreparedPayments::prepare(&runtime, payments_path, provider_pack_paths).await?; let pool = crate::serve::pool(&runtime.database, &resolver, false)?; - let router = load_router(&runtime, payments_path, provider_pack_paths, pool).await?; + { + let migration = crate::serve::pool(&runtime.database, &resolver, true)?; + let mut client = migration + .get() + .await + .map_err(|_| refused("payment migration database unavailable"))?; + PreparedPayments::migrate(&mut client).await?; + // When the grant step makes no grant, the privilege check in + // `into_router` refuses a role that lacks one. + crate::serve::grant_when_split(&mut client, &pool, &prepared.requirements()).await?; + } + let router = prepared.into_router(pool).await?; let shutdown = crate::serve::shutdown_signal()?; let listener = tokio::net::TcpListener::bind(runtime.listener.bind.0) .await diff --git a/crates/registry-adapter/src/payments/store.rs b/crates/registry-adapter/src/payments/store.rs index 3201d38097..528213345f 100644 --- a/crates/registry-adapter/src/payments/store.rs +++ b/crates/registry-adapter/src/payments/store.rs @@ -58,6 +58,18 @@ pub struct PaymentStore { pub(crate) deployment: String, } +/// The table privileges a runtime role needs for the collection tables. +/// Startup checks them, and `adapter serve` grants those a split runtime role +/// lacks. +pub const RUNTIME_GRANTS: [(&str, &[&str]); 3] = [ + ("adapter_payment_attempts", &["SELECT", "INSERT", "UPDATE"]), + ("adapter_payment_commands", &["SELECT", "INSERT"]), + ("adapter_payment_events", &["SELECT", "INSERT"]), +]; +/// The sequence the events table draws its identifiers from. A runtime role +/// needs USAGE on it. +pub const RUNTIME_SEQUENCE: &str = "adapter_payment_events_sequence_seq"; + impl PaymentStore { pub fn new(pool: Pool, deployment: String) -> Self { Self { pool, deployment } @@ -77,14 +89,7 @@ impl PaymentStore { 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"][..]), - ] { + for (table, privileges) in RUNTIME_GRANTS { if !crate::journal::missing_table_privileges(&client, table, privileges) .await .map_err(|_| Error::Unavailable)? @@ -96,7 +101,7 @@ impl PaymentStore { let row = client .query_one( "SELECT has_sequence_privilege(current_user, $1, 'USAGE')", - &[&"adapter_payment_events_sequence_seq"], + &[&RUNTIME_SEQUENCE], ) .await .map_err(|_| Error::Unavailable)?; diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index b2abda2a61..612c2d5ef1 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -698,6 +698,39 @@ fn runtime_requirements( required } +/// Everything a runtime role must hold for a deployment: table privileges, by +/// table, and USAGE on sequences. Startup grants what the role lacks, then +/// checks it. +pub(crate) struct Requirements { + pub(crate) tables: Vec<(&'static str, &'static [&'static str])>, + pub(crate) sequences: Vec<&'static str>, +} + +impl Requirements { + /// What the payment host requires: the collection tables always, and the + /// G2P tables when a disbursement connection is declared. + pub(crate) fn payments(disbursements: bool) -> Self { + let mut required = Self { + tables: crate::payments::store::RUNTIME_GRANTS.to_vec(), + sequences: vec![crate::payments::store::RUNTIME_SEQUENCE], + }; + if disbursements { + required + .tables + .extend(crate::payments::g2p_store::RUNTIME_GRANTS); + required + .sequences + .push(crate::payments::g2p_store::RUNTIME_SEQUENCE); + } + required + } + + pub(crate) fn extend(&mut self, other: Self) { + self.tables.extend(other.tables); + self.sequences.extend(other.sequences); + } +} + /// The advisory-lock key the grant step holds for its transaction, so /// replicas starting together do not rewrite the same catalog rows at once. /// Its ASCII bytes spell `adap_gnt`. @@ -746,16 +779,33 @@ async fn missing_for( .collect()) } +/// Whether `grantee` lacks USAGE on `relation`, a sequence given as an +/// already-quoted, schema-qualified name; true when it does not exist. +async fn lacks_sequence_usage( + transaction: &tokio_postgres::Transaction<'_>, + grantee: &str, + relation: &str, +) -> Result { + let held: bool = transaction + .query_one( + "SELECT coalesce(has_sequence_privilege($1, to_regclass($2), 'USAGE'), false)", + &[&grantee, &relation], + ) + .await? + .get(0); + Ok(!held) +} + /// Everything `grantee` still lacks of `required` and of `USAGE` on `schema`, /// as "PRIVILEGES on object" phrases. async fn lacking( transaction: &tokio_postgres::Transaction<'_>, grantee: &str, schema: &str, - required: &[(&'static str, &'static [&'static str])], + required: &Requirements, ) -> Result, tokio_postgres::Error> { let mut lacking = Vec::new(); - for (table, privileges) in required { + for (table, privileges) in &required.tables { let missing = missing_for( transaction, grantee, @@ -767,6 +817,11 @@ async fn lacking( lacking.push(format!("{} on {table}", missing.join(", "))); } } + for sequence in &required.sequences { + if lacks_sequence_usage(transaction, grantee, &format!("{schema}.{sequence}")).await? { + lacking.push(format!("USAGE on sequence {sequence}")); + } + } let usage: bool = transaction .query_one( "SELECT has_schema_privilege($1, current_schema(), 'USAGE')", @@ -801,7 +856,7 @@ async fn lacking( async fn grant_runtime_privileges( client: &mut deadpool_postgres::Client, grantee: &str, - required: &[(&'static str, &'static [&'static str])], + required: &Requirements, ) -> Result { let transaction = client.transaction().await.map_err(|e| grant_error(&e))?; transaction @@ -850,7 +905,7 @@ async fn grant_runtime_privileges( } let mut granted = 0_usize; let quoted_grantee = quote_identifier(grantee); - for (table, privileges) in required { + for (table, privileges) in &required.tables { let missing = missing_for( &transaction, grantee, @@ -876,6 +931,26 @@ async fn grant_runtime_privileges( )) })?; } + for sequence in &required.sequences { + if !lacks_sequence_usage(&transaction, grantee, &format!("{schema}.{sequence}")) + .await + .map_err(|e| grant_error(&e))? + { + continue; + } + granted += 1; + transaction + .batch_execute(&format!( + "GRANT USAGE ON SEQUENCE {schema}.{sequence} TO {quoted_grantee}" + )) + .await + .map_err(|error| { + ServeError::Configuration(format!( + "database: could not grant USAGE on sequence {sequence} to the runtime role: {}", + database_message(&error) + )) + })?; + } let usage: bool = transaction .query_one( "SELECT has_schema_privilege($1, current_schema(), 'USAGE')", @@ -917,6 +992,37 @@ async fn grant_runtime_privileges( Ok(true) } +/// Grant the runtime session's role what `required` names, from `migration`, +/// when the two sessions are different roles. The grantee is the role the +/// runtime session proves it holds, read before any grant: a runtime URL +/// naming `public`, a role that cannot log in or a wrong password fails here, +/// and the URL's text never chooses who receives privileges. One role on both +/// sessions issues no grant and returns false, as `grant_runtime_privileges` +/// does when its members rule made none. +pub(crate) async fn grant_when_split( + migration: &mut deadpool_postgres::Client, + runtime: &Pool, + required: &Requirements, +) -> Result { + let runtime_role: String = runtime + .get() + .await + .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))? + .query_one("SELECT current_user::text", &[]) + .await + .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))? + .get(0); + let migration_role: String = migration + .query_one("SELECT current_user::text", &[]) + .await + .map_err(|error| ServeError::Configuration(format!("database: {error}")))? + .get(0); + if runtime_role == migration_role { + return Ok(false); + } + grant_runtime_privileges(migration, &runtime_role, required).await +} + async fn run_facade( project_directory: &std::path::Path, profile_path: Option<&std::path::Path>, @@ -1013,12 +1119,25 @@ async fn run_facade( } else { None }; + // The payment configuration, packs and credentials settle before any + // database work, so a refusal grants nothing. + let payments = match payments_path { + Some(path) => Some( + crate::payments::http::PreparedPayments::prepare( + &loaded.runtime, + path, + payment_provider_pack, + ) + .await?, + ), + None => None, + }; let shutdown = shutdown_signal()?; let migration = pool(&loaded.runtime.database, &loaded.resolver, true)?; let journal = pool(&loaded.runtime.database, &loaded.resolver, false)?; // Whether the grant step found the runtime role holding everything the // deployment requires in the schema the migrations ran in. - let mut grants_verified = false; + let grants_verified; { let mut client = migration .get() @@ -1030,31 +1149,17 @@ async fn run_facade( idempotent::migrate(&mut client).await.map_err(|error| { ServeError::Configuration(format!("idempotency migration: {error}")) })?; - // The grantee is the role the runtime session proves it holds, read - // before any grant: a runtime URL naming `public`, a role that cannot - // log in or a wrong password fails here, and the URL's text never - // chooses who receives privileges. - let runtime_role: String = journal - .get() - .await - .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))? - .query_one("SELECT current_user::text", &[]) - .await - .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))? - .get(0); - let migration_role: String = client - .query_one("SELECT current_user::text", &[]) - .await - .map_err(|error| ServeError::Configuration(format!("database: {error}")))? - .get(0); - if runtime_role != migration_role { - grants_verified = grant_runtime_privileges( - &mut client, - &runtime_role, - &runtime_requirements(serves_write, declares_recovery, declares_resume), - ) - .await?; + if payments.is_some() { + crate::payments::http::PreparedPayments::migrate(&mut client).await?; } + let mut required = Requirements { + tables: runtime_requirements(serves_write, declares_recovery, declares_resume), + sequences: Vec::new(), + }; + if let Some(payments) = &payments { + required.extend(payments.requirements()); + } + grants_verified = grant_when_split(&mut client, &journal, &required).await?; } { // A runtime role that lacks a grant this deployment uses is refused @@ -1119,16 +1224,8 @@ async fn run_facade( 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, - payment_provider_pack, - journal.clone(), - ) - .await?, - ), + let payments_router = match payments { + Some(payments) => Some(payments.into_router(journal.clone()).await?), None => None, }; let address: SocketAddr = loaded.runtime.listener.bind.0; @@ -1310,6 +1407,33 @@ mod tests { .all(|(table, _)| *table != "adapter_idempotency_schema_migrations")); } + #[test] + fn payment_requirements_follow_what_the_payment_host_checks() { + let collections = Requirements::payments(false); + assert_eq!( + collections.tables, + crate::payments::store::RUNTIME_GRANTS.to_vec() + ); + assert_eq!( + collections.sequences, + ["adapter_payment_events_sequence_seq"] + ); + let both = Requirements::payments(true); + assert_eq!(both.tables.len(), 6); + assert!(both + .tables + .iter() + .any(|(table, privileges)| *table == "adapter_g2p_attempts" + && *privileges == ["SELECT", "INSERT", "UPDATE"])); + assert_eq!( + both.sequences, + [ + "adapter_payment_events_sequence_seq", + "adapter_g2p_events_sequence_seq" + ] + ); + } + #[test] fn a_role_name_is_quoted_as_one_identifier() { assert_eq!(quote_identifier("runtime"), "\"runtime\""); diff --git a/crates/registry-adapter/tests/postgres_journal_retention_served.rs b/crates/registry-adapter/tests/postgres_journal_retention_served.rs index 019466bd3c..f1bfe2eeeb 100644 --- a/crates/registry-adapter/tests/postgres_journal_retention_served.rs +++ b/crates/registry-adapter/tests/postgres_journal_retention_served.rs @@ -181,6 +181,53 @@ impl SplitRoles { profile: Option<&Path>, endpoint: &str, ) -> Self { + Self::spawn_launch( + upstream_url, + migration_url, + runtime_url, + Some((project, profile, endpoint)), + None, + ) + } + + /// Serve `payments` (with the provider packs it pins) over split roles, + /// beside the GovStack project when `facade` is given, alone when not. + fn spawn_payments( + migration_url: &str, + runtime_url: &str, + facade: Option<(&str, &Path)>, + payments: &Path, + packs: &[&Path], + ) -> Self { + Self::spawn_launch( + facade.map_or("", |(upstream_url, _)| upstream_url), + migration_url, + runtime_url, + facade.map(|(_, project)| (project, None, "tracker")), + Some((payments, packs)), + ) + } + + fn spawn_launch( + upstream_url: &str, + migration_url: &str, + runtime_url: &str, + facade: Option<(&Path, Option<&Path>, &str)>, + payments: Option<(&Path, &[&Path])>, + ) -> Self { + let endpoints = match facade { + Some((_, _, endpoint)) => format!( + r#"endpoints: + - endpoint: {endpoint} + baseUrl: {upstream_url} + credential: + type: basic + usernameRef: secret:env/TEST_UPSTREAM_USERNAME + passwordRef: secret:env/TEST_UPSTREAM_PASSWORD +"# + ), + None => "endpoints: []\n".to_owned(), + }; let key = access_token_test_key(jsonwebtoken::Algorithm::ES256); let jwks = jwks_from_private_jwk(&key).to_string(); let port = TcpListener::bind("127.0.0.1:0") @@ -196,14 +243,7 @@ impl SplitRoles { r#"apiVersion: id.registrystack.org/formats/adapter/runtime/v1alpha1 kind: AdapterRuntimeConfig id: govstack-split-roles -endpoints: - - endpoint: {endpoint} - baseUrl: {upstream_url} - credential: - type: basic - usernameRef: secret:env/TEST_UPSTREAM_USERNAME - passwordRef: secret:env/TEST_UPSTREAM_PASSWORD -listener: +{endpoints}listener: bind: 127.0.0.1:{port} database: runtimeUrlRef: secret:env/TEST_DB_RUNTIME_URL @@ -230,16 +270,21 @@ cursorKeyRef: secret:env/TEST_CURSOR_KEY ) .expect("write the runtime config"); let mut command = Command::new(env!("CARGO_BIN_EXE_adapter")); - command - .args(["serve", "--runtime-config"]) - .arg(&runtime) - .arg("--project") - .arg(project); - if !project.join("pack.yaml").exists() { - command.arg("--pack").arg(Served::example_pack()); + command.args(["serve", "--runtime-config"]).arg(&runtime); + if let Some((project, profile, _)) = facade { + command.arg("--project").arg(project); + if !project.join("pack.yaml").exists() { + command.arg("--pack").arg(Served::example_pack()); + } + if let Some(profile) = profile.filter(|_| !project.join("profile.yaml").exists()) { + command.arg("--profile").arg(profile); + } } - if let Some(profile) = profile.filter(|_| !project.join("profile.yaml").exists()) { - command.arg("--profile").arg(profile); + if let Some((payments, packs)) = payments { + command.arg("--payments-config").arg(payments); + for pack in packs { + command.arg("--payment-provider-pack").arg(pack); + } } let child = command .env("TEST_UPSTREAM_USERNAME", USERNAME) @@ -248,6 +293,7 @@ cursorKeyRef: secret:env/TEST_CURSOR_KEY .env("TEST_DB_RUNTIME_URL", runtime_url) .env("TEST_JWKS", &jwks) .env("TEST_CURSOR_KEY", CURSOR_KEY) + .env("TEST_PAYMENT_TOKEN", "synthetic-payment-token") .stdout(Stdio::null()) .stderr(Stdio::piped()) .spawn() @@ -951,6 +997,8 @@ async fn single_role_serve_issues_no_grant() { let log = format!("{schema}_log"); // An event trigger records the session role of every GRANT in the // database, so the test can observe a grant a single role issues to itself. + // Other tests run GRANTs while it exists, and its own cleanup can drop the + // log table under one of them, so the function ignores that one case. execute( &base, &format!( @@ -958,7 +1006,8 @@ async fn single_role_serve_issues_no_grant() { CREATE TABLE {log}.grants (session_role text NOT NULL); \ CREATE FUNCTION {log}.record() RETURNS event_trigger \ LANGUAGE plpgsql SECURITY DEFINER AS $$ \ - BEGIN INSERT INTO {log}.grants VALUES (session_user); END $$; \ + BEGIN INSERT INTO {log}.grants VALUES (session_user); \ + EXCEPTION WHEN undefined_table THEN NULL; END $$; \ CREATE EVENT TRIGGER {log}_trigger ON ddl_command_end \ WHEN TAG IN ('GRANT') EXECUTE FUNCTION {log}.record(); \ CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}'; \ @@ -1001,3 +1050,510 @@ async fn single_role_serve_issues_no_grant() { ) .await; } + +// Payment tables. The payment host's startup check requires the privileges +// below on the collection tables and, when `payments.yaml` declares a +// disbursement connection, on the G2P tables. These lists are retyped here on +// purpose: a change to the check must change them too. +const COLLECTIONS: [(&str, &[&str]); 3] = [ + ("adapter_payment_attempts", &["SELECT", "INSERT", "UPDATE"]), + ("adapter_payment_commands", &["SELECT", "INSERT"]), + ("adapter_payment_events", &["SELECT", "INSERT"]), +]; +const DISBURSEMENTS: [(&str, &[&str]); 3] = [ + ("adapter_g2p_attempts", &["SELECT", "INSERT", "UPDATE"]), + ("adapter_g2p_commands", &["SELECT", "INSERT"]), + ("adapter_g2p_events", &["SELECT", "INSERT"]), +]; +const COLLECTIONS_SEQUENCE: &str = "adapter_payment_events_sequence_seq"; +const DISBURSEMENTS_SEQUENCE: &str = "adapter_g2p_events_sequence_seq"; + +const G2P_SCRIPT: &str = r#" +fn submit_request(intent, settings, acceptance) { + #{pathParameters: #{}, query: #{}, headers: #{}, body: #{correlation: intent.correlationId}} +} +fn submit_response(intent, settings, acceptance, response) { + #{correlationId: intent.correlationId, references: #{transfer: response.body.id}} +} +fn status_request(intent, settings, acceptance) { + #{pathParameters: #{}, query: #{id: acceptance.references.transfer}, headers: #{}, body: ()} +} +fn status_response(intent, settings, acceptance, response) { + #{ + 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: "ACCOUNT_ID", value: response.body.debit}, + #{role: "recipient", key: "MSISDN", value: response.body.credit} + ] + } +} +"#; + +/// A `payments.yaml` with one simulator collection connection, and one bearer +/// disbursement connection when `disbursements`, with the provider pack the +/// second pins. Returns the configuration path and the packs to pass. +fn payments_fixture( + directory: &Path, + disbursements: bool, +) -> (std::path::PathBuf, Vec) { + std::fs::create_dir_all(directory.join("scripts")).expect("create the pack scripts directory"); + std::fs::write(directory.join("scripts/g2p.rhai"), G2P_SCRIPT).expect("write the script"); + let pack = 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: bearer + 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(G2P_SCRIPT.as_bytes()) + ); + let pack_path = directory.join("pack.yaml"); + std::fs::write(&pack_path, &pack).expect("write the provider pack"); + let mut yaml = r#"apiVersion: id.registrystack.org/formats/adapter/payments/v1alpha1 +kind: AdapterPayments +connections: + - id: licence-fees + institutionId: institution-a + serviceId: licence-issuance + allowedClients: [synthetic-client] + requiredScope: payments:collect + binding: + simulation: true + currency: USD + currencyScale: 2 + providerCredentialRef: secret:env/TEST_PAYMENT_TOKEN + providerCredentialIdentity: registry + 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/TEST_PAYMENT_TOKEN + credentialIdentity: payment-adapter +"# + .to_owned(); + if disbursements { + yaml.push_str(&format!( + r#"disbursements: + - id: cash-transfers + allowedClients: [synthetic-client] + requiredScope: payments:disburse + binding: + institutionId: ministry-social-protection + serviceId: cash-transfer + programmeId: cash-programme + fundingAccountId: programme-account + currency: KES + currencyScale: 2 + providerPack: + id: g2p-pay + version: '1' + digest: {} + fundingPartyKey: ACCOUNT_ID + recipientPartyKey: MSISDN + provider: + type: http + revision: bearer-v1 + submitBaseUrl: https://disbursements.example.test/ + statusBaseUrl: https://disbursements.example.test/ + auth: + type: bearer + credentialIdentity: provider + credentialRef: secret:env/TEST_PAYMENT_TOKEN + settings: {{}} + registry: + baseUrl: https://breg.example.test/ + credentialIdentity: g2p-payment-adapter + credentialRef: secret:env/TEST_PAYMENT_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 +"#, + registry_platform_config::sha256_uri(pack.as_bytes()) + )); + } + let payments_path = directory.join("payments.yaml"); + std::fs::write(&payments_path, yaml).expect("write the payments configuration"); + ( + payments_path, + if disbursements { + vec![pack_path] + } else { + Vec::new() + }, + ) +} + +/// Whether `role` holds USAGE on the sequence `name` of `schema`. +async fn sequence_usage(database: &str, schema: &str, name: &str, role: &str) -> bool { + connect(database) + .await + .query_one( + "SELECT has_sequence_privilege($1, to_regclass($2), 'USAGE')", + &[&role, &format!("{schema}.{name}")], + ) + .await + .expect("read the sequence privilege") + .get(0) +} + +/// The tables `role` holds a privilege on, restricted to the payment host's +/// (`adapter_payment_*` and `adapter_g2p_*`). +async fn payment_table_privileges( + database: &str, + schema: &str, + role: &str, +) -> std::collections::BTreeMap> { + table_privileges(database, schema, role) + .await + .into_iter() + .filter(|(table, _)| { + table.starts_with("adapter_payment_") || table.starts_with("adapter_g2p_") + }) + .collect() +} + +/// How a payment grant test serves: beside a GovStack project, or alone. +#[derive(Clone, Copy)] +enum PaymentHost { + BesideFacade, + Alone, +} + +/// Serve payments over a split runtime role that starts with no grants, and +/// assert it ends holding exactly the privileges the payment host requires: +/// the collection tables, and the G2P tables when `disbursements`, plus USAGE +/// on the schema and the events sequences, and nothing else anywhere. +async fn assert_payments_grants_exactly(host: PaymentHost, disbursements: bool, deployment: &str) { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), deployment).await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), disbursements); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let runtime_url = as_role(&database, &role); + let upstream_url = upstream.url(""); + let govstack = Served::govstack_project(); + let facade = match host { + PaymentHost::BesideFacade => Some((upstream_url.as_str(), govstack.as_path())), + PaymentHost::Alone => None, + }; + let mut serving = + SplitRoles::spawn_payments(&database, &runtime_url, facade, &payments, &packs); + serving.wait_until_listening(); + + let mut required: Vec<(&str, &[&str])> = COLLECTIONS.to_vec(); + if disbursements { + required.extend(DISBURSEMENTS); + } + // Beside a project the facade's own tables are granted too. The facade + // grant tests cover those, so this reads the payment tables only. + assert_eq!( + payment_table_privileges(&database, &schema, &role).await, + expected(&required), + "the runtime role holds exactly the payment privileges the host requires" + ); + assert!(sequence_usage(&database, &schema, COLLECTIONS_SEQUENCE, &role).await); + assert_eq!( + sequence_usage(&database, &schema, DISBURSEMENTS_SEQUENCE, &role).await, + disbursements, + "the G2P sequence is granted when a disbursement connection is declared, not before" + ); + let schema_privileges = connect(&database) + .await + .query_one( + "SELECT has_schema_privilege($1, $2, 'USAGE'), has_schema_privilege($1, $2, 'CREATE')", + &[&role, &schema], + ) + .await + .expect("read the schema privileges"); + assert!(schema_privileges.get::<_, bool>(0), "USAGE on the schema"); + assert!( + !schema_privileges.get::<_, bool>(1), + "no CREATE on the schema" + ); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::from([role.clone()]), + "the runtime role is the only grantee, and PUBLIC gained nothing" + ); + drop(serving); + drop_role(&database, &role).await; +} + +#[tokio::test] +async fn serve_grants_the_collection_tables_beside_a_project() { + assert_payments_grants_exactly(PaymentHost::BesideFacade, false, "grants-pay-facade").await; +} + +#[tokio::test] +async fn serve_grants_the_g2p_tables_when_disbursements_are_declared_beside_a_project() { + assert_payments_grants_exactly(PaymentHost::BesideFacade, true, "grants-g2p-facade").await; +} + +#[tokio::test] +async fn the_payments_only_host_grants_the_collection_tables_and_schema_usage() { + assert_payments_grants_exactly(PaymentHost::Alone, false, "grants-pay-alone").await; +} + +#[tokio::test] +async fn the_payments_only_host_grants_the_g2p_tables_when_disbursements_are_declared() { + assert_payments_grants_exactly(PaymentHost::Alone, true, "grants-g2p-alone").await; +} + +/// One role on both sessions owns the payment tables and issues no grant. +#[tokio::test] +async fn a_single_role_payments_host_issues_no_grant() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-pay-single").await; + let schema = current_schema(&database).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), true); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let mut serving = SplitRoles::spawn_payments(&database, &database, None, &payments, &packs); + serving.wait_until_listening(); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "no role other than the owner holds anything" + ); + drop(serving); +} + +/// A runtime role with a plain member inherits what it is granted, so the +/// payment tables are granted nothing and startup refuses as it does without +/// the grant step. +#[tokio::test] +async fn a_payments_runtime_role_with_members_is_granted_nothing_and_refused() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-pay-members").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let member = format!("{schema}_member"); + create_login_role(&database, &role).await; + create_login_role(&database, &member).await; + execute(&database, &format!("GRANT {role} TO {member};")).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), true); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let runtime_url = as_role(&database, &role); + + let stderr = + SplitRoles::spawn_payments(&database, &runtime_url, None, &payments, &packs).refusal(); + assert!( + stderr.contains("payment runtime role lacks required table or sequence privileges"), + "{stderr}" + ); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "an automatic grant is never made to a role others inherit from: {stderr}" + ); + drop_role(&database, &member).await; + drop_role(&database, &role).await; +} + +/// A migration role that owns the facade tables but not a payment table +/// cannot make that grant: the whole transaction rolls back and the refusal +/// names the privilege and the table. +#[tokio::test] +async fn a_migration_role_that_does_not_own_a_payment_table_fails_startup_and_grants_nothing() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema( + &upstream, + &Served::govstack_project(), + "grants-pay-nonowner", + ) + .await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let migrator = format!("{schema}_migrator"); + create_login_role(&database, &role).await; + create_login_role(&database, &migrator).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), false); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let migration_url = as_role(&database, &migrator); + let runtime_url = as_role(&database, &role); + // Create the payment tables as the test database's own role first, so the + // migrator owns none of them. The payments-only host then migrates as the + // migrator, which finds them in place. + let mut alone = SplitRoles::spawn_payments(&database, &database, None, &payments, &packs); + alone.wait_until_listening(); + drop(alone); + execute( + &database, + &format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL TABLES IN SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL SEQUENCES IN SCHEMA {schema} TO {migrator};" + ), + ) + .await; + + let stderr = + SplitRoles::spawn_payments(&migration_url, &runtime_url, None, &payments, &packs).refusal(); + assert!( + stderr.contains("SELECT, INSERT, UPDATE on adapter_payment_attempts"), + "{stderr}" + ); + assert!( + stderr.contains("the migration role does not own"), + "{stderr}" + ); + assert!(!stderr.contains(RUNTIME_PASSWORD), "{stderr}"); + assert!( + !acl_grantees(&database, &schema).await.contains(&role), + "a failed grant leaves nothing behind: {stderr}" + ); + drop_role(&database, &migrator).await; + drop_role(&database, &role).await; +} + +/// A payments configuration the host refuses (a credential reference that +/// resolves to nothing) settles before any database work, so nothing is +/// granted, beside a project or alone. +async fn assert_refused_payments_grant_nothing(host: PaymentHost, deployment: &str) { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), deployment).await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), true); + let refused = std::fs::read_to_string(&payments) + .expect("read the payments configuration") + .replace( + "secret:env/TEST_PAYMENT_TOKEN", + "secret:env/TEST_PAYMENT_ABSENT", + ); + std::fs::write(&payments, refused).expect("write the refused configuration"); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let runtime_url = as_role(&database, &role); + let upstream_url = upstream.url(""); + let govstack = Served::govstack_project(); + let facade = match host { + PaymentHost::BesideFacade => Some((upstream_url.as_str(), govstack.as_path())), + PaymentHost::Alone => None, + }; + + let stderr = + SplitRoles::spawn_payments(&database, &runtime_url, facade, &payments, &packs).refusal(); + assert!( + stderr.contains("a payment credential could not be resolved"), + "{stderr}" + ); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "a refused payments configuration grants nothing: {stderr}" + ); + drop_role(&database, &role).await; +} + +#[tokio::test] +async fn a_refused_payments_configuration_grants_nothing_beside_a_project() { + assert_refused_payments_grant_nothing(PaymentHost::BesideFacade, "grants-refused-facade").await; +} + +#[tokio::test] +async fn a_refused_payments_configuration_grants_nothing_when_served_alone() { + assert_refused_payments_grant_nothing(PaymentHost::Alone, "grants-refused-alone").await; +} + +/// The payment grants share the facade tables' transaction: the migration role +/// owns the facade tables but not the payment tables, so the facade grants, +/// which would succeed alone, roll back with the payment ones. +#[tokio::test] +async fn payment_grants_commit_with_the_facade_grants_or_not_at_all() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-pay-atomic").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let migrator = format!("{schema}_migrator"); + create_login_role(&database, &role).await; + create_login_role(&database, &migrator).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), false); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + // Create the payment tables as the test database's own role, then hand + // every other table to the migrator. + let mut creator = SplitRoles::spawn_payments(&database, &database, None, &payments, &packs); + creator.wait_until_listening(); + drop(creator); + execute( + &database, + &format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL TABLES IN SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL SEQUENCES IN SCHEMA {schema} TO {migrator}; \ + DO $$ DECLARE t text; BEGIN \ + FOR t IN SELECT tablename FROM pg_tables WHERE schemaname = '{schema}' \ + AND tablename NOT LIKE 'adapter\\_payment\\_%' AND tablename NOT LIKE 'adapter\\_g2p\\_%' \ + LOOP EXECUTE format('ALTER TABLE {schema}.%I OWNER TO {migrator}', t); END LOOP; \ + END $$;" + ), + ) + .await; + let migration_url = as_role(&database, &migrator); + let runtime_url = as_role(&database, &role); + let upstream_url = upstream.url(""); + let govstack = Served::govstack_project(); + + let stderr = SplitRoles::spawn_payments( + &migration_url, + &runtime_url, + Some((upstream_url.as_str(), govstack.as_path())), + &payments, + &packs, + ) + .refusal(); + assert!(stderr.contains("on adapter_payment_attempts"), "{stderr}"); + assert!( + !acl_grantees(&database, &schema).await.contains(&role), + "the facade grants rolled back with the payment ones: {stderr}" + ); + drop_role(&database, &migrator).await; + drop_role(&database, &role).await; +} diff --git a/docs/site/src/content/docs/operate/adapter.mdx b/docs/site/src/content/docs/operate/adapter.mdx index dafcef209b..e60b2066df 100644 --- a/docs/site/src/content/docs/operate/adapter.mdx +++ b/docs/site/src/content/docs/operate/adapter.mdx @@ -114,9 +114,13 @@ The Adapter grants nothing else: no default privileges, and nothing on It never revokes a grant, so a feature you remove from a deployment leaves its earlier grants in place until you revoke them. -You still grant the payment tables yourself when you start `adapter serve` with -`--payments-config`. -`adapter serve` refuses to start without these privileges, and it does not grant them: +When you start `adapter serve` with `--payments-config`, the same grant step covers the payment +tables, in the same transaction as the facade tables. +`adapter serve` without a project (payments only) runs the grant step on its own and also grants +`USAGE` on the schema. +The statements below are equivalent to what it runs for them. +The G2P statements apply when `payments.yaml` declares disbursement connections, and only the +grants the role still lacks are issued: ```sql GRANT SELECT, INSERT, UPDATE ON adapter_payment_attempts TO runtime; @@ -128,10 +132,13 @@ GRANT SELECT, INSERT, UPDATE ON adapter_g2p_attempts TO runtime; GRANT SELECT, INSERT ON adapter_g2p_commands, adapter_g2p_events TO runtime; GRANT USAGE ON SEQUENCE adapter_g2p_events_sequence_seq TO runtime; --- When you serve payments without a project, so no facade grant step runs. +-- When you serve payments without a project. GRANT USAGE ON SCHEMA adapter TO runtime; ``` +When `adapter serve` makes no grant for the reasons below, grant these yourself. +The payment host then refuses to start until the runtime role holds them. + `adapter serve` makes no automatic grant in two cases: - The runtime role lacks a privilege and has members that would inherit it. @@ -150,8 +157,9 @@ When the runtime role holds every privilege in the migration schema and startup missing, the runtime session's search path resolves a different schema. {/* Evidence: crates/registry-adapter/src/serve.rs runtime_requirements, grant_runtime_privileges; - crates/registry-adapter/src/payments/store.rs check_privileges; - crates/registry-adapter/src/payments/g2p_store.rs check_privileges; + crates/registry-adapter/src/payments/store.rs RUNTIME_GRANTS, RUNTIME_SEQUENCE; + crates/registry-adapter/src/payments/g2p_store.rs RUNTIME_GRANTS, RUNTIME_SEQUENCE; + crates/registry-adapter/src/payments/http.rs PreparedPayments; crates/registry-adapter/src/journal.rs RUNTIME_PRIVILEGES; crates/registry-adapter/src/idempotent.rs WRITE_RUNTIME_GRANTS, RECOVERY_RUNTIME_GRANTS, RESUME_RUNTIME_GRANTS; @@ -163,7 +171,14 @@ missing, the runtime session's search path resolves a different schema. a_provisioned_runtime_role_is_granted_its_privileges, a_provisioned_runtime_role_with_a_plain_member_is_granted_nothing_and_refused, an_administrator_with_members_of_its_own_blocks_the_grant, - a_migration_role_that_does_not_own_the_tables_fails_startup_and_grants_nothing. */} + a_migration_role_that_does_not_own_the_tables_fails_startup_and_grants_nothing, + serve_grants_the_collection_tables_beside_a_project, + serve_grants_the_g2p_tables_when_disbursements_are_declared_beside_a_project, + the_payments_only_host_grants_the_collection_tables_and_schema_usage, + the_payments_only_host_grants_the_g2p_tables_when_disbursements_are_declared, + a_single_role_payments_host_issues_no_grant, + a_payments_runtime_role_with_members_is_granted_nothing_and_refused, + a_migration_role_that_does_not_own_a_payment_table_fails_startup_and_grants_nothing. */} ## Operate an ingestion job diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index bd27aca006..e5070c69e7 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -23,8 +23,12 @@ role and has no members of its own does not count. A grant the migration role has no right to make (it does not own the object) stops startup with the missing privilege named and rolls everything back. With one role in both - sessions, no grant is issued. Payment and G2P tables under - `--payments-config` still need your own grants. The runtime role must exist, + sessions, no grant is issued. The payment tables under + `--payments-config` follow the same rules: the collection tables always, the + G2P tables when `payments.yaml` declares disbursement connections, with + `USAGE` on their events sequences, in the facade's grant transaction or, when + serving payments without a project, in a grant step of their own that also + grants `USAGE` on the schema. The runtime role must exist, and the migration role must own the tables. - `adapter serve --payments-config` hosts typed synthetic payment collection operations on the shared listener and PostgreSQL store, including without diff --git a/products/adapter/examples/payment-collections/README.md b/products/adapter/examples/payment-collections/README.md index 44997d8403..9af44b308e 100644 --- a/products/adapter/examples/payment-collections/README.md +++ b/products/adapter/examples/payment-collections/README.md @@ -107,26 +107,17 @@ step. `adapter effective-contract` exports the record-facade contract; ## 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; -``` - -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; -``` +The configured migration role creates the payment tables at startup. When the +runtime role differs, `adapter serve` grants it the privileges the payment host +checks, after migration and before binding the listener: the collection tables +always, the disbursement tables when the payments configuration declares +`disbursements`, and `USAGE` on the schema when serving payments without a +project. See +[Grant the runtime database role](https://docs.registrystack.org/operate/adapter/#grant-the-runtime-database-role) +for the rules and for the SQL to run yourself when `adapter serve` makes no +grant (a runtime role with members that would inherit them, or a migration role +that does not own the tables). Startup refuses missing grants before binding +the listener. Production builds retain the shared Adapter PostgreSQL TLS requirement. The `postgres-test` feature permits explicitly configured plaintext only for diff --git a/products/adapter/scripts/test-payment-native.mjs b/products/adapter/scripts/test-payment-native.mjs index 8dda40813b..1a30f7564c 100644 --- a/products/adapter/scripts/test-payment-native.mjs +++ b/products/adapter/scripts/test-payment-native.mjs @@ -103,18 +103,6 @@ async function issue(bill, receipt, key, expected = [200]) { 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']); @@ -129,7 +117,6 @@ async function independentStores(originalConfiguration) { 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`; @@ -215,8 +202,7 @@ print(json.dumps({'path':str(root), 'python':platform.python_version(), 'files': 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'); - await startAdapter(); check('PostgreSQL TLS startup and exact split-role payment privilege diagnostic'); + await startAdapter(); check('PostgreSQL TLS startup grants the split runtime role its payment privileges'); const bill = await createBill('recovery'); await issue(bill, 'absent-receipt', 'unpaid-issue', [412]); From 0b71e39a7e87e3cb8787daf0e15b886bfde99e9f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 06:10:52 +0100 Subject: [PATCH 034/136] feat: count and log every refused request under its check in the other runtimes fix(render): treat an IPv4-mapped loopback timestamp URL as loopback, as the shared rule does Render checks a test timestamp authority's plain http URL with the shared loopback rule, which counts IPv4-mapped forms of 127.0.0.0/8 as loopback. The test now expects that, and an IPv4-mapped address off the host stays refused. feat(render): count and log every refused caller under the check that refused it Each refusal answers as before and is now counted in render_request_refusals_total{check} and written as one request refused line with the trace id. feat(platform): count and log every refused MCP request under its check The MCP edge counts each refused request by the check that refused it and writes one rate-limited "request refused" line naming the failed check, at most five lines per check per minute. The edge has no metrics listener, so the line is the operator's signal. Refusal statuses, headers and bodies are unchanged. Gateways built on the edge and the BReg review page accept the loopback spellings of the shared definition under development-loopback and still refuse "localhost." and "*.localhost". A refused static key set now says why. feat(casework): count each review, directory, clock and grant refusal under its own check A refused review, staffing, inbox, assignment, clock or task-grant request now counts in casework_request_refusals_total under the check that refused it: role, access profile, separation of duties, ownership, operation, source authority, or the task grant's expiry, status, client or binding. A target concealed as not found counts under visibility, or under the check that hid it. A review result request for a review the producer does not own counts too. The caller's answer is unchanged: the same status, headers and body. feat(documents): count and log every refused request under the check that refused it Every refused request counts in documents_request_refusals_total{check} on the metrics listener, published at zero for every check, and writes one rate-limited "request refused" line naming the failed check. A scope refusal carries a fixed remedy naming the scope claim setting. A static key set that holds a private key member or a repeated member name is refused at startup with the rule it broke and the key's position, never a key value. Refusal statuses, headers and bodies are unchanged. feat(evidence): count and log every refused request under the check that refused it Evidence counts every 401, 403 and 429 answer in evidence_request_refusals_total{check} on the private metrics listener, published at zero for every check, and writes one rate-limited "request refused" line with the failed check and the request's trace id. A rise under key-source-unavailable means the issuer's key set cannot be reached. No response status, header or body changes. feat(scheduling): count and log every refused request under the check that refused it Every 401, 403 and concealing answer counts in scheduling_request_refusals_total{check} on the metrics listener, published at zero for every check, and writes one rate-limited "request refused" line with the failed check and the trace id. The line replaces the authentication refusal line with a stage field. A static key set that breaks the public-key rule is refused at startup under scheduling.runtime.unreadable-jwks-secret with the rule it broke. A plain http reminder or hook destination accepts any loopback host by the shared rule. Refusal statuses, headers and bodies are unchanged. feat(evidence): count and log every refused wallet-facing request under its check Evidence OID4VCI and Evidence OID4VP count each refused request in evidence_oid4vci_request_refusals_total{check} and evidence_oid4vp_request_refusals_total{check}, published at zero for every check, and write one rate-limited "request refused" line naming the failed check. That bounded line replaces the key-source warning each service wrote; the counter under key-source-unavailable is the signal to alert on. Responses are unchanged. feat(breg): count every concealed or refused read and write under the check that hid it A request answered 404 resource.not_found because the caller may not see the target now counts in breg_request_refusals_total under the check that hid it: the route, the profile claim, the task grant, the row boundary, the purpose, the action guard or visibility. Proposals, Actions, attachments, statistics, external views, ingestion, record attachments, the access log and GIS follow the same rule. A Proposal document refused for its authority names the condition: an action mismatch counts as operation, a Proposal outside the task grant's scope as task-grant-scope, and another caller's Proposal as ownership. Unknown routes stay uncounted. Refusal statuses, headers and bodies are unchanged. feat(messaging): count and log every refused request under the check that refused it Every refused request counts in messaging_request_refusals_total{check} on the metrics listener, published at zero for every check, and writes one rate-limited "request refused" line with the failed check and the trace id. The line replaces the authentication refusal line with a stage field and the three callback refusal lines. A key endpoint outage counts under key-source-unavailable. A static key set that breaks the public-key rule is refused at startup under messaging.runtime.unreadable-jwks-secret with the rule it broke, and messagingctl names the rule for a borrowed owner's key set. A plain http provider base URL and a development SMTP relay share the loopback rule. Refusal statuses, headers and bodies are unchanged. Signed-off-by: Jeremi Joslin --- Cargo.lock | 2 + crates/registry-breg-mcp/src/config.rs | 38 +- crates/registry-breg-mcp/src/runtime.rs | 49 +- crates/registry-breg-review/src/config.rs | 33 +- crates/registry-breg/Cargo.toml | 5 + crates/registry-breg/src/access_preview.rs | 4 +- crates/registry-breg/src/api/access_log.rs | 18 +- crates/registry-breg/src/api/actions.rs | 152 ++- .../src/api/actions/availability.rs | 4 +- crates/registry-breg/src/api/attachments.rs | 61 +- .../registry-breg/src/api/external_views.rs | 98 +- crates/registry-breg/src/api/gis.rs | 22 +- crates/registry-breg/src/api/ingestion.rs | 181 ++-- crates/registry-breg/src/api/mod.rs | 549 +++++++--- crates/registry-breg/src/api/proposals.rs | 514 +++++---- .../src/api/record_attachments.rs | 22 +- crates/registry-breg/src/api/statistics.rs | 43 +- .../src/api/tests/immediate_action_tests.rs | 2 +- crates/registry-breg/src/mutation.rs | 46 +- crates/registry-breg/src/mutation/proposal.rs | 100 +- crates/registry-breg/src/postgres/mutation.rs | 2 +- crates/registry-breg/src/postgres/proposal.rs | 10 +- .../tests/concealment_refusals.rs | 643 ++++++++++++ .../tests/golden/concealment_refusals.json | 171 +++ .../registry-breg/tests/postgres_mutation.rs | 58 +- crates/registry-casework/src/assignment.rs | 21 +- .../registry-casework/src/auth/delegated.rs | 13 +- crates/registry-casework/src/clocks.rs | 5 +- crates/registry-casework/src/http.rs | 85 +- crates/registry-casework/src/review.rs | 179 +++- crates/registry-casework/src/review/inbox.rs | 4 +- .../registry-casework/src/review/staffing.rs | 20 +- crates/registry-casework/src/service.rs | 5 +- crates/registry-casework/src/store.rs | 9 +- crates/registry-casework/src/task_grants.rs | 73 +- .../src/task_grants/http_tests.rs | 2 +- .../src/task_grants/lock_order_tests.rs | 4 +- .../tests/golden/refusal_responses.json | 32 + .../registry-casework/tests/refusal_golden.rs | 17 + .../tests/review_acceptance_postgres.rs | 18 +- .../tests/review_directory_postgres.rs | 12 +- .../tests/review_postgres.rs | 36 +- .../support/authority_closure_regressions.rs | 2 +- .../tests/support/inbox_pagination.rs | 2 +- .../independent_staffing_activation.rs | 8 +- crates/registry-documents/Cargo.toml | 7 +- crates/registry-documents/src/auth.rs | 227 ++-- crates/registry-documents/src/config.rs | 58 +- crates/registry-documents/src/http.rs | 163 ++- crates/registry-documents/src/metrics.rs | 43 +- crates/registry-documents/src/service.rs | 385 +++++-- .../registry-documents/src/service/erasure.rs | 19 +- .../registry-documents/src/service/grants.rs | 37 +- .../tests/golden/refusals.json | 475 +++++++++ .../tests/refusal_golden.rs | 621 +++++++++++ .../tests/token_characterisation.rs | 6 +- crates/registry-evidence-oid4vci/Cargo.toml | 1 + .../src/authorizer.rs | 36 +- .../src/observability.rs | 19 + .../src/observability/golden-scrape.txt | 47 + .../registry-evidence-oid4vci/src/service.rs | 438 +++++++- .../src/service/draft13.rs | 10 +- .../tests/draft13_profile.rs | 3 +- .../tests/golden/refusals.json | 205 ++++ .../tests/inji_interoperability.rs | 3 +- .../tests/offer_authorization.rs | 17 +- .../tests/state_machine_recovery.rs | 3 +- .../tests/token_characterisation.rs | 4 +- crates/registry-evidence-oid4vp/Cargo.toml | 4 +- crates/registry-evidence-oid4vp/src/auth.rs | 41 +- .../registry-evidence-oid4vp/src/metrics.rs | 11 + .../registry-evidence-oid4vp/src/service.rs | 133 ++- .../tests/golden/refusals.json | 250 +++++ .../tests/refusal_golden.rs | 270 +++++ .../tests/refusal_recording.rs | 373 +++++++ crates/registry-evidence/Cargo.toml | 4 +- crates/registry-evidence/src/auth.rs | 59 +- crates/registry-evidence/src/observability.rs | 66 +- .../src/observability/golden-scrape.txt | 47 + .../src/refusal_recording_tests.rs | 520 +++++++++ crates/registry-evidence/src/runtime.rs | 145 ++- crates/registry-evidence/src/runtime_tests.rs | 6 +- crates/registry-evidence/src/selector.rs | 259 +++-- crates/registry-evidence/src/server.rs | 126 ++- .../tests/golden/refusal_answers.json | 416 ++++++++ .../tests/selector_conformance.rs | 81 +- .../tests/token_characterisation.rs | 22 +- crates/registry-mcp-edge/Cargo.toml | 2 +- .../src/compatibility_tests/inbound.rs | 94 +- crates/registry-mcp-edge/src/config.rs | 48 +- crates/registry-mcp-edge/src/inbound.rs | 101 +- .../src/inbound/refusal_tests.rs | 446 ++++++++ crates/registry-mcp-edge/src/server.rs | 19 +- .../tests/golden/refusals.json | 224 ++++ crates/registry-mcp/src/config.rs | 16 +- crates/registry-mcp/src/runtime.rs | 65 +- crates/registry-messaging/Cargo.toml | 4 +- crates/registry-messaging/src/auth.rs | 245 +++-- crates/registry-messaging/src/callbacks.rs | 60 +- crates/registry-messaging/src/config.rs | 104 +- crates/registry-messaging/src/http.rs | 983 +++++++++++++++++- .../src/http_provider/settings.rs | 46 +- crates/registry-messaging/src/metrics.rs | 52 +- crates/registry-messaging/src/smtp/mod.rs | 4 +- .../registry-messaging/src/smtp/settings.rs | 12 +- .../tests/golden/refusals.json | 325 ++++++ .../tests/token_characterisation.rs | 6 +- .../registry-messagingctl/src/dev/borrowed.rs | 17 +- .../src/dev/borrowed_tests.rs | 24 + crates/registry-render/Cargo.toml | 4 +- crates/registry-render/src/auth.rs | 32 +- .../src/auth/token_characterisation.rs | 11 +- crates/registry-render/src/metrics.rs | 11 + crates/registry-render/src/runtime.rs | 4 +- crates/registry-render/src/server.rs | 529 +++++++++- .../tests/golden/authentication_refusals.json | 192 ++++ crates/registry-scheduling/Cargo.toml | 5 +- crates/registry-scheduling/src/auth.rs | 182 ++-- crates/registry-scheduling/src/config.rs | 101 +- crates/registry-scheduling/src/http.rs | 524 ++++++++-- crates/registry-scheduling/src/metrics.rs | 44 + crates/registry-scheduling/src/runtime.rs | 2 +- crates/registry-scheduling/src/service.rs | 139 ++- crates/registry-scheduling/src/source_busy.rs | 38 +- .../tests/golden/refusal-answers.json | 128 +++ .../review_regressions.rs | 151 ++- .../tests/token_characterisation.rs | 32 +- .../src/content/docs/operate/breg-monitor.mdx | 7 +- .../src/content/docs/operate/casework.mdx | 3 +- .../src/content/docs/operate/documents.mdx | 12 +- .../content/docs/operate/registry-render.mdx | 1 + .../src/content/docs/operate/stuck-work.mdx | 4 +- docs/site/src/content/docs/security/breg.mdx | 13 + .../src/content/docs/security/casework.mdx | 14 + .../src/content/docs/security/documents.mdx | 31 +- .../src/content/docs/security/evidence.mdx | 37 +- .../src/content/docs/security/messaging.mdx | 41 +- .../site/src/content/docs/security/render.mdx | 20 +- products/breg/CHANGELOG.md | 12 +- products/casework/CHANGELOG.md | 4 +- products/documents/CHANGELOG.md | 12 + products/evidence/CHANGELOG.md | 13 + products/messaging/CHANGELOG.md | 19 + .../contracts/security-test-traceability.yaml | 2 +- products/platform/CHANGELOG.md | 11 + products/render/CHANGELOG.md | 8 + products/scheduling/CHANGELOG.md | 15 + .../scheduling/scripts/generate_openapi.py | 2 +- 148 files changed, 12466 insertions(+), 1875 deletions(-) create mode 100644 crates/registry-breg/tests/concealment_refusals.rs create mode 100644 crates/registry-breg/tests/golden/concealment_refusals.json create mode 100644 crates/registry-documents/tests/golden/refusals.json create mode 100644 crates/registry-documents/tests/refusal_golden.rs create mode 100644 crates/registry-evidence-oid4vci/tests/golden/refusals.json create mode 100644 crates/registry-evidence-oid4vp/tests/golden/refusals.json create mode 100644 crates/registry-evidence-oid4vp/tests/refusal_golden.rs create mode 100644 crates/registry-evidence-oid4vp/tests/refusal_recording.rs create mode 100644 crates/registry-evidence/src/refusal_recording_tests.rs create mode 100644 crates/registry-evidence/tests/golden/refusal_answers.json create mode 100644 crates/registry-mcp-edge/src/inbound/refusal_tests.rs create mode 100644 crates/registry-mcp-edge/tests/golden/refusals.json create mode 100644 crates/registry-messaging/tests/golden/refusals.json create mode 100644 crates/registry-render/tests/golden/authentication_refusals.json create mode 100644 crates/registry-scheduling/tests/golden/refusal-answers.json diff --git a/Cargo.lock b/Cargo.lock index f3f5c7d0f3..edb30821d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7247,6 +7247,7 @@ dependencies = [ "registry-evidence-client", "registry-evidence-verifier", "registry-platform-audit", + "registry-platform-authcommon", "registry-platform-buildinfo", "registry-platform-config", "registry-platform-crypto", @@ -8439,6 +8440,7 @@ dependencies = [ "registry-platform-hooks", "registry-platform-httpsec", "registry-platform-httputil", + "registry-platform-loopback", "registry-platform-metrics", "registry-platform-oidc", "registry-platform-testing", diff --git a/crates/registry-breg-mcp/src/config.rs b/crates/registry-breg-mcp/src/config.rs index cc98f55aa9..70c21287fc 100644 --- a/crates/registry-breg-mcp/src/config.rs +++ b/crates/registry-breg-mcp/src/config.rs @@ -25,12 +25,12 @@ use registry_platform_config::{ ConfigBlockError, ConfigBlockErrorKind, LoadedRuntimeConfig, PrivateListenerConfig, RemovedKey, RuntimeConfigLoader, RuntimeEnvelope, SecretProvidersConfig, TlsTermination, }; +use registry_platform_httputil::loopback::loopback_host; use registry_platform_yaml::{ escape_pointer_segment, BoundedU64, Diagnostic, Invalid, LocalId, Report, RetiredApiVersion, UniqueList, Url, }; use serde::{Deserialize, Deserializer}; -use url::Host; /// apiVersion of the gateway runtime configuration document. pub const RUNTIME_API_VERSION: &str = "id.registrystack.org/formats/breg/mcp-runtime/v1alpha1"; @@ -451,7 +451,7 @@ fn endpoint_findings( ]; for (pointer, endpoint) in endpoints { let url = endpoint.to_url(); - let secure = url.scheme() == "https" || (development && loopback_host(&url)); + let secure = url.scheme() == "https" || (development && is_loopback(&url)); if termination_known && !secure { findings.push(Finding::new( "breg.mcp-runtime.plain-http-endpoint", @@ -520,14 +520,11 @@ fn cross_member_findings( } } -fn loopback_host(url: &url::Url) -> bool { +fn is_loopback(url: &url::Url) -> bool { url.scheme() == "http" - && match url.host() { - Some(Host::Ipv4(address)) => address.is_loopback(), - Some(Host::Ipv6(address)) => address.is_loopback(), - Some(Host::Domain(domain)) => domain == "localhost", - None => false, - } + && url + .host_str() + .is_some_and(|host| loopback_host(host).is_some()) } /// A value that satisfies the member at `pointer`, so a deferred expression @@ -1260,6 +1257,29 @@ rateLimits: ); } + #[test] + fn plain_http_follows_the_shared_loopback_definition() { + let development = + document().replace("operator-controlled-upstream", "development-loopback"); + for host in ["LOCALHOST", "127.0.0.2", "[::1]", "[::ffff:127.0.0.1]"] { + let config = development.replace( + "https://registry.example.test/", + &format!("http://{host}:8080/"), + ); + load(&config).unwrap_or_else(|_| panic!("{host} is loopback")); + } + for host in ["localhost.", "app.localhost", "[::ffff:10.0.0.1]"] { + refused( + &development.replace( + "https://registry.example.test/", + &format!("http://{host}:8080/"), + ), + "breg.mcp-runtime.plain-http-endpoint", + "/registry/baseUrl", + ); + } + } + #[test] fn an_endpoint_carries_no_query_or_fragment() { for (from, to, path) in [ diff --git a/crates/registry-breg-mcp/src/runtime.rs b/crates/registry-breg-mcp/src/runtime.rs index 466788949d..cb09aaeb5d 100644 --- a/crates/registry-breg-mcp/src/runtime.rs +++ b/crates/registry-breg-mcp/src/runtime.rs @@ -77,6 +77,16 @@ fn resource_server_failure(error: ResourceServerError) -> StartupError { StartupError::ResourceServer(description) } +/// Reads the static key document. The refusal text names what the document +/// got wrong and carries no key material, so it goes to the operator's log. +fn static_key_fetcher(document: &[u8]) -> Result { + let keys = parse_static_jwks(document).map_err(|error| { + tracing::error!(%error, "the static key set was refused"); + StartupError::Key("resourceServer.jwksSource.documentRef") + })?; + Ok(JwksFetcher::new_static(keys, JwksFetcherConfig::defaults())) +} + fn resolver(config: &RuntimeConfig) -> Result { config.secret_providers.resolver().map_err(|error| { StartupError::Secret(describe_secret_failure( @@ -150,9 +160,7 @@ async fn assemble(config: &RuntimeConfig) -> Result { "resourceServer.jwksSource.documentRef", document_ref, )?; - let keys = parse_static_jwks(document.expose_secret()) - .map_err(|_| StartupError::Key("resourceServer.jwksSource.documentRef"))?; - JwksFetcher::new_static(keys, JwksFetcherConfig::defaults()) + static_key_fetcher(document.expose_secret())? } }; let resource_options = ResourceServerOptions { @@ -274,6 +282,41 @@ where mod tests { use super::*; + /// A public EC key as a provider publishes it, with members the verifier + /// does not read. + fn provider_key_set(extra: &str) -> Vec { + format!( + r#"{{"keys":[{{"kty":"EC","crv":"P-256","kid":"key-1","use":"sig","alg":"ES256","ext":true,"x5c":["MIIB"],"x5t":"abc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"{extra}}}]}}"# + ) + .into_bytes() + } + + #[test] + fn a_static_key_set_with_unknown_public_members_loads() { + static_key_fetcher(&provider_key_set("")) + .expect("a provider key set with ext and x5c members loads"); + } + + #[test] + fn a_static_key_set_with_a_private_member_keeps_its_code_and_logs_the_validator_text() { + let logs = registry_platform_testing::CapturedDiagnosticLogs::default(); + let error = tracing::dispatcher::with_default(&logs.subscriber(), || { + let Err(error) = static_key_fetcher(&provider_key_set(r#","d":"CANARY-PRIVATE""#)) + else { + panic!("a private member is refused"); + }; + error + }); + assert!(matches!( + error, + StartupError::Key("resourceServer.jwksSource.documentRef") + )); + let text = logs.text(); + assert!(text.contains("private-key member"), "{text}"); + assert!(!text.contains("CANARY-PRIVATE"), "{text}"); + assert!(!error.to_string().contains("CANARY-PRIVATE")); + } + #[test] fn neutral_principal_rate_limit_uses_breg_public_name() { let error = resource_server_failure(ResourceServerError::RateLimit("perPrincipal")); diff --git a/crates/registry-breg-review/src/config.rs b/crates/registry-breg-review/src/config.rs index 8e5f7239b4..88d22d746a 100644 --- a/crates/registry-breg-review/src/config.rs +++ b/crates/registry-breg-review/src/config.rs @@ -24,13 +24,12 @@ use registry_platform_config::{ PrivateListenerConfig, RemovedKey, RuntimeConfigLoader, RuntimeEnvelope, SecretProvidersConfig, SecretReference, TlsTermination, }; -use registry_platform_httputil::{valid_resource_uri, valid_scope_token}; +use registry_platform_httputil::{loopback::loopback_host, valid_resource_uri, valid_scope_token}; use registry_platform_yaml::{ escape_pointer_segment, BoundedU32, BoundedU64, Diagnostic, ExternalId, Invalid, LocalId, Report, RetiredApiVersion, UniqueList, Url, }; use serde::{de, Deserialize, Deserializer}; -use url::Host; /// apiVersion of the review page runtime configuration document. pub const RUNTIME_API_VERSION: &str = "id.registrystack.org/formats/breg/review-runtime/v1alpha1"; @@ -682,7 +681,7 @@ fn endpoint_findings( ]; for (pointer, endpoint) in endpoints { let url = endpoint.to_url(); - let secure = url.scheme() == "https" || (development && loopback_host(&url)); + let secure = url.scheme() == "https" || (development && is_loopback(&url)); if termination_known && !secure { findings.push(Finding::new( "breg.review-runtime.plain-http-endpoint", @@ -713,14 +712,11 @@ fn endpoint_findings( } } -fn loopback_host(url: &url::Url) -> bool { +fn is_loopback(url: &url::Url) -> bool { url.scheme() == "http" - && match url.host() { - Some(Host::Ipv4(address)) => address.is_loopback(), - Some(Host::Ipv6(address)) => address.is_loopback(), - Some(Host::Domain(domain)) => domain == "localhost", - None => false, - } + && url + .host_str() + .is_some_and(|host| loopback_host(host).is_some()) } /// Whether `url`, read from the provider's discovery document, is an @@ -729,7 +725,7 @@ fn loopback_host(url: &url::Url) -> bool { pub(crate) fn allowed_discovered_endpoint(url: &url::Url, development: bool) -> bool { let secure = match url.scheme() { "https" => true, - "http" => development && loopback_host(url), + "http" => development && is_loopback(url), _ => false, }; secure @@ -1355,6 +1351,21 @@ audit: ); } + #[test] + fn plain_http_follows_the_shared_loopback_definition() { + for host in ["LOCALHOST", "127.0.0.2", "[::ffff:127.0.0.1]"] { + load(&development().replace("http://127.0.0.1:9000", &format!("http://{host}:9000"))) + .unwrap_or_else(|_| panic!("{host} is loopback")); + } + for host in ["localhost.", "app.localhost", "[::ffff:10.0.0.1]"] { + refused( + &development().replace("http://127.0.0.1:9000", &format!("http://{host}:9000")), + "breg.review-runtime.plain-http-endpoint", + "/signIn/issuer", + ); + } + } + #[test] fn the_shared_listener_requires_an_explicit_bind() { let omitted = development().replace(" bind: 127.0.0.1:8115\n", ""); diff --git a/crates/registry-breg/Cargo.toml b/crates/registry-breg/Cargo.toml index 3938916f16..84c2011253 100644 --- a/crates/registry-breg/Cargo.toml +++ b/crates/registry-breg/Cargo.toml @@ -516,6 +516,11 @@ name = "authentication_refusals" path = "tests/authentication_refusals.rs" required-features = ["runtime"] +[[test]] +name = "concealment_refusals" +path = "tests/concealment_refusals.rs" +required-features = ["runtime"] + [[test]] name = "http_read_only" path = "tests/http_read_only.rs" diff --git a/crates/registry-breg/src/access_preview.rs b/crates/registry-breg/src/access_preview.rs index 07da382a53..69be9fd08c 100644 --- a/crates/registry-breg/src/access_preview.rs +++ b/crates/registry-breg/src/access_preview.rs @@ -92,7 +92,9 @@ pub fn preview_access( if !operation_granted { Some("operation-not-granted") } else { - authorize_profile_claims(profile, &claims).err() + authorize_profile_claims(profile, &claims) + .err() + .map(|refusal| refusal.reason) } } }; diff --git a/crates/registry-breg/src/api/access_log.rs b/crates/registry-breg/src/api/access_log.rs index 3462bcd27c..7d4c7c4d1a 100644 --- a/crates/registry-breg/src/api/access_log.rs +++ b/crates/registry-breg/src/api/access_log.rs @@ -50,7 +50,7 @@ async fn read( let mut surface = match super::authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_read_concealment( &service, &route, @@ -58,7 +58,7 @@ async fn read( &claims, path.get("record_id"), &correlation, - reason, + refusal, ) .await; } @@ -78,17 +78,23 @@ async fn read( ) .await; } - if claims.principal().is_none() - || record_id.is_none_or(|id| !valid_canonical_record_uuid(id)) + let refused_check = if claims.principal().is_none() { + Some(FailedCheck::TokenClaims) + } else if record_id.is_none_or(|id| !valid_canonical_record_uuid(id)) || headers.contains_key(crate::subject_access_log::REQUESTER_HEADER) || headers.contains_key(crate::subject_access_log::PURPOSE_HEADER) { + Some(FailedCheck::Visibility) + } else { + None + }; + if let Some(check) = refused_check { return audited_read_refusal( &service, &route, &surface, record_id, - concealed(), + concealed(check), &correlation, ) .await; @@ -121,7 +127,7 @@ async fn read( .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); response } - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(ReadServiceError::CursorInvalid) => cursor_invalid(), Err(_) => unavailable(), } diff --git a/crates/registry-breg/src/api/actions.rs b/crates/registry-breg/src/api/actions.rs index f368f1317a..1f2fd0bcb6 100644 --- a/crates/registry-breg/src/api/actions.rs +++ b/crates/registry-breg/src/api/actions.rs @@ -111,35 +111,54 @@ fn authorize_action<'a>( claims: &VerifiedRequestClaims, options: &QueryOptions, ) -> Option> { - service.mutations.as_ref()?; + authorize_action_checked(service, route, claims, options).ok() +} + +/// The admission of one Action route. The refusal names the first check that +/// failed, for the operator only. +fn authorize_action_checked<'a>( + service: &'a HttpService, + route: &'a CompiledActionRoute, + claims: &VerifiedRequestClaims, + options: &QueryOptions, +) -> Result, FailedCheck> { + if service.mutations.is_none() { + return Err(FailedCheck::Visibility); + } let inventory = service.registry.actions(); // A caller cannot construct an alternate path, operation or action under a // valid route identifier. Discovery and dispatch use this same inventory. if !inventory.routes.contains(route) || !matches!(route.operation, Operation::Invoke | Operation::Start) { - return None; + return Err(FailedCheck::Operation); } - let access = inventory.access.iter().find(|entry| { - entry.route_id == route.id - && entry.action_id == route.action_id - && entry.operation == route.operation - })?; + let access = inventory + .access + .iter() + .find(|entry| { + entry.route_id == route.id + && entry.action_id == route.action_id + && entry.operation == route.operation + }) + .ok_or(FailedCheck::AccessProfile)?; let selected = options .access_profile() .map(String::as_str) - .or(access.default_profile_id.as_deref())?; + .or(access.default_profile_id.as_deref()) + .ok_or(FailedCheck::AccessProfile)?; if !access.profile_ids.contains(selected) || !route.access_profiles.iter().any(|id| id == selected) { - return None; + return Err(FailedCheck::AccessProfile); } let action = inventory .actions .iter() - .find(|action| action.id == route.action_id)?; + .find(|action| action.id == route.action_id) + .ok_or(FailedCheck::Operation)?; if route.operation == Operation::Start { - proposals::authorize( + proposals::authorize_checked( &service.registry, action, claims, @@ -151,27 +170,35 @@ fn authorize_action<'a>( && (claims.actor_subject().is_some() || claims.actor_kind() == Some(registry_platform_oidc::ActorKind::Agent)) { - return None; + return Err(FailedCheck::TaskGrantMissing); } let grant = action .permissions .iter() - .find(|grant| grant.profile_id == selected)?; - if !grant.operations.contains(&route.operation) - || grant.principal_claim.as_deref() != claims.principal_claim() - || !grant - .required_scopes - .iter() - .all(|scope| claims.has_scope(scope)) - || (!grant.required_purposes.is_empty() - && !claims - .purpose() - .is_some_and(|purpose| grant.required_purposes.contains(purpose))) + .find(|grant| grant.profile_id == selected) + .ok_or(FailedCheck::AccessProfile)?; + if !grant.operations.contains(&route.operation) { + return Err(FailedCheck::Operation); + } + if grant.principal_claim.as_deref() != claims.principal_claim() { + return Err(FailedCheck::TokenClaims); + } + if !grant + .required_scopes + .iter() + .all(|scope| claims.has_scope(scope)) { - return None; + return Err(FailedCheck::Scope); + } + if !grant.required_purposes.is_empty() + && !claims + .purpose() + .is_some_and(|purpose| grant.required_purposes.contains(purpose)) + { + return Err(FailedCheck::Purpose); } if let Some(expected) = grant.actor_kind { - let actual = claims.actor_kind()?; + let actual = claims.actor_kind().ok_or(FailedCheck::ActorKind)?; if !matches!( (expected, actual), ( @@ -185,14 +212,14 @@ fn authorize_action<'a>( registry_platform_oidc::ActorKind::Service ) ) { - return None; + return Err(FailedCheck::ActorKind); } if route.operation == Operation::Invoke && expected == crate::contract::ActorKindSource::Agent && claims.actor_subject().is_none() && claims.grant().is_none() { - return None; + return Err(FailedCheck::TaskGrantMissing); } } // A delegated token acts for its principal; only a grant written for @@ -200,18 +227,18 @@ fn authorize_action<'a>( if claims.actor_subject().is_some() && grant.actor_kind != Some(crate::contract::ActorKindSource::Agent) { - return None; + return Err(FailedCheck::Delegation); } if !grant.requester_clients.is_empty() && !claims .requester_client() .is_some_and(|client| grant.requester_clients.contains(client)) { - return None; + return Err(FailedCheck::RequesterClient); } - let principal = claims.principal()?; + let principal = claims.principal().ok_or(FailedCheck::TokenClaims)?; let task_grant = if route.operation == Operation::Invoke { - action_task_grant_binding(action, grant, claims).ok()? + action_task_grant_binding(action, grant, claims)? } else { None }; @@ -224,8 +251,9 @@ fn authorize_action<'a>( verified_row_boundaries_from_sources(&target.row_boundaries, claims)?, )) }) - .collect::>>()?; - Some(AuthorizedActionSurface { + .collect::>>() + .ok_or(FailedCheck::RowBoundary)?; + Ok(AuthorizedActionSurface { route, action, context: AuthorizedActionContext::new( @@ -245,31 +273,34 @@ fn action_task_grant_binding( action: &CompiledAction, permission: &crate::model::CompiledActionPermission, claims: &VerifiedRequestClaims, -) -> Result, ()> { +) -> Result, FailedCheck> { match (&permission.task_grant, claims.grant()) { (None, None) => Ok(None), (Some(source), Some(grant)) => { - if permission.actor_kind != Some(crate::contract::ActorKindSource::Agent) - || !grant - .bounds() - .breg_permissions() - .is_some_and(|permissions| { - permissions.iter().any(|bound| { - bound.collection() == format!("action:{}", action.id) - && bound - .operations() - .iter() - .any(|operation| operation == "invoke") - }) + if permission.actor_kind != Some(crate::contract::ActorKindSource::Agent) { + return Err(FailedCheck::ActorKind); + } + if !grant + .bounds() + .breg_permissions() + .is_some_and(|permissions| { + permissions.iter().any(|bound| { + bound.collection() == format!("action:{}", action.id) + && bound + .operations() + .iter() + .any(|operation| operation == "invoke") }) + }) { - return Err(()); + return Err(FailedCheck::TaskGrantScope); } bind_task_grant(&source.source_issuer, claims) .map(Some) - .map_err(|_| ()) + .map_err(|refusal| refusal.check) } - _ => Err(()), + (Some(_), None) => Err(FailedCheck::TaskGrantMissing), + (None, Some(_)) => Err(FailedCheck::TaskGrantScope), } } @@ -284,7 +315,7 @@ pub(super) async fn dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let (options, valid_options) = match QueryOptions::parse(raw_query.as_deref(), false) { Ok(options) => (options, true), @@ -293,10 +324,11 @@ pub(super) async fn dispatch( let refusal = |response| action_refusal(mutations, &route, &claims, &options, &correlation, response); if !valid_options { - return refusal(concealed()).await; + return refusal(concealed(FailedCheck::Visibility)).await; } - let Some(surface) = authorize_action(&service, &route, &claims, &options) else { - return refusal(concealed()).await; + let surface = match authorize_action_checked(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(check) => return refusal(concealed(check)).await, }; if !single_content_type(&headers, "application/json") { return refusal(unsupported_media_type()).await; @@ -399,11 +431,17 @@ pub(super) async fn dispatch( .await { Ok(availability::Availability::NotSatisfied { guard_reason, .. }) => { - crate::correlation::action_guard_failure_response(guard_reason) + crate::correlation::note_refusal( + crate::correlation::action_guard_failure_response(guard_reason), + FailedCheck::ActionGuard, + ) } // Visibility and the record may have changed since rollback. // Never turn the private cause into an existence oracle. - _ => precondition_failed(), + _ => crate::correlation::note_refusal( + precondition_failed(), + FailedCheck::ActionGuard, + ), } } Err(error) => mutation_problem(error), @@ -421,7 +459,9 @@ pub(super) async fn dispatch( .await { Ok(response) => exact_non_record_no_store(response), - Err(crate::mutation::MutationError::PreconditionFailed) => concealed(), + Err(crate::mutation::MutationError::PreconditionFailed) => { + concealed(FailedCheck::RowBoundary) + } Err(error) => mutation_problem(error), } } diff --git a/crates/registry-breg/src/api/actions/availability.rs b/crates/registry-breg/src/api/actions/availability.rs index 5f1e89ea6b..d65040b0d0 100644 --- a/crates/registry-breg/src/api/actions/availability.rs +++ b/crates/registry-breg/src/api/actions/availability.rs @@ -238,7 +238,7 @@ pub(in crate::api) async fn observe_target( ReadServiceError::FieldEncryptionUnavailable => field_encryption_unavailable(), _ => unavailable(), })? - .ok_or_else(concealed)?; + .ok_or_else(|| concealed(FailedCheck::Visibility))?; // Held bytes have already passed the ordinary GET terminal audit gate. let value: Value = serde_json::from_slice(read.body()).map_err(|_| unavailable())?; let data = value @@ -277,7 +277,7 @@ pub(in crate::api) async fn observe_target( ) .map_err(|_| unavailable())? { - return Err(concealed()); + return Err(concealed(FailedCheck::RowBoundary)); } Ok(Some(ObservedTarget { revision, current })) } diff --git a/crates/registry-breg/src/api/attachments.rs b/crates/registry-breg/src/api/attachments.rs index 412a09eafa..fb52f50999 100644 --- a/crates/registry-breg/src/api/attachments.rs +++ b/crates/registry-breg/src/api/attachments.rs @@ -71,40 +71,47 @@ async fn authorize( method: HttpMethod, correlation: &RequestCorrelation, ) -> Result<(String, ProposalAuthority), Response> { - let mutations = service.mutations.as_ref().ok_or_else(concealed)?; + let mutations = service + .mutations + .as_ref() + .ok_or_else(|| concealed(FailedCheck::Visibility))?; let action_id = mutations .proposal_action_id(id) .await .map_err(super::proposals::proposal_problem)? - .ok_or_else(concealed)?; + .ok_or_else(|| concealed(FailedCheck::Visibility))?; let action = service .registry .actions() .actions .iter() .find(|action| action.id == action_id) - .ok_or_else(concealed)?; + .ok_or_else(|| concealed(FailedCheck::Visibility))?; let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return Err(concealed()); + return Err(concealed(FailedCheck::Operation)); }; - let Some(authority) = super::proposals::authorize( + let authority = match super::proposals::authorize_checked( &service.registry, action, claims, selected, ProposalAuthorityOperation::Lifecycle(operation), Some(id), - ) else { - return Err(super::proposals::known_action_refusal( - mutations, - action, - claims, - selected, - ProposalAuthorityOperation::Lifecycle(operation), - method, - correlation, - ) - .await); + ) { + Ok(authority) => authority, + Err(check) => { + return Err(super::proposals::known_action_refusal( + mutations, + action, + claims, + selected, + ProposalAuthorityOperation::Lifecycle(operation), + method, + correlation, + check, + ) + .await); + } }; let grant = proposal.permissions.iter().find(|grant| { grant.profile_id == authority.common.access_profile() @@ -125,7 +132,7 @@ async fn authorize( &authority, method, correlation, - concealed(), + concealed(FailedCheck::Operation), ) .await); } @@ -145,13 +152,13 @@ async fn mutate( removal: bool, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = super::proposals::selected_profile(raw.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let (action_id, authority) = match authorize( &service, @@ -211,7 +218,7 @@ async fn mutate( .find(|action| action.id == action_id) .expect("admitted Action"); let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return concealed(); + return concealed(FailedCheck::Operation); }; let definition = &proposal.attachments[&slot]; let (content_type, bytes) = if removal { @@ -322,13 +329,13 @@ async fn download( RawQuery(raw): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(query) = parse_download_query(raw.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let (field, operation) = match &query.review { Some(review) => ( @@ -360,7 +367,7 @@ async fn download( .iter() .find(|action| action.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(records) = super::proposals::review_record_authorities( &service.registry, @@ -375,7 +382,7 @@ async fn download( &authority, HttpMethod::Get, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; }; @@ -411,7 +418,7 @@ async fn download( .header(VARY, "authorization") .body(Body::from(bytes)) .unwrap_or_else(|_| unavailable()), - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => super::proposals::proposal_problem(error), } } diff --git a/crates/registry-breg/src/api/external_views.rs b/crates/registry-breg/src/api/external_views.rs index 6c7a752fe9..1446b481ed 100644 --- a/crates/registry-breg/src/api/external_views.rs +++ b/crates/registry-breg/src/api/external_views.rs @@ -178,20 +178,27 @@ fn root_context( access_profile: Option, claims: &VerifiedRequestClaims, headers: &HeaderMap, -) -> Option { - let route = service.registry.routes().routes.iter().find(|route| { - route.entity_id == view.record_type.as_str() - && route.operation == operation - && read_path_for_route(service, route).is_none() - })?; +) -> Result { + let route = service + .registry + .routes() + .routes + .iter() + .find(|route| { + route.entity_id == view.record_type.as_str() + && route.operation == operation + && read_path_for_route(service, route).is_none() + }) + .ok_or(FailedCheck::AccessProfile)?; let mut options = QueryOptions::default(); options.parsed.access_profile = access_profile; - let authorised = authorize_route(service, route, claims, &options)?; + let authorised = authorize_route_with_reason(service, route, claims, &options) + .map_err(|refusal| refusal.check)?; let mut context = authorised.context; context .bind_access_attribution(authorised.response_entity, headers) - .ok()?; - Some(context) + .map_err(|_| FailedCheck::Delegation)?; + Ok(context) } fn refresh_deadline( @@ -354,7 +361,7 @@ fn worker_request( &claims, &HeaderMap::new(), ) - .ok_or(ExternalViewError::Concealed)?; + .map_err(|_| ExternalViewError::Concealed)?; Ok(ExternalViewRequest { context, correlation: RequestCorrelation::breg_created(), @@ -378,25 +385,43 @@ async fn admit_source_change( request: axum::extract::Request, ) -> Response { let Some(backend) = service.external_views.as_ref() else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(plan) = backend.managed_plan(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let permits = |notifier: &crate::external_refresh_config::ResolvedExternalRefreshNotifier| { - claims.actor_kind() == Some(ActorKind::Service) - && claims.principal().is_some() - && claims.requester_client() == Some(notifier.requester_client.as_str()) - && claims.has_scope(¬ifier.required_scope) + if claims.actor_kind() != Some(ActorKind::Service) { + Err(FailedCheck::ActorKind) + } else if claims.principal().is_none() { + Err(FailedCheck::TokenClaims) + } else if claims.requester_client() != Some(notifier.requester_client.as_str()) { + Err(FailedCheck::RequesterClient) + } else if !claims.has_scope(¬ifier.required_scope) { + Err(FailedCheck::Scope) + } else { + Ok(()) + } }; - if !plan.notifiers.values().any(permits) { - return concealed(); + if !plan + .notifiers + .values() + .any(|notifier| permits(notifier).is_ok()) + { + let check = plan + .notifiers + .values() + .find_map(|notifier| permits(notifier).err()) + .unwrap_or(FailedCheck::AccessProfile); + return concealed(check); } let Some(change) = refresh_body::(request).await else { return invalid_request(); }; - if !plan.notifiers.get(&change.projection).is_some_and(permits) { - return concealed(); + match plan.notifiers.get(&change.projection).map(permits) { + Some(Ok(())) => {} + Some(Err(check)) => return concealed(check), + None => return concealed(FailedCheck::AccessProfile), } if !service .registry @@ -404,7 +429,7 @@ async fn admit_source_change( .projections .contains_key(&change.projection) { - return concealed(); + return concealed(FailedCheck::Visibility); } if !registry_adapter_core::projection_token_valid(&change.selector) { return invalid_request(); @@ -516,14 +541,14 @@ async fn handle( ) -> Response { let inventory = service.registry.external_views(); let Some(view) = inventory.views.get(&target.view) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(link) = view .links .iter() .find(|link| link.id.as_str() == target.link) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(projection) = inventory.projections.get(link.projection.as_str()) else { return unavailable(); @@ -535,26 +560,27 @@ async fn handle( Operation::List }; let profile_selection = admission_profile(raw.as_deref()); - let Some(context) = root_context( + let context = match root_context( service, view, root_operation, profile_selection.clone(), claims, headers, - ) else { - return concealed(); + ) { + Ok(context) => context, + Err(check) => return concealed(check), }; let profile = context.selected_profile(); if context.purpose() != Some(projection.purpose.as_str()) { - return concealed(); + return concealed(FailedCheck::Purpose); } let grant = if target.refresh { let Some(ids) = inventory.refresh.get(profile) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; if projection.mode != ExternalProjectionMode::Indexed || !ids.contains(&projection.id) { - return concealed(); + return concealed(FailedCheck::Visibility); } None } else { @@ -564,20 +590,20 @@ async fn handle( .and_then(|views| views.get(&target.view)) .and_then(|grant| grant.links.iter().find(|grant| grant.link == link.id)) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; if !is_detail && (projection.mode != ExternalProjectionMode::Indexed || projection.cardinality != ExternalCardinality::One) { - return concealed(); + return concealed(FailedCheck::Visibility); } Some(grant) }; let root = match target.root { Some(root) => match Uuid::parse_str(&root) { Ok(id) if id.hyphenated().to_string() == root => Some(id), - _ => return concealed(), + _ => return concealed(FailedCheck::Visibility), }, None => None, }; @@ -627,7 +653,7 @@ async fn handle( fn external_view_problem(error: ExternalViewError) -> Response { match error { - ExternalViewError::Concealed => concealed(), + ExternalViewError::Concealed => concealed(FailedCheck::Visibility), ExternalViewError::InvalidCursor => cursor_invalid(), ExternalViewError::Incomplete => fixed_problem(ProblemCode::ExternalViewIncomplete), ExternalViewError::Unavailable => unavailable(), @@ -880,8 +906,10 @@ mod tests { plan.worker.required_scopes = BTreeSet::from(["registry:licensing:read".to_owned()]); let officer = &service.registry.entities()["licence"].access_profiles["officer"]; assert_eq!( - crate::api::authorize_profile_claims(officer, &plan.worker_claims().unwrap()).err(), - Some("actor-kind-mismatched") + crate::api::authorize_profile_claims(officer, &plan.worker_claims().unwrap()) + .err() + .map(|refusal| (refusal.reason, refusal.check)), + Some(("actor-kind-mismatched", FailedCheck::ActorKind)) ); assert!(refused(&service, &plan)); } diff --git a/crates/registry-breg/src/api/gis.rs b/crates/registry-breg/src/api/gis.rs index f0420b2e6b..4b7ea04a87 100644 --- a/crates/registry-breg/src/api/gis.rs +++ b/crates/registry-breg/src/api/gis.rs @@ -29,6 +29,7 @@ use crate::correlation::RequestCorrelation; use crate::cursor::{CursorAdapter, CursorRepresentation}; use crate::model::{CompiledEntity, CompiledQueryKind, CompiledQueryOperation, CompiledRoute}; use crate::query as strict_query; +use registry_platform_authcommon::FailedCheck; const GIS_ROOT: &str = "/v1/gis"; const SERVICE_DESC_MEDIA_TYPE: &str = "application/vnd.oai.openapi+json;version=3.0"; @@ -247,8 +248,10 @@ async fn collection( RawQuery(raw_query): RawQuery, Path(collection): Path, ) -> Response { - let Some(collection) = authorize_gis_collection(&service, &claims, &collection) else { - return concealed(); + let collection = match authorize_gis_collection_with_reason(&service, &claims, &collection) { + Some(Ok(collection)) => collection, + Some(Err(refusal)) => return concealed(refusal.refusal.check), + None => return concealed(FailedCheck::Visibility), }; if parse_metadata_query(raw_query.as_deref()).is_err() { return invalid_query(); @@ -270,7 +273,7 @@ async fn items( let mut authorized = match authorize_gis_collection_with_reason(&service, &claims, &collection) { Some(Ok(authorized)) => authorized, - Some(Err(refusal)) if refusal.reason == ReadRefusalReason::ProfileAdmission => { + Some(Err(refusal)) if refusal.refusal.reason == ReadRefusalReason::ProfileAdmission => { return audited_read_concealment( &service, refusal.route, @@ -278,11 +281,12 @@ async fn items( &claims, None, &correlation, - refusal.reason, + refusal.refusal, ) .await; } - Some(Err(_)) | None => return concealed(), + Some(Err(refusal)) => return concealed(refusal.refusal.check), + None => return concealed(FailedCheck::Visibility), }; if let Err(binding) = authorized .surface @@ -400,7 +404,7 @@ async fn items( &claims, None, &correlation, - crate::audit::ReadRefusalReason::SelectOverreach, + super::RouteRefusal::select_overreach(), ) .await; } @@ -434,7 +438,7 @@ async fn items( struct GisAdmissionRefusal<'a> { route: &'a CompiledRoute, profile_id: &'a str, - reason: ReadRefusalReason, + refusal: super::RouteRefusal, } struct AuthorizedGisCollection<'a> { @@ -547,11 +551,11 @@ fn authorize_gis_collection_with_reason<'a>( let options = profile_query_options(&operation.profile_id); let surface = match authorize_route_with_reason(service, route, claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return Some(Err(GisAdmissionRefusal { route, profile_id: &operation.profile_id, - reason, + refusal, })) } }; diff --git a/crates/registry-breg/src/api/ingestion.rs b/crates/registry-breg/src/api/ingestion.rs index a92e1e0b43..1894f8f8c2 100644 --- a/crates/registry-breg/src/api/ingestion.rs +++ b/crates/registry-breg/src/api/ingestion.rs @@ -103,7 +103,7 @@ async fn create_run( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -113,19 +113,24 @@ async fn create_run( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; if headers.contains_key("idempotency-key") { return audited_mutation_refusal( @@ -202,7 +207,7 @@ async fn list_runs( RawQuery(raw_query): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let admission = match ingestion_list_admission_options(raw_query.as_deref()) { Ok(options) => options, @@ -214,20 +219,25 @@ async fn list_runs( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; } }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &admission) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &admission, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &admission) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &admission, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; let query = match parse_list_query(raw_query.as_deref()) { Ok(query) => query, @@ -267,7 +277,7 @@ async fn read_run( Path(path): Path>, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -277,19 +287,24 @@ async fn read_run( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; let Some(run_id) = path_run_id(&path) else { return audited_mutation_refusal( @@ -297,7 +312,7 @@ async fn read_run( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -323,7 +338,7 @@ async fn cancel_run( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -333,19 +348,24 @@ async fn cancel_run( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; if headers.contains_key("idempotency-key") { return audited_mutation_refusal( @@ -386,7 +406,7 @@ async fn cancel_run( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -431,7 +451,7 @@ async fn submit_chunk( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -441,19 +461,24 @@ async fn submit_chunk( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; // The chunk items are the batch items of the compiled route, so the // entity must carry a batch surface at all. @@ -529,7 +554,7 @@ async fn submit_chunk( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -579,7 +604,7 @@ async fn chunk_receipt( Path(path): Path>, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -589,19 +614,24 @@ async fn chunk_receipt( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; let Some(run_id) = path_run_id(&path) else { return audited_mutation_refusal( @@ -609,7 +639,7 @@ async fn chunk_receipt( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -620,7 +650,7 @@ async fn chunk_receipt( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -677,10 +707,11 @@ fn ingestion_problem(error: IngestionServiceError) -> Response { IngestionServiceError::RequestInvalid | IngestionServiceError::InvalidTimerWindow { .. } => invalid_request(), IngestionServiceError::PreconditionFailed => precondition_failed(), - IngestionServiceError::NotFound => concealed(), - IngestionServiceError::ProfileMismatch => { - fixed_problem(ProblemCode::IngestionProfileMismatch) - } + IngestionServiceError::NotFound => concealed(FailedCheck::Visibility), + IngestionServiceError::ProfileMismatch => crate::correlation::note_refusal( + fixed_problem(ProblemCode::IngestionProfileMismatch), + FailedCheck::AccessProfile, + ), IngestionServiceError::RunNotOpen => fixed_problem(ProblemCode::IngestionRunNotOpen), IngestionServiceError::RunBlocked => fixed_problem(ProblemCode::IngestionRunBlocked), IngestionServiceError::ChunkMismatch => fixed_problem(ProblemCode::IngestionChunkMismatch), diff --git a/crates/registry-breg/src/api/mod.rs b/crates/registry-breg/src/api/mod.rs index bfea094a6e..9b926ff42a 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -257,7 +257,7 @@ fn probe_routes(service: Arc) -> Router { } async fn probe_method_not_allowed() -> Response { - concealed() + unknown_route() } /// axum's `get` also answers HEAD by running the whole read under the @@ -423,7 +423,7 @@ async fn openapi( RawQuery(raw_query): RawQuery, ) -> Response { let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let visible = visible_surfaces(&service, &claims, &options); let visible_actions = actions::visible_actions(&service, &claims, &options); @@ -436,7 +436,7 @@ async fn openapi( && visible_statistics.is_empty() && visible_proposals.is_empty() { - return concealed(); + return concealed(FailedCheck::Visibility); } let mut paths = Map::new(); @@ -612,7 +612,7 @@ async fn registry_metadata( RawQuery(raw_query): RawQuery, ) -> Response { let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let surfaces = visible_surfaces(&service, &claims, &options); let operations = metadata::operations(&service, &surfaces); @@ -625,7 +625,7 @@ async fn registry_metadata( && visible_statistics.is_empty() && visible_proposals.is_empty() { - return concealed(); + return concealed(FailedCheck::Visibility); } let mut entities: BTreeMap = BTreeMap::new(); @@ -639,10 +639,10 @@ async fn registry_metadata( for (_, entry) in visible { let Some(response_entity) = service.registry.entities().get(&entry.response_entity_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(dataset_identifier) = response_entity.primary_dataset.as_ref() else { - return concealed(); + return concealed(FailedCheck::Visibility); }; entities .entry(response_entity.id.clone()) @@ -858,14 +858,14 @@ async fn record_schema( RawQuery(raw_query): RawQuery, ) -> Response { let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let surfaces = visible_surfaces(&service, &claims, &options) .into_iter() .filter(|surface| surface.response_entity.id == record_type_id) .collect::>(); let Some(first) = surfaces.first() else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let readable = surfaces @@ -877,7 +877,7 @@ async fn record_schema( }); match filtered_schema(&service, &record_type_id, &readable) { Some(schema) => Json(schema).into_response(), - None => concealed(), + None => concealed(FailedCheck::Visibility), } } @@ -906,7 +906,7 @@ async fn read_dispatch( }; let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { let response = audited_read_concealment( &service, &route, @@ -914,7 +914,7 @@ async fn read_dispatch( &claims, path.get("record_id"), &correlation, - reason, + refusal, ) .await; return response; @@ -960,7 +960,7 @@ async fn read_dispatch( &route, &surface, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -971,7 +971,7 @@ async fn read_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -989,7 +989,7 @@ async fn read_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Disclosure), &correlation, Some(ReadRefusalReason::SelectOverreach), ) @@ -1002,7 +1002,7 @@ async fn read_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Disclosure), &correlation, ) .await; @@ -1029,7 +1029,7 @@ async fn read_dispatch( surface.response_entity, public_deployment_prefix(&service), ), - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(ReadServiceError::Unavailable | ReadServiceError::SnapshotUnreadable) => { unavailable() } @@ -1048,7 +1048,7 @@ async fn read_dispatch( &route, &surface, path.get("record_id"), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1107,7 +1107,7 @@ async fn read_dispatch( &route, &surface, path.get("record_id"), - concealed(), + concealed(FailedCheck::Disclosure), &correlation, ) .await; @@ -1118,7 +1118,7 @@ async fn read_dispatch( &route, &surface, path.get("record_id"), - concealed(), + concealed(FailedCheck::Disclosure), &correlation, ) .await; @@ -1163,7 +1163,7 @@ async fn read_dispatch( Err(ReadServiceError::CursorInvalid) => cursor_invalid(), } } - _ => concealed(), + _ => concealed(FailedCheck::Operation), } } @@ -1192,7 +1192,7 @@ async fn lookup_dispatch( }; let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_read_concealment( &service, &route, @@ -1200,7 +1200,7 @@ async fn lookup_dispatch( &claims, None, &correlation, - reason, + refusal, ) .await; } @@ -1248,7 +1248,7 @@ async fn lookup_dispatch( &route, &surface, None, - concealed(), + concealed(FailedCheck::Disclosure), &correlation, Some(ReadRefusalReason::SelectOverreach), ) @@ -1328,8 +1328,15 @@ async fn lookup_dispatch( } }; if !readable_fields.is_subset(&surface.readable_fields) { - return audited_read_refusal(&service, &route, &surface, None, concealed(), &correlation) - .await; + return audited_read_refusal( + &service, + &route, + &surface, + None, + concealed(FailedCheck::Disclosure), + &correlation, + ) + .await; } let Some(operation) = lookup_query_operation_for_selector(&service, &route, &surface, &selector.selector_id) @@ -1348,8 +1355,15 @@ async fn lookup_dispatch( .iter() .all(|field| operation.projection_fields.contains(field)) { - return audited_read_refusal(&service, &route, &surface, None, concealed(), &correlation) - .await; + return audited_read_refusal( + &service, + &route, + &surface, + None, + concealed(FailedCheck::Disclosure), + &correlation, + ) + .await; } let request = RecordReadRequest { entity_id: route.entity_id.clone(), @@ -1371,7 +1385,7 @@ async fn lookup_dispatch( surface.response_entity, public_deployment_prefix(&service), ), - Ok(None) => lookup_unresolved(), + Ok(None) => crate::correlation::note_refusal(lookup_unresolved(), FailedCheck::Visibility), Err(ReadServiceError::Unavailable | ReadServiceError::SnapshotUnreadable) => unavailable(), Err(ReadServiceError::FieldEncryptionUnavailable) => field_encryption_unavailable(), Err(ReadServiceError::CursorInvalid) => cursor_invalid(), @@ -1426,7 +1440,7 @@ async fn revision_dispatch( Path(path): Path>, ) -> Response { let Some(revisions) = &service.revisions else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let options = match QueryOptions::parse(raw_query.as_deref(), false) { Ok(options) => options, @@ -1444,7 +1458,7 @@ async fn revision_dispatch( }; let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_revision_concealment( revisions.as_ref(), &route, @@ -1452,7 +1466,7 @@ async fn revision_dispatch( &claims, path.get("record_id"), &correlation, - reason, + refusal, ) .await; } @@ -1480,7 +1494,7 @@ async fn revision_dispatch( &route, &surface, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1497,7 +1511,7 @@ async fn revision_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1510,7 +1524,7 @@ async fn revision_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1522,7 +1536,7 @@ async fn revision_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1559,7 +1573,7 @@ async fn revision_dispatch( surface.response_entity, public_deployment_prefix(&service), ), - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(ReadServiceError::FieldEncryptionUnavailable) => field_encryption_unavailable(), Err(_) => unavailable(), }, @@ -1569,11 +1583,11 @@ async fn revision_dispatch( surface.response_entity, public_deployment_prefix(&service), ), - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(ReadServiceError::FieldEncryptionUnavailable) => field_encryption_unavailable(), Err(_) => unavailable(), }, - None => concealed(), + None => concealed(FailedCheck::Operation), } } @@ -1586,7 +1600,7 @@ async fn snapshot_dispatch( headers: HeaderMap, ) -> Response { let Some(snapshots) = &service.snapshots else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let options = match QueryOptions::parse_snapshot(raw_query.as_deref()) { Ok(options) => options, @@ -1596,7 +1610,7 @@ async fn snapshot_dispatch( &route, &claims, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1604,7 +1618,7 @@ async fn snapshot_dispatch( }; let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_read_concealment( &service, &route, @@ -1612,7 +1626,7 @@ async fn snapshot_dispatch( &claims, None, &correlation, - reason, + refusal, ) .await; } @@ -1750,7 +1764,7 @@ async fn audited_revision_concealment( claims: &VerifiedRequestClaims, target_record: Option<&String>, correlation: &RequestCorrelation, - reason: ReadRefusalReason, + refusal: RouteRefusal, ) -> Response { let selected_access_profile = options.access_profile().and_then(|profile| { route @@ -1761,7 +1775,7 @@ async fn audited_revision_concealment( }); match revisions .refusal(RevisionReadRefusal { - refusal_reason: Some(reason), + refusal_reason: Some(refusal.reason), method: route.method, operation_id: route.id.clone(), target_record: target_record.cloned(), @@ -1773,7 +1787,7 @@ async fn audited_revision_concealment( }) .await { - Ok(()) => concealed(), + Ok(()) => concealed(refusal.check), Err(_) => unavailable(), } } @@ -1866,7 +1880,7 @@ async fn audited_read_concealment( claims: &VerifiedRequestClaims, target_record: Option<&String>, correlation: &RequestCorrelation, - reason: ReadRefusalReason, + refusal: RouteRefusal, ) -> Response { let selected_access_profile = options.access_profile().and_then(|profile| { route @@ -1879,7 +1893,7 @@ async fn audited_read_concealment( .read_refusal( route.operation, RecordReadRefusal { - refusal_reason: Some(reason), + refusal_reason: Some(refusal.reason), method: route.method, operation_id: route.id.clone(), target_record: target_record.cloned(), @@ -1892,7 +1906,7 @@ async fn audited_read_concealment( ) .await { - Ok(()) => concealed(), + Ok(()) => concealed(refusal.check), Err(_) => unavailable(), } } @@ -1907,7 +1921,7 @@ async fn create_dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -1917,19 +1931,24 @@ async fn create_dispatch( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(mut surface) = authorize_route(&service, &route, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &route, - &options, - &claims, - None, - &correlation, - ) - .await; + let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &route, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; if let Err(binding) = surface.context.bind_access_reason(&headers) { return audited_mutation_refusal( @@ -2038,7 +2057,7 @@ async fn patch_dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(record_id) = path.get("record_id") else { return invalid_request(); @@ -2051,19 +2070,24 @@ async fn patch_dispatch( &claims, Some(record_id.as_str()), &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(mut surface) = authorize_route(&service, &route, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &route, - &options, - &claims, - Some(record_id.as_str()), - &correlation, - ) - .await; + let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &route, + &options, + &claims, + Some(record_id.as_str()), + &correlation, + refusal.check, + ) + .await; + } }; if let Err(binding) = surface.context.bind_access_reason(&headers) { return audited_mutation_refusal( @@ -2207,7 +2231,7 @@ async fn batch_dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -2217,19 +2241,24 @@ async fn batch_dispatch( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(mut surface) = authorize_route(&service, &route, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &route, - &options, - &claims, - None, - &correlation, - ) - .await; + let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &route, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; if let Err(binding) = surface.context.bind_access_reason(&headers) { return audited_mutation_refusal( @@ -2354,7 +2383,7 @@ async fn tombstone_dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(record_id) = path.get("record_id") else { return invalid_request(); @@ -2367,19 +2396,24 @@ async fn tombstone_dispatch( &claims, Some(record_id.as_str()), &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(mut surface) = authorize_route(&service, &route, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &route, - &options, - &claims, - Some(record_id.as_str()), - &correlation, - ) - .await; + let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &route, + &options, + &claims, + Some(record_id.as_str()), + &correlation, + refusal.check, + ) + .await; + } }; if let Err(binding) = surface.context.bind_access_reason(&headers) { return audited_mutation_refusal( @@ -2520,6 +2554,7 @@ async fn audited_mutation_concealment( claims: &VerifiedRequestClaims, target_record: Option<&str>, correlation: &RequestCorrelation, + check: FailedCheck, ) -> Response { // Only a profile the compiled route grants may reach the journal, so an // unknown caller-supplied value is recorded as absent. @@ -2546,7 +2581,7 @@ async fn audited_mutation_concealment( }) .await { - Ok(()) => concealed(), + Ok(()) => concealed(check), Err(_) => mutation_problem(MutationError::Unavailable), } } @@ -2566,7 +2601,7 @@ async fn not_found( { statistics::unknown(&service, &claims, &correlation, &method).await } - _ => concealed(), + _ => unknown_route(), } } @@ -2625,6 +2660,45 @@ fn metadata_entry_for_surface<'a>( Some((entity, entry)) } +/// A route the caller was not admitted to. The reason is the audit journal's +/// closed vocabulary. The check is the operator's, and it names which +/// admission rule refused, which the reason alone cannot. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct RouteRefusal { + pub(crate) reason: ReadRefusalReason, + pub(crate) check: FailedCheck, +} + +impl RouteRefusal { + const fn surface(check: FailedCheck) -> Self { + Self { + reason: ReadRefusalReason::SurfaceUnavailable, + check, + } + } + + const fn admission(refusal: ClaimRefusal) -> Self { + Self { + reason: ReadRefusalReason::ProfileAdmission, + check: refusal.check, + } + } + + const fn admission_check(check: FailedCheck) -> Self { + Self { + reason: ReadRefusalReason::ProfileAdmission, + check, + } + } + + const fn select_overreach() -> Self { + Self { + reason: ReadRefusalReason::SelectOverreach, + check: FailedCheck::Disclosure, + } + } +} + fn authorize_route<'a>( service: &'a HttpService, route: &'a CompiledRoute, @@ -2639,7 +2713,7 @@ fn authorize_route_with_reason<'a>( route: &'a CompiledRoute, claims: &VerifiedRequestClaims, options: &QueryOptions, -) -> Result, ReadRefusalReason> { +) -> Result, RouteRefusal> { if let Some((read_path, response_entity)) = read_path_for_route(service, route) { return authorize_read_path_route( service, @@ -2697,7 +2771,7 @@ fn authorize_direct_route<'a>( route: &'a CompiledRoute, claims: &VerifiedRequestClaims, options: &QueryOptions, -) -> Result, ReadRefusalReason> { +) -> Result, RouteRefusal> { if claims.grant().is_none() && (claims.actor_subject().is_some() || claims.actor_kind() == Some(registry_platform_oidc::ActorKind::Agent)) @@ -2710,40 +2784,40 @@ fn authorize_direct_route<'a>( | Operation::Import ) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::TaskGrantMissing)); } - let access = - access_entry_for_route(service, route).ok_or(ReadRefusalReason::SurfaceUnavailable)?; + let access = access_entry_for_route(service, route) + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let selected_profile = options .access_profile() .map(String::as_str) .or(access.default_profile_id.as_deref()) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; if !access.profile_ids.contains(selected_profile) || !route .access_profiles .iter() .any(|id| id == selected_profile) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::AccessProfile)); } let entity = service .registry .entities() .get(&route.entity_id) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let profile = entity .access_profiles .get(selected_profile) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; if !profile.operations.contains(&route.operation) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::Operation)); } if route.operation == Operation::Revisions && !profile.revision_access { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::Operation)); } - let row_boundaries = authorize_profile_claims(profile, claims) - .map_err(|_| ReadRefusalReason::ProfileAdmission)?; + let row_boundaries = + authorize_profile_claims(profile, claims).map_err(RouteRefusal::admission)?; let readable_fields = profile .readable_fields .iter() @@ -2762,9 +2836,7 @@ fn authorize_direct_route<'a>( selected_profile.to_owned(), row_boundaries, ) - .with_task_grant( - task_grant_binding(profile, claims).map_err(|_| ReadRefusalReason::ProfileAdmission)?, - ) + .with_task_grant(task_grant_binding(profile, claims).map_err(RouteRefusal::admission)?) .with_audit_context(claims) .with_recipients(claims) .with_access_reason_requirement(profile.require_access_reason); @@ -2785,41 +2857,41 @@ fn authorize_read_path_route<'a>( response_entity: &'a CompiledEntity, claims: &VerifiedRequestClaims, options: &QueryOptions, -) -> Result, ReadRefusalReason> { - let access = - access_entry_for_route(service, route).ok_or(ReadRefusalReason::SurfaceUnavailable)?; +) -> Result, RouteRefusal> { + let access = access_entry_for_route(service, route) + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let selected_profile = options .access_profile() .map(String::as_str) .or(access.default_profile_id.as_deref()) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; if !access.profile_ids.contains(selected_profile) || !route .access_profiles .iter() .any(|id| id == selected_profile) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::AccessProfile)); } let entity = service .registry .entities() .get(&route.entity_id) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let profile = entity .access_profiles .get(selected_profile) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let grant = profile .read_paths .iter() .find(|grant| grant.path == read_path.id) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::Operation))?; if route.operation != Operation::List || route.query_kind != Some(CompiledQueryKind::List) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::Operation)); } - let row_boundaries = authorize_profile_claims(profile, claims) - .map_err(|_| ReadRefusalReason::ProfileAdmission)?; + let row_boundaries = + authorize_profile_claims(profile, claims).map_err(RouteRefusal::admission)?; let readable_fields = grant.readable_fields.iter().cloned().collect(); Ok(AuthorizedSurface { route, @@ -2831,9 +2903,7 @@ fn authorize_read_path_route<'a>( selected_profile.to_owned(), row_boundaries, ) - .with_task_grant( - task_grant_binding(profile, claims).map_err(|_| ReadRefusalReason::ProfileAdmission)?, - ) + .with_task_grant(task_grant_binding(profile, claims).map_err(RouteRefusal::admission)?) .with_audit_context(claims) .with_recipients(claims) .with_access_reason_requirement(profile.require_access_reason), @@ -2917,33 +2987,60 @@ fn served_operation(service: &HttpService, route: &CompiledRoute) -> bool { } } +/// Why a profile or a task grant did not admit a request. The reason is the +/// offline preview's vocabulary and the check is the operator's. Neither +/// crosses the public HTTP concealment boundary. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct ClaimRefusal { + pub(crate) reason: &'static str, + pub(crate) check: FailedCheck, +} + +impl ClaimRefusal { + const fn new(reason: &'static str, check: FailedCheck) -> Self { + Self { reason, check } + } +} + /// Shared by real HTTP admission and offline synthetic access previews. /// Detailed reasons never cross the public HTTP concealment boundary. pub(crate) fn authorize_profile_claims( profile: &AccessProfileSource, claims: &VerifiedRequestClaims, -) -> Result, &'static str> { +) -> Result, ClaimRefusal> { if Some(profile.principal_claim.as_str()) != claims.principal_claim() || claims.principal().is_none() { - return Err("principal-missing-or-mismatched"); + return Err(ClaimRefusal::new( + "principal-missing-or-mismatched", + FailedCheck::TokenClaims, + )); } if !profile .required_scopes .iter() .all(|scope| claims.has_scope(scope)) { - return Err("required-scope-missing"); + return Err(ClaimRefusal::new( + "required-scope-missing", + FailedCheck::Scope, + )); } if !profile.required_purposes.is_empty() && !claims .purpose() .is_some_and(|purpose| profile.required_purposes.contains(purpose)) { - return Err("purpose-missing-or-not-allowed"); + return Err(ClaimRefusal::new( + "purpose-missing-or-not-allowed", + FailedCheck::Purpose, + )); } if let Some(expected) = profile.actor_kind { - let actual = claims.actor_kind().ok_or("actor-kind-missing")?; + let actual = claims.actor_kind().ok_or(ClaimRefusal::new( + "actor-kind-missing", + FailedCheck::ActorKind, + ))?; let matches = matches!( (expected, actual), ( @@ -2958,7 +3055,10 @@ pub(crate) fn authorize_profile_claims( ) ); if !matches { - return Err("actor-kind-mismatched"); + return Err(ClaimRefusal::new( + "actor-kind-mismatched", + FailedCheck::ActorKind, + )); } } // A delegated token acts for its principal; only a profile written for @@ -2966,44 +3066,72 @@ pub(crate) fn authorize_profile_claims( if claims.actor_subject().is_some() && profile.actor_kind != Some(crate::contract::ActorKindSource::Agent) { - return Err("delegated_actor_requires_agent_profile"); + return Err(ClaimRefusal::new( + "delegated_actor_requires_agent_profile", + FailedCheck::Delegation, + )); } if !profile.requester_clients.is_empty() && !claims .requester_client() .is_some_and(|client| profile.requester_clients.contains(client)) { - return Err("requester-client-missing-or-mismatched"); + return Err(ClaimRefusal::new( + "requester-client-missing-or-mismatched", + FailedCheck::RequesterClient, + )); } match (&profile.task_grant, claims.grant()) { - (Some(_), None) => return Err("task_grant_missing"), - (None, Some(_)) => return Err("task_grant_profile_required"), + (Some(_), None) => { + return Err(ClaimRefusal::new( + "task_grant_missing", + FailedCheck::TaskGrantMissing, + )) + } + (None, Some(_)) => { + return Err(ClaimRefusal::new( + "task_grant_profile_required", + FailedCheck::TaskGrantScope, + )) + } (None, None) if profile.actor_kind == Some(crate::contract::ActorKindSource::Agent) && claims.actor_subject().is_none() => { - return Err("trusted_actor_missing"); + return Err(ClaimRefusal::new( + "trusted_actor_missing", + FailedCheck::Delegation, + )); } _ => {} } - verified_row_boundaries(profile, claims).ok_or("row-claim-missing-or-wrong-cardinality") + verified_row_boundaries(profile, claims).ok_or(ClaimRefusal::new( + "row-claim-missing-or-wrong-cardinality", + FailedCheck::RowBoundary, + )) } fn task_grant_binding( profile: &AccessProfileSource, claims: &VerifiedRequestClaims, -) -> Result, &'static str> { +) -> Result, ClaimRefusal> { let Some(expected) = &profile.task_grant else { return Ok(None); }; - let grant = claims.grant().ok_or("task_grant_missing")?; + let grant = claims.grant().ok_or(ClaimRefusal::new( + "task_grant_missing", + FailedCheck::TaskGrantMissing, + ))?; if !profile.required_purposes.contains(grant.purpose()) { - return Err("task_grant_binding_mismatched"); + return Err(ClaimRefusal::new( + "task_grant_binding_mismatched", + FailedCheck::TaskGrantBinding, + )); } - let actual = grant - .bounds() - .breg_permissions() - .ok_or("task_grant_bounds_wrong_type")?; + let actual = grant.bounds().breg_permissions().ok_or(ClaimRefusal::new( + "task_grant_bounds_wrong_type", + FailedCheck::TaskGrantScope, + ))?; let actual = actual .iter() .map(|permission| { @@ -3033,7 +3161,10 @@ fn task_grant_binding( Some((permission.collection.clone(), operations)) }) .collect::>>() - .ok_or("task_grant_bounds_invalid")?; + .ok_or(ClaimRefusal::new( + "task_grant_bounds_invalid", + FailedCheck::TaskGrantScope, + ))?; // A verified token can compose independently scoped Proposal authority. // Record routes still use only this static profile's fields and operations. if !expected_bounds.iter().all(|(collection, operations)| { @@ -3041,7 +3172,10 @@ fn task_grant_binding( .get(collection) .is_some_and(|actual| operations.is_subset(actual)) }) { - return Err("task_grant_bounds_mismatched"); + return Err(ClaimRefusal::new( + "task_grant_bounds_mismatched", + FailedCheck::TaskGrantScope, + )); } bind_task_grant(&expected.source_issuer, claims).map(Some) } @@ -3053,20 +3187,29 @@ fn task_grant_binding( fn bind_task_grant( source_issuer: &str, claims: &VerifiedRequestClaims, -) -> Result { - let grant = claims.grant().ok_or("task_grant_missing")?; +) -> Result { + let grant = claims.grant().ok_or(ClaimRefusal::new( + "task_grant_missing", + FailedCheck::TaskGrantMissing, + ))?; if grant.source_issuer() != source_issuer || Some(grant.client()) != claims.requester_client() || Some(grant.principal()) != claims.principal() || Some(grant.purpose()) != claims.purpose() { - return Err("task_grant_binding_mismatched"); + return Err(ClaimRefusal::new( + "task_grant_binding_mismatched", + FailedCheck::TaskGrantBinding, + )); } let binding = crate::task_grant::TaskGrantBinding::from_verified(grant, claims.grant_subjects().clone()) - .map_err(|_| "task_grant_invalid")?; + .map_err(|_| ClaimRefusal::new("task_grant_invalid", FailedCheck::TaskGrantClaims))?; if !binding.is_current() { - return Err("task_grant_expired"); + return Err(ClaimRefusal::new( + "task_grant_expired", + FailedCheck::TaskGrantExpired, + )); } Ok(binding) } @@ -4998,7 +5141,15 @@ fn method_name(method: crate::model::HttpMethod) -> &'static str { } } -fn concealed() -> Response { +/// The 404 that hides whether the target exists or what the caller may see. +/// The check names, for the operator only, which rule refused. +fn concealed(check: FailedCheck) -> Response { + crate::correlation::note_refusal(fixed_problem(ProblemCode::ResourceNotFound), check) +} + +/// The 404 of a path or method the service does not serve. No check refused +/// the caller, so nothing is counted. +fn unknown_route() -> Response { fixed_problem(ProblemCode::ResourceNotFound) } @@ -5015,7 +5166,7 @@ fn field_encryption_unavailable() -> Response { /// refused forwarded attribution stays concealed. fn access_binding_refusal(refusal: context::AccessBindingRefusal) -> Response { match refusal { - context::AccessBindingRefusal::Attribution => concealed(), + context::AccessBindingRefusal::Attribution => concealed(FailedCheck::Delegation), context::AccessBindingRefusal::ReasonRequired => { fixed_problem(ProblemCode::RequestAccessReasonRequired) } @@ -5593,12 +5744,21 @@ fn precondition_failed() -> Response { } fn mutation_problem(error: MutationError) -> Response { + let check = error.failed_check(); + let response = mutation_problem_response(error); + match check { + Some(check) => crate::correlation::note_refusal(response, check), + None => response, + } +} + +fn mutation_problem_response(error: MutationError) -> Response { match error { MutationError::InvalidRequest | MutationError::InvalidTimerWindow { .. } => { invalid_request() } MutationError::InvalidRequestAt(location) => invalid_request_at(&location), - MutationError::AuthorizationRefused + MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed | MutationError::FieldGuardFailed { .. } | MutationError::ProposalGuardFailed(_) @@ -6229,3 +6389,84 @@ mod temporal_instant_tests { assert!(normalize_history_valid_at(entity, "2026-06-05T00:00:00+05:30").is_err()); } } + +#[cfg(test)] +mod refusal_check_tests { + use super::*; + use registry_platform_authcommon::RefusalNote; + + fn noted(response: &Response) -> Option { + response + .extensions() + .get::() + .map(|note| note.check) + } + + #[test] + fn a_concealed_answer_carries_its_check_and_an_unknown_route_carries_none() { + let hidden = concealed(FailedCheck::Visibility); + assert_eq!(hidden.status(), StatusCode::NOT_FOUND); + assert_eq!(noted(&hidden), Some(FailedCheck::Visibility)); + let unknown = unknown_route(); + assert_eq!(unknown.status(), StatusCode::NOT_FOUND); + assert_eq!(noted(&unknown), None); + } + + #[test] + fn a_mutation_refusal_names_the_check_and_a_plain_failure_names_none() { + for (error, check) in [ + ( + MutationError::AuthorizationRefused(FailedCheck::Operation), + FailedCheck::Operation, + ), + ( + MutationError::AuthorizationRefused(FailedCheck::TaskGrantScope), + FailedCheck::TaskGrantScope, + ), + ( + MutationError::AuthorizationRefused(FailedCheck::Ownership), + FailedCheck::Ownership, + ), + ( + MutationError::WriteOutsideBoundary, + FailedCheck::RowBoundary, + ), + ( + MutationError::FieldGuardFailed { + input: "input".to_owned(), + }, + FailedCheck::ActionGuard, + ), + ] { + let response = mutation_problem(error); + assert_eq!(noted(&response), Some(check)); + } + for error in [ + MutationError::PreconditionFailed, + MutationError::Conflict, + MutationError::Unavailable, + ] { + assert_eq!(noted(&mutation_problem(error)), None); + } + assert_eq!( + noted(&mutation_problem(MutationError::WriteOutsideBoundary)).map(FailedCheck::as_str), + Some("row-boundary") + ); + } + + #[test] + fn a_route_refusal_keeps_the_audit_reason_beside_the_check() { + let refusal = RouteRefusal::surface(FailedCheck::AccessProfile); + assert_eq!(refusal.reason, ReadRefusalReason::SurfaceUnavailable); + assert_eq!(refusal.check, FailedCheck::AccessProfile); + let overreach = RouteRefusal::select_overreach(); + assert_eq!(overreach.reason, ReadRefusalReason::SelectOverreach); + assert_eq!(overreach.check, FailedCheck::Disclosure); + let admission = RouteRefusal::admission(ClaimRefusal::new( + "task_grant_expired", + FailedCheck::TaskGrantExpired, + )); + assert_eq!(admission.reason, ReadRefusalReason::ProfileAdmission); + assert_eq!(admission.check, FailedCheck::TaskGrantExpired); + } +} diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index c58eb74417..98dfbdf74a 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -12,7 +12,7 @@ use crate::postgres::{ProposalAuthority, ProposalAuthorityOperation, RowBoundary pub(super) fn proposal_problem(error: MutationError) -> Response { match error { - MutationError::AuthorizationRefused => concealed(), + MutationError::AuthorizationRefused(check) => concealed(check), error => mutation_problem(error), } } @@ -156,34 +156,64 @@ fn permission_matches( permission: &CompiledProposalPermission, claims: &VerifiedRequestClaims, standing_own_draft: bool, -) -> bool { - permission.principal_claim.as_deref() == claims.principal_claim() - && permission - .required_scopes - .iter() - .all(|scope| claims.has_scope(scope)) - && (permission.required_purposes.is_empty() - || claims - .purpose() - .is_some_and(|purpose| permission.required_purposes.contains(purpose))) - && actor_matches(permission.actor_kind, claims, standing_own_draft) - && (permission.requester_clients.is_empty() - || claims - .requester_client() - .is_some_and(|client| permission.requester_clients.contains(client))) +) -> Result<(), FailedCheck> { + request_matches( + permission.principal_claim.as_deref(), + &permission.required_scopes, + &permission.required_purposes, + permission.actor_kind, + &permission.requester_clients, + claims, + standing_own_draft, + ) +} + +/// The checks a Proposal permission and an Action start grant share, in the +/// order they are made. The first that fails names itself. +fn request_matches( + principal_claim: Option<&str>, + required_scopes: &BTreeSet, + required_purposes: &BTreeSet, + actor_kind: Option, + requester_clients: &BTreeSet, + claims: &VerifiedRequestClaims, + standing_own_draft: bool, +) -> Result<(), FailedCheck> { + if principal_claim != claims.principal_claim() { + return Err(FailedCheck::TokenClaims); + } + if !required_scopes.iter().all(|scope| claims.has_scope(scope)) { + return Err(FailedCheck::Scope); + } + if !required_purposes.is_empty() + && !claims + .purpose() + .is_some_and(|purpose| required_purposes.contains(purpose)) + { + return Err(FailedCheck::Purpose); + } + actor_matches(actor_kind, claims, standing_own_draft)?; + if !requester_clients.is_empty() + && !claims + .requester_client() + .is_some_and(|client| requester_clients.contains(client)) + { + return Err(FailedCheck::RequesterClient); + } + Ok(()) } fn actor_matches( expected: Option, claims: &VerifiedRequestClaims, standing_own_draft: bool, -) -> bool { +) -> Result<(), FailedCheck> { use crate::contract::ActorKindSource; use registry_platform_oidc::ActorKind; if claims.actor_subject().is_some() && expected != Some(ActorKindSource::Agent) { - return false; + return Err(FailedCheck::Delegation); } - match expected { + let matches = match expected { None => true, Some(ActorKindSource::Human) => claims.actor_kind() == Some(ActorKind::Human), Some(ActorKindSource::Agent) => { @@ -193,6 +223,11 @@ fn actor_matches( || standing_own_draft) } Some(ActorKindSource::Service) => claims.actor_kind() == Some(ActorKind::Service), + }; + if matches { + Ok(()) + } else { + Err(FailedCheck::ActorKind) } } @@ -233,15 +268,28 @@ pub(crate) fn authorize( operation: ProposalAuthorityOperation, proposal_id: Option, ) -> Option { + authorize_checked(registry, action, claims, selected, operation, proposal_id).ok() +} + +/// The admission of a Proposal operation. The refusal names the first check +/// that failed, for the operator only. +pub(crate) fn authorize_checked( + registry: &CompiledRegistry, + action: &CompiledAction, + claims: &VerifiedRequestClaims, + selected: Option<&str>, + operation: ProposalAuthorityOperation, + proposal_id: Option, +) -> Result { let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return None; + return Err(FailedCheck::Operation); }; if matches!( operation, ProposalAuthorityOperation::Lifecycle(ProposalOperation::Apply | ProposalOperation::Retry) ) && !external_recovery_actor_allowed(&proposal.application, Some(claims)) { - return None; + return Err(FailedCheck::ActorKind); } let standing_agent = (claims.actor_subject().is_some() || claims.actor_kind() == Some(registry_platform_oidc::ActorKind::Agent)) @@ -254,31 +302,27 @@ pub(crate) fn authorize( | ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetReviewContext) ) { - return None; + return Err(FailedCheck::TaskGrantMissing); } let (profile, targets, task_source) = match operation { ProposalAuthorityOperation::Start => { - let grant = action.permissions.iter().find(|grant| { - selected.map_or(grant.default, |profile| profile == grant.profile_id) - && grant.operations.contains(&Operation::Start) - })?; - if grant.principal_claim.as_deref() != claims.principal_claim() - || !grant - .required_scopes - .iter() - .all(|scope| claims.has_scope(scope)) - || (!grant.required_purposes.is_empty() - && !claims - .purpose() - .is_some_and(|p| grant.required_purposes.contains(p))) - || !actor_matches(grant.actor_kind, claims, standing_agent) - || (!grant.requester_clients.is_empty() - && !claims - .requester_client() - .is_some_and(|c| grant.requester_clients.contains(c))) - { - return None; - } + let grant = action + .permissions + .iter() + .find(|grant| { + selected.map_or(grant.default, |profile| profile == grant.profile_id) + && grant.operations.contains(&Operation::Start) + }) + .ok_or(FailedCheck::AccessProfile)?; + request_matches( + grant.principal_claim.as_deref(), + &grant.required_scopes, + &grant.required_purposes, + grant.actor_kind, + &grant.requester_clients, + claims, + standing_agent, + )?; let targets = grant .targets .iter() @@ -288,7 +332,8 @@ pub(crate) fn authorize( boundaries(&target.row_boundaries, claims)?, )) }) - .collect::>>()?; + .collect::>>() + .ok_or(FailedCheck::RowBoundary)?; ( grant.profile_id.as_str(), targets, @@ -296,15 +341,19 @@ pub(crate) fn authorize( ) } ProposalAuthorityOperation::Lifecycle(operation) => { - let grant = proposal.permissions.iter().find(|grant| { - selected.map_or(grant.default, |profile| profile == grant.profile_id) - && grant.operations.contains(&operation) - })?; + let grant = proposal + .permissions + .iter() + .find(|grant| { + selected.map_or(grant.default, |profile| profile == grant.profile_id) + && grant.operations.contains(&operation) + }) + .ok_or(FailedCheck::AccessProfile)?; if standing_agent && operation == ProposalOperation::Edit && grant.ownership != Some(crate::model::ProposalOwnership::Caller) { - return None; + return Err(FailedCheck::Operation); } // A standing agent edits only its caller-owned draft. The one // additional operation is current review-context disclosure, and @@ -315,16 +364,14 @@ pub(crate) fn authorize( && operation == ProposalOperation::GetReviewContext && (claims.actor_subject().is_none() || grant.requester_clients.is_empty()) { - return None; - } - if !permission_matches(grant, claims, standing_agent) { - return None; + return Err(FailedCheck::Delegation); } + permission_matches(grant, claims, standing_agent)?; if grant.review_authority.is_some() && (operation != ProposalOperation::GetReviewStatus || claims.actor_kind() != Some(registry_platform_oidc::ActorKind::Service)) { - return None; + return Err(FailedCheck::ActorKind); } let targets = grant .targets @@ -335,7 +382,8 @@ pub(crate) fn authorize( boundaries(&target.row_boundaries, claims)?, )) }) - .collect::>>()?; + .collect::>>() + .ok_or(FailedCheck::RowBoundary)?; ( grant.profile_id.as_str(), targets, @@ -347,20 +395,24 @@ pub(crate) fn authorize( registry, &action.id, operation, - claims.principal()?, + claims.principal().ok_or(FailedCheck::TokenClaims)?, profile, claims.purpose(), targets, ) - .ok()?; + .map_err(|_| FailedCheck::Operation)?; authority.common = authority .common .with_audit_context(crate::audit::RequestAuditContext::from_claims(claims)); match (task_source, claims.grant()) { (None, None) => {} (Some(source), Some(grant)) => { - let binding = bind_task_grant(&source.source_issuer, claims).ok()?; - let bounds = grant.bounds().breg_permissions()?; + let binding = + bind_task_grant(&source.source_issuer, claims).map_err(|refusal| refusal.check)?; + let bounds = grant + .bounds() + .breg_permissions() + .ok_or(FailedCheck::TaskGrantScope)?; let operation_name = crate::mutation::proposal_operation_name(operation); let scope = match operation { ProposalAuthorityOperation::Start => { @@ -369,7 +421,7 @@ pub(crate) fn authorize( bound.collection() == collection && bound.operations().iter().any(|op| op == operation_name) }) { - return None; + return Err(FailedCheck::TaskGrantScope); } None } @@ -384,7 +436,7 @@ pub(crate) fn authorize( }) .collect::>(); if scope.is_empty() || proposal_id.is_some_and(|id| !scope.contains(&id)) { - return None; + return Err(FailedCheck::TaskGrantScope); } Some(scope) } @@ -392,13 +444,14 @@ pub(crate) fn authorize( authority.common = authority .common .with_proposal_task_grant(binding.clone(), operation) - .ok()?; + .map_err(|_| FailedCheck::TaskGrantScope)?; authority.task_grant = Some(binding); authority.proposal_scope = scope; } - _ => return None, + (Some(_), None) => return Err(FailedCheck::TaskGrantMissing), + (None, Some(_)) => return Err(FailedCheck::TaskGrantScope), } - Some(authority) + Ok(authority) } pub(super) fn selected_profile(raw: Option<&str>) -> Result, ()> { @@ -490,6 +543,7 @@ pub(super) async fn known_action_refusal( operation: ProposalAuthorityOperation, method: HttpMethod, correlation: &RequestCorrelation, + check: FailedCheck, ) -> Response { let profile = selected.filter(|profile| match operation { ProposalAuthorityOperation::Start => action.permissions.iter().any(|grant| { @@ -526,7 +580,7 @@ pub(super) async fn known_action_refusal( ) .await { - Ok(()) => concealed(), + Ok(()) => concealed(check), Err(_) => unavailable(), } } @@ -537,6 +591,7 @@ async fn audited_list_concealment( claims: &VerifiedRequestClaims, selected: Option<&str>, correlation: &RequestCorrelation, + check: FailedCheck, ) -> Response { let selected_access_profile = selected.filter(|selected| { service.registry.actions().actions.iter().any(|action| { @@ -565,7 +620,7 @@ async fn audited_list_concealment( }) .await { - Ok(()) => concealed(), + Ok(()) => concealed(check), Err(_) => unavailable(), } } @@ -581,10 +636,10 @@ pub(super) async fn start( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = selected_profile(raw_query.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(action) = service .registry @@ -593,29 +648,33 @@ pub(super) async fn start( .iter() .find(|action| action.id == route.action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; if route.operation != Operation::Start || route.path != action.route { - return concealed(); + return concealed(FailedCheck::Visibility); } - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Start, None, - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Start, - HttpMethod::Post, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Start, + HttpMethod::Post, + &correlation, + check, + ) + .await; + } }; if !single_content_type(&headers, "application/json") { return admitted_http_refusal( @@ -728,17 +787,17 @@ pub(super) async fn get( RawQuery(raw_query): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = selected_profile(raw_query.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -748,33 +807,37 @@ pub(super) async fn get( .iter() .find(|a| a.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), - HttpMethod::Get, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), + HttpMethod::Get, + &correlation, + check, + ) + .await; + } }; match mutations .proposal_document(id, &authority, &claims, &correlation) .await { Ok((value, etag)) => json_response(value, Some(&etag)), - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_problem(error), } } @@ -790,24 +853,24 @@ pub(super) async fn submission( RawQuery(raw_query): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(version) = version .parse::() .ok() .filter(|parsed| *parsed > 0 && parsed.to_string() == version) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = selected_profile(raw_query.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -817,26 +880,30 @@ pub(super) async fn submission( .iter() .find(|a| a.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), - HttpMethod::Get, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), + HttpMethod::Get, + &correlation, + check, + ) + .await; + } }; match mutations .proposal_submission_read(id, version, &authority, &correlation) @@ -844,7 +911,7 @@ pub(super) async fn submission( { Ok(Some(value)) => json_response(value, None), Ok(None) => fixed_problem(ProblemCode::ProposalSubmissionExpired), - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_problem(error), } } @@ -860,10 +927,10 @@ pub(super) async fn transition( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let operation = match operation.as_str() { "edit" => ProposalOperation::Edit, @@ -873,14 +940,14 @@ pub(super) async fn transition( "apply" => ProposalOperation::Apply, "rebase" => ProposalOperation::Rebase, "retry" => ProposalOperation::Retry, - _ => return concealed(), + _ => return concealed(FailedCheck::Operation), }; let Ok(selected) = selected_profile(raw_query.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -890,29 +957,33 @@ pub(super) async fn transition( .iter() .find(|a| a.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(operation), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(operation), - HttpMethod::Post, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(operation), + HttpMethod::Post, + &correlation, + check, + ) + .await; + } }; let rebase_start_authority = if operation == ProposalOperation::Rebase { - match authorize( + match authorize_checked( &service.registry, action, &claims, @@ -920,14 +991,14 @@ pub(super) async fn transition( ProposalAuthorityOperation::Start, None, ) { - Some(authority) => Some(authority), - None => { + Ok(authority) => Some(authority), + Err(check) => { return admitted_http_refusal( mutations, &authority, HttpMethod::Post, &correlation, - concealed(), + concealed(check), ) .await; } @@ -1105,7 +1176,7 @@ pub(super) async fn transition( "", service.field_encryption.as_deref(), ), - Err(MutationError::ProposalGuardFailed(failure)) => { + Err(MutationError::ProposalGuardFailed(failure)) => crate::correlation::note_refusal( guard_failure_response( &service, &authority, @@ -1114,8 +1185,9 @@ pub(super) async fn transition( &correlation, *failure, ) - .await - } + .await, + FailedCheck::ActionGuard, + ), Err(error) => proposal_problem(error), } } @@ -1184,23 +1256,23 @@ pub(super) async fn review_context_batch( RawQuery(raw): RawQuery, ) -> Response { let Some(raw) = raw.filter(|raw| raw.len() <= MAX_RAW_QUERY_BYTES) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let mut ids = None; let mut profile = Vec::new(); for pair in raw.split('&') { let Some((key, value)) = pair.split_once('=') else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(key) = percent_decode(key) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; if key == "ids" { if ids.is_some() { - return concealed(); + return concealed(FailedCheck::Visibility); } let Ok(value) = percent_decode(value) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; ids = Some(value); } else { @@ -1208,7 +1280,7 @@ pub(super) async fn review_context_batch( } } let Some(ids) = ids else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let ids = ids.split(',').collect::>(); let mut distinct = BTreeSet::new(); @@ -1219,11 +1291,11 @@ pub(super) async fn review_context_batch( || !distinct.insert(*id) }) { - return concealed(); + return concealed(FailedCheck::Visibility); } let profile = Some(profile.join("&")); if selected_profile(profile.as_deref()).is_err() { - return concealed(); + return concealed(FailedCheck::Visibility); } // Bound the aggregate independently of each Proposal's configured context. let mut remaining = 8 * 1024 * 1024 - 64 * 1024; @@ -1302,17 +1374,17 @@ pub(super) async fn task_grant_context( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = selected_profile(raw.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -1322,27 +1394,31 @@ pub(super) async fn task_grant_context( .iter() .find(|action| action.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let operation = ProposalOperation::GetTaskGrantContext; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(operation), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(operation), - HttpMethod::Post, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(operation), + HttpMethod::Post, + &correlation, + check, + ) + .await; + } }; if !single_content_type(&headers, "application/json") { return admitted_http_refusal( @@ -1393,13 +1469,13 @@ pub(super) async fn task_grant_context( &authority, HttpMethod::Post, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; } let selected_fields = request.fields.iter().cloned().collect::>(); let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return concealed(); + return concealed(FailedCheck::Operation); }; let granted = proposal.permissions.iter().find(|permission| { permission.profile_id == authority.common.access_profile() @@ -1414,7 +1490,7 @@ pub(super) async fn task_grant_context( &authority, HttpMethod::Post, &correlation, - concealed(), + concealed(FailedCheck::Disclosure), ) .await; } @@ -1431,7 +1507,7 @@ pub(super) async fn task_grant_context( &authority, HttpMethod::Post, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; }; @@ -1455,7 +1531,7 @@ pub(super) async fn task_grant_context( ); response } - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_problem(error), } } @@ -1469,21 +1545,21 @@ async fn review_read( correlation: RequestCorrelation, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok((selected, include_progress)) = (if operation == ProposalOperation::GetReviewStatus { review_status_options(raw.as_deref()) } else { selected_profile(raw.as_deref()).map(|selected| (selected, false)) }) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -1493,26 +1569,30 @@ async fn review_read( .iter() .find(|action| action.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(operation), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(operation), - HttpMethod::Get, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(operation), + HttpMethod::Get, + &correlation, + check, + ) + .await; + } }; let records = review_record_authorities( &service.registry, @@ -1528,7 +1608,7 @@ async fn review_read( &authority, HttpMethod::Get, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; }; @@ -1537,7 +1617,7 @@ async fn review_read( .await { Ok((value, etag)) => json_response(value, etag.as_deref()), - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_problem(error), } } @@ -1634,31 +1714,42 @@ pub(super) async fn list( RawQuery(raw_query): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let selected = match proposal_list_admission_profile(raw_query.as_deref()) { Ok(selected) => selected, Err(()) => { - return audited_list_concealment(mutations, &service, &claims, None, &correlation) - .await; - } - }; - let authorities = service - .registry - .actions() - .actions - .iter() - .filter_map(|action| { - authorize( - &service.registry, - action, + return audited_list_concealment( + mutations, + &service, &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(ProposalOperation::List), None, + &correlation, + FailedCheck::AccessProfile, ) - }) - .collect::>(); + .await; + } + }; + // When no Proposal action admits the caller, the first Proposal action's + // refusal names the check. A registry with none refuses on the profile. + let mut first_refusal = None; + let mut authorities = Vec::new(); + for action in &service.registry.actions().actions { + match authorize_checked( + &service.registry, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::List), + None, + ) { + Ok(authority) => authorities.push(authority), + Err(check) if matches!(action.execution, CompiledActionExecution::Proposal { .. }) => { + first_refusal.get_or_insert(check); + } + Err(_) => {} + } + } if authorities.is_empty() { return audited_list_concealment( mutations, @@ -1666,6 +1757,7 @@ pub(super) async fn list( &claims, selected.as_deref(), &correlation, + first_refusal.unwrap_or(FailedCheck::AccessProfile), ) .await; } diff --git a/crates/registry-breg/src/api/record_attachments.rs b/crates/registry-breg/src/api/record_attachments.rs index 528902a9c1..3b2dc33e9b 100644 --- a/crates/registry-breg/src/api/record_attachments.rs +++ b/crates/registry-breg/src/api/record_attachments.rs @@ -65,7 +65,7 @@ async fn download( let mut surface = match super::authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_read_concealment( &service, &audit_route, @@ -73,7 +73,7 @@ async fn download( &claims, record_id, &correlation, - reason, + refusal, ) .await; } @@ -103,16 +103,22 @@ async fn download( }); // The attachment row-level policy needs a principal, so a principal-less // caller is refused here rather than by an empty database answer. - if claims.principal().is_none() - || record_id.is_none_or(|id| !valid_canonical_record_uuid(id)) - || !granted - { + let refused_check = if claims.principal().is_none() { + Some(FailedCheck::TokenClaims) + } else if record_id.is_none_or(|id| !valid_canonical_record_uuid(id)) { + Some(FailedCheck::Visibility) + } else if !granted { + Some(FailedCheck::Operation) + } else { + None + }; + if let Some(check) = refused_check { return audited_read_refusal( &service, &audit_route, &surface, record_id, - concealed(), + concealed(check), &correlation, ) .await; @@ -139,7 +145,7 @@ async fn download( .await { Ok(Some(held)) => attachment_response(held), - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(_) => unavailable(), } } diff --git a/crates/registry-breg/src/api/statistics.rs b/crates/registry-breg/src/api/statistics.rs index 2b5f6f856c..07726dd907 100644 --- a/crates/registry-breg/src/api/statistics.rs +++ b/crates/registry-breg/src/api/statistics.rs @@ -156,7 +156,7 @@ pub(super) fn authorize_with_reason( kind: Kind, claims: &VerifiedRequestClaims, selected: Option<&str>, -) -> Result { +) -> Result { let eligible = |id: &str| match kind { Kind::Live => dataset.live_profiles.contains(id), Kind::Exact => dataset @@ -181,13 +181,13 @@ pub(super) fn authorize_with_reason( let selected = selected .or(configured_default) .or_else(|| default.map(String::as_str)) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; if !eligible(selected) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::AccessProfile)); } claims .principal() - .ok_or(ReadRefusalReason::ProfileAdmission)?; + .ok_or(RouteRefusal::admission_check(FailedCheck::TokenClaims))?; if matches!( kind, Kind::Live | Kind::Publish | Kind::DryRun | Kind::Withdraw @@ -202,7 +202,7 @@ pub(super) fn authorize_with_reason( && route.operation == Operation::List && read_path_for_route(service, route).is_none() }) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let mut options = QueryOptions::default(); options.parsed.access_profile = Some(selected.to_owned()); return authorize_route_with_reason(service, route, claims, &options) @@ -211,18 +211,15 @@ pub(super) fn authorize_with_reason( let profile = dataset .access_profiles .get(selected) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; - let boundaries = authorize_profile_claims(profile, claims) - .map_err(|_| ReadRefusalReason::ProfileAdmission)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; + let boundaries = authorize_profile_claims(profile, claims).map_err(RouteRefusal::admission)?; Ok(AuthorizedRequestContext::new( claims.principal().map(str::to_owned), claims.purpose().map(str::to_owned), selected.to_owned(), boundaries, ) - .with_task_grant( - task_grant_binding(profile, claims).map_err(|_| ReadRefusalReason::ProfileAdmission)?, - ) + .with_task_grant(task_grant_binding(profile, claims).map_err(RouteRefusal::admission)?) .with_audit_context(claims) .with_recipients(claims)) } @@ -397,7 +394,7 @@ async fn dispatch( &claims, None, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; }; @@ -405,17 +402,17 @@ async fn dispatch( let context = match authorize_with_reason(&service, dataset, route.kind, &claims, selected.as_deref()) { Ok(context) => context, - Err(reason) => { + Err(refusal) => { let reason = (route.kind.method() == HttpMethod::Get - && reason == ReadRefusalReason::ProfileAdmission) - .then_some(reason); + && refusal.reason == ReadRefusalReason::ProfileAdmission) + .then_some(refusal.reason); return refusal_with_reason( &service, &route, &claims, selected.as_deref(), &correlation, - concealed(), + concealed(refusal.check), reason, ) .await; @@ -681,13 +678,13 @@ async fn execute( } Kind::Latest | Kind::Version => { if route.kind == Kind::Version && version.is_none() { - return Err(concealed()); + return Err(concealed(FailedCheck::Visibility)); } let stored = backend .read_version(StatisticsVersionReadRequest { context, dataset_id: &route.dataset, - period_code: period.ok_or_else(concealed)?, + period_code: period.ok_or_else(|| concealed(FailedCheck::Visibility))?, version, selection, deadline, @@ -791,7 +788,7 @@ async fn execute( .dry_run(StatisticsDryRunRequest { context, dataset_id: &route.dataset, - period_code: period.ok_or_else(concealed)?, + period_code: period.ok_or_else(|| concealed(FailedCheck::Visibility))?, status, computed_at: now, today, @@ -825,7 +822,7 @@ async fn execute( .as_object() .filter(|o| o.len() == 1) .ok_or_else(invalid_request)?; - let period = period.ok_or_else(concealed)?; + let period = period.ok_or_else(|| concealed(FailedCheck::Visibility))?; let held = if route.kind == Kind::Publish { let status = match object.get("status").and_then(Value::as_str) { Some("provisional") => ReleaseStatus::Provisional, @@ -858,7 +855,7 @@ async fn execute( context, dataset_id: &route.dataset, period_code: period, - version: version.ok_or_else(concealed)?, + version: version.ok_or_else(|| concealed(FailedCheck::Visibility))?, reason, idempotency_key: key, route_id: &route.id(), @@ -953,7 +950,7 @@ fn negotiate(headers: &HeaderMap) -> bool { } fn service_problem(error: StatisticsServiceError) -> Response { match error { - StatisticsServiceError::Concealed => concealed(), + StatisticsServiceError::Concealed => concealed(FailedCheck::Visibility), StatisticsServiceError::QueryInvalid { field_path } => { statistics_invalid_query_at(field_path) } @@ -1142,7 +1139,7 @@ pub(super) async fn unknown( claims, None, correlation, - concealed(), + super::unknown_route(), RefusalHttpMethod::from_request(method), "statistics.unknown", None, diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index 94dcb824a8..97870cf08d 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -2068,7 +2068,7 @@ async fn task_statistics_reads_bind_the_grant_to_the_request_principal_and_purpo }; for (case, claims) in [("principal", &other_principal), ("purpose", &other_purpose)] { assert_eq!( - read(claims).err(), + read(claims).err().map(|refusal| refusal.reason), Some(ReadRefusalReason::ProfileAdmission), "a grant for another {case} cannot read released statistics" ); diff --git a/crates/registry-breg/src/mutation.rs b/crates/registry-breg/src/mutation.rs index cae653bef2..cfc932da6e 100644 --- a/crates/registry-breg/src/mutation.rs +++ b/crates/registry-breg/src/mutation.rs @@ -2397,7 +2397,7 @@ pub enum MutationError { not_after_field: String, }, #[error("mutation is outside the caller's authorized record boundary")] - AuthorizationRefused, + AuthorizationRefused(registry_platform_authcommon::FailedCheck), /// A direct create or patch produced a row outside the selected access /// profile's row boundary. This is distinct from concealed target and /// stale-condition failures, which remain generic precondition refusals. @@ -2493,6 +2493,50 @@ pub enum MutationError { PackagePinMismatch(registry_platform_config::blocks::PackageDigestMismatch), } +impl MutationError { + /// The check a refused caller failed, for the operator only. `None` for an + /// error that does not refuse the caller. The match names every variant, + /// so a new one must decide. + #[deny(clippy::wildcard_enum_match_arm)] + pub(crate) fn failed_check(&self) -> Option { + use registry_platform_authcommon::FailedCheck; + match self { + Self::AuthorizationRefused(check) => Some(*check), + Self::WriteOutsideBoundary => Some(FailedCheck::RowBoundary), + Self::FieldGuardFailed { .. } | Self::ProposalGuardFailed(_) => { + Some(FailedCheck::ActionGuard) + } + Self::InvalidRequest + | Self::InvalidRequestAt(_) + | Self::InvalidTimerWindow { .. } + | Self::PreconditionFailed + | Self::ProposalReviewResultMismatch + | Self::Conflict + | Self::ProposalUniqueConflict + | Self::ProposalRejected + | Self::AttachmentSlotWriteOnce + | Self::AttachmentTooLarge + | Self::AttachmentContentType + | Self::AttachmentDigestMismatch + | Self::IdempotencyConflict + | Self::IdempotencyExpired + | Self::Unavailable + | Self::RetryableConflict + | Self::CommitUnresolved + | Self::ActionHandlerFailure(_) + | Self::ActionEvidenceFailure { .. } + | Self::ActionRefusal(_) + | Self::TimerGenerationUnsupported + | Self::FieldPatternViolation { .. } + | Self::RowLocalConstraintViolation(_) + | Self::FieldEncryptionUnavailable + | Self::IngestionRefusal(_) + | Self::MigrationLockHeld + | Self::PackagePinMismatch(_) => None, + } + } +} + /// PostgreSQL allocation schema entry point exposed only to the real-database /// test target. Production installation is conditional on the compiled /// registry using generated identifiers. diff --git a/crates/registry-breg/src/mutation/proposal.rs b/crates/registry-breg/src/mutation/proposal.rs index 721039b79c..a18ed843b8 100644 --- a/crates/registry-breg/src/mutation/proposal.rs +++ b/crates/registry-breg/src/mutation/proposal.rs @@ -732,16 +732,16 @@ impl MutationTransaction { authority: &ProposalAuthority, ) -> Result<(), MutationError> { let action = proposal_action(registry, &document.action_id)?; - if document.action_id != authority.common.action_id() - || authority - .proposal_scope - .as_ref() - .is_some_and(|scope| !scope.contains(&document.proposal_id)) - || (authority.ownership == Some(ProposalOwnership::Caller) - && document.header.owner_reference - != self.proposal_owner_reference(authority.common.principal())) - { - return Err(MutationError::AuthorizationRefused); + if let Some(check) = proposal_document_refusal( + &document.action_id, + authority.common.action_id(), + authority.proposal_scope.as_ref(), + document.proposal_id, + authority.ownership, + &document.header.owner_reference, + || self.proposal_owner_reference(authority.common.principal()), + ) { + return Err(MutationError::AuthorizationRefused(check)); } for (entity_id, id) in &document.input_targets { let entity = registry @@ -4547,6 +4547,86 @@ mod disclosure_tests { } } +/// The check a Proposal document fails against the caller's authority, if +/// any: another action, a Proposal outside the grant's bound scope, or a +/// Proposal another caller owns. +fn proposal_document_refusal( + document_action_id: &str, + authority_action_id: &str, + scope: Option<&BTreeSet>, + proposal_id: Uuid, + ownership: Option, + document_owner: &str, + caller_owner: impl FnOnce() -> String, +) -> Option { + use registry_platform_authcommon::FailedCheck; + if document_action_id != authority_action_id { + return Some(FailedCheck::Operation); + } + if scope.is_some_and(|scope| !scope.contains(&proposal_id)) { + return Some(FailedCheck::TaskGrantScope); + } + if ownership == Some(ProposalOwnership::Caller) && document_owner != caller_owner() { + return Some(FailedCheck::Ownership); + } + None +} + +#[cfg(test)] +mod document_refusal_tests { + use super::*; + use registry_platform_authcommon::FailedCheck; + + #[test] + fn each_refusing_condition_names_its_own_check() { + let id = Uuid::from_u128(1); + let scope = BTreeSet::from([id]); + let owner = || "owner-a".to_owned(); + let check = + |action: &str, scope: Option<&BTreeSet>, proposal: Uuid, ownership, who: &str| { + proposal_document_refusal( + action, "action-a", scope, proposal, ownership, who, owner, + ) + }; + assert_eq!( + check("action-b", None, id, None, "owner-a"), + Some(FailedCheck::Operation) + ); + assert_eq!( + check( + "action-a", + Some(&scope), + Uuid::from_u128(2), + None, + "owner-a" + ), + Some(FailedCheck::TaskGrantScope) + ); + assert_eq!( + check( + "action-a", + Some(&scope), + id, + Some(ProposalOwnership::Caller), + "owner-b" + ), + Some(FailedCheck::Ownership) + ); + assert_eq!( + check( + "action-a", + Some(&scope), + id, + Some(ProposalOwnership::Caller), + "owner-a" + ), + None + ); + // Another owner's Proposal is admitted when ownership is not the caller's. + assert_eq!(check("action-a", None, id, None, "owner-b"), None); + } +} + #[cfg(test)] mod turn_tests { use super::*; diff --git a/crates/registry-breg/src/postgres/mutation.rs b/crates/registry-breg/src/postgres/mutation.rs index db04f8c041..11b4e1692a 100644 --- a/crates/registry-breg/src/postgres/mutation.rs +++ b/crates/registry-breg/src/postgres/mutation.rs @@ -2049,7 +2049,7 @@ impl PostgresRecordMutationService { | MutationError::Conflict | MutationError::ProposalUniqueConflict | MutationError::ProposalRejected - | MutationError::AuthorizationRefused + | MutationError::AuthorizationRefused(_) // Ingestion consumes the batch mutation outcome through // its run protocol. Its item refusal remains the generic // 412 instead of the direct write route's 403. diff --git a/crates/registry-breg/src/postgres/proposal.rs b/crates/registry-breg/src/postgres/proposal.rs index 2aaa8ec348..3d991c0705 100644 --- a/crates/registry-breg/src/postgres/proposal.rs +++ b/crates/registry-breg/src/postgres/proposal.rs @@ -1471,7 +1471,7 @@ impl PostgresRecordMutationService { { Ok(()) => {} Err( - MutationError::AuthorizationRefused | MutationError::PreconditionFailed, + MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed, ) => { guarded .rollback() @@ -1641,7 +1641,9 @@ impl PostgresRecordMutationService { fn link_readable(outcome: Result<(), MutationError>) -> Result { match outcome { Ok(()) => Ok(true), - Err(MutationError::AuthorizationRefused | MutationError::PreconditionFailed) => Ok(false), + Err(MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed) => { + Ok(false) + } Err(error) => Err(error), } } @@ -1654,7 +1656,9 @@ mod tests { fn a_link_check_omits_only_a_refusal_and_fails_on_anything_else() { assert_eq!(link_readable(Ok(())), Ok(true)); for refusal in [ - MutationError::AuthorizationRefused, + MutationError::AuthorizationRefused( + registry_platform_authcommon::FailedCheck::Ownership, + ), MutationError::PreconditionFailed, ] { assert_eq!(link_readable(Err(refusal)), Ok(false)); diff --git a/crates/registry-breg/tests/concealment_refusals.rs b/crates/registry-breg/tests/concealment_refusals.rs new file mode 100644 index 0000000000..b6d05e7a17 --- /dev/null +++ b/crates/registry-breg/tests/concealment_refusals.rs @@ -0,0 +1,643 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Every concealed read refusal answers with the fixed 404 problem, counts +//! once under `breg_request_refusals_total{check}`, and writes one value-free +//! `request refused` line that names the check. +//! +//! The recorder is process-wide and admits five log lines per check per +//! minute, so this file drives every case from one test and keeps each check +//! under that bound. +//! +//! `tests/golden/concealment_refusals.json` freezes the status, the headers +//! that matter and the body (minus `traceId`) of each answer. +//! `REGISTRY_BREG_WRITE_GOLDEN=1` rewrites it. A change to the file in a +//! review is a change to a public response. + +#![cfg(feature = "runtime")] + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::body::{to_bytes, Body}; +use axum::http::header::AUTHORIZATION; +use axum::http::{HeaderValue, Request}; +use registry_breg::api::{ + authenticated_router, HeldReadResponse, HttpService, ReadRuntimeIdentity, ReadServiceError, + ReadinessProbe, RecordReadRequest, RecordReadService, ServiceFuture, +}; +use registry_breg::auth::{AuthorityClaimConfig, RegistryAuthenticator}; +use registry_breg::cursor::CursorCodec; +use registry_breg::metrics::{metrics_app, Metrics}; +use registry_breg::{compile_project, parse_project_yaml, CompileProfile, CompiledRegistry}; +use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_oidc::{ClaimNames, JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{ + fixtures, oidc_verifier_config, sign_ed25519_compact_jwt, MockIdp, +}; +use serde_json::{json, Value}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber; +use zeroize::Zeroizing; + +const AUDIENCE: &str = "urn:example:breg"; +const PRINCIPAL: &str = "principal-value-never-rendered"; +const ACTOR_ID: &str = "00000000-0000-4000-8000-0000000000aa"; +const RECORD_ID: &str = "00000000-0000-4000-8000-000000000001"; +const GOLDEN: &str = "tests/golden/concealment_refusals.json"; + +const PROJECT: &str = r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {id: concealment-recording, version: 0.1.0, defaultLanguage: en, canonicalBaseIri: https://authoring.example.test} +recordTypes: + case: + primaryDataset: test-dataset + route: cases + mutationMode: mutable + tombstone: false + classification: public + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + - {id: tenant, type: string, required: true, maximumLength: 100, classification: internal} +datasets: + test-dataset: {} + +accessProfiles: + reader: + default: true + principalClaim: sub + requiredScopes: [registry.read] + permissions: + records: + - {recordType: case, operations: [get, list], readableFields: [label], rowBoundaries: unrestricted} + purposeful: + principalClaim: sub + requiredScopes: unrestricted + requiredPurposes: [record-review] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} + human-only: + principalClaim: sub + requiredScopes: unrestricted + actorKind: human + requesterClients: [human-client] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} + client-bound: + principalClaim: sub + requiredScopes: unrestricted + actorKind: service + requesterClients: [agent-client] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} + tenant-bound: + principalClaim: sub + requiredScopes: unrestricted + permissions: + records: + - recordType: case + operations: [get] + readableFields: [label] + rowBoundaries: + - {field: tenant, claim: tenant_claim, operator: equals} + granted: + principalClaim: sub + requiredScopes: unrestricted + actorKind: agent + requesterClients: [agent-client] + requiredPurposes: [record-review] + taskGrant: {sourceIssuer: https://casework.example} + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} +"#; + +struct EmptyReads; + +impl RecordReadService for EmptyReads { + fn get( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } + + fn list( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result> { + Box::pin(async { + Ok(HeldReadResponse::from_json(&json!({"items": []})).expect("fixture serializes")) + }) + } + + fn lookup( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } +} + +struct Ready; + +impl ReadinessProbe for Ready { + fn is_ready(&self) -> ServiceFuture<'_, bool> { + Box::pin(async { true }) + } +} + +fn compiled(source: &str) -> Arc { + let project = parse_project_yaml(source.as_bytes()).expect("project parses"); + Arc::new(compile_project(&project, &[], CompileProfile::Authoring).expect("project compiles")) +} + +fn service(registry: Arc) -> HttpService { + HttpService::new( + registry, + ReadRuntimeIdentity { + package_revision: "package-refusal-test".to_owned(), + schema_fingerprint: "schema-refusal-test".to_owned(), + }, + Arc::new(EmptyReads), + Arc::new(Ready), + Arc::new( + CursorCodec::new( + Zeroizing::new(vec![0x43; 32]), + std::time::Duration::from_secs(300), + ) + .expect("test cursor key is valid"), + ), + ) +} + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock") + .as_secs() +} + +fn key_source(idp: &MockIdp) -> Arc { + Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::dev(), + )) +} + +struct Harness { + app: axum::Router, + idp: MockIdp, +} + +impl Harness { + async fn start() -> Self { + let registry = compiled(PROJECT); + let idp = MockIdp::start().await; + let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); + verifier.allowed_clients = vec![ + "agent-client".to_owned(), + "other-client".to_owned(), + "human-client".to_owned(), + ]; + let claims = AuthorityClaimConfig::new("sub", Some("registry_purpose".to_owned())) + .with_contextual_claims( + ClaimNames::default(), + BTreeMap::from([("agent-client".to_owned(), ACTOR_ID.to_owned())]), + ); + let authenticator = + RegistryAuthenticator::new(®istry, verifier, key_source(&idp), claims) + .expect("authentication config is valid"); + let app = authenticated_router(Arc::new(service(registry)), Arc::new(authenticator)); + Self { app, idp } + } + + fn token(&self, mut claims: Value) -> String { + let now = unix_now(); + let object = claims.as_object_mut().expect("claims are an object"); + object + .entry("iss") + .or_insert_with(|| json!(self.idp.issuer())); + object.entry("iat").or_insert_with(|| json!(now)); + object.entry("nbf").or_insert_with(|| json!(now)); + object.entry("exp").or_insert_with(|| json!(now + 900)); + sign_ed25519_compact_jwt( + fixtures::ED25519_PRIVATE_JWK, + "JWT", + "registry-platform-testing-ed25519-1", + claims, + ) + } +} + +fn service_claims() -> Value { + json!({ + "aud": AUDIENCE, + "sub": PRINCIPAL, + "azp": "agent-client", + "registry_actor_kind": "service", + "scope": "registry.read", + }) +} + +fn with(mut claims: Value, key: &str, value: Value) -> Value { + claims + .as_object_mut() + .expect("claims are an object") + .insert(key.to_owned(), value); + claims +} + +fn without(mut claims: Value, key: &str) -> Value { + claims + .as_object_mut() + .expect("claims are an object") + .remove(key); + claims +} + +fn grant_claims(now: u64) -> Value { + json!({ + "aud": AUDIENCE, + "sub": PRINCIPAL, + "registry_principal": PRINCIPAL, + "azp": "agent-client", + "registry_actor_kind": "agent", + "registry_purpose": "record-review", + "request_purpose": "record-review", + "registry_grant_id": "00000000-0000-4000-8000-0000000000bf", + "registry_approver": "h:synthetic-approver", + "registry_grant_source_issuer": "https://casework.example", + "registry_grant_client": "agent-client", + "registry_grant_resource": AUDIENCE, + "registry_grant_exp": now + 600, + "registry_grant_bounds": {"type":"breg","permissions":[{"collection":"cases","operations":["get"]}]}, + "identity": {"tenant_claim": "tenant-from-approved-identity"}, + }) +} + +fn read_request(path: &str, token: Option<&str>) -> Request { + let mut request = Request::builder() + .uri(path) + .body(Body::empty()) + .expect("request"); + if let Some(token) = token { + request.headers_mut().append( + AUTHORIZATION, + HeaderValue::from_str(&format!("Bearer {token}")).expect("header value"), + ); + } + request +} + +#[derive(Clone, Default)] +struct CapturedLogs(Arc>>); + +impl std::io::Write for CapturedLogs { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 + .lock() + .expect("captured log buffer") + .extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for CapturedLogs { + type Writer = Self; + + fn make_writer(&'writer self) -> Self::Writer { + self.clone() + } +} + +impl CapturedLogs { + fn subscriber(&self) -> tracing::Dispatch { + let writer = self.clone(); + tracing::Dispatch::new( + tracing_subscriber::fmt() + .json() + .without_time() + .with_ansi(false) + .with_writer(writer) + .finish(), + ) + } + + fn events(&self) -> Vec { + let bytes = self.0.lock().expect("captured log buffer").clone(); + String::from_utf8(bytes) + .expect("log lines are UTF-8") + .lines() + .map(|line| serde_json::from_str(line).expect("JSON log line")) + .collect() + } +} + +/// The counter, read the way an operator reads it: from the metrics listener. +async fn refusal_counts() -> BTreeMap { + let response = metrics_app(Arc::new(Metrics::without_pool_for_test())) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .expect("scrape request"), + ) + .await + .expect("metrics respond"); + let bytes = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("metrics body"); + let text = String::from_utf8(bytes.to_vec()).expect("metrics are UTF-8"); + let mut counts = BTreeMap::new(); + for line in text.lines() { + if let Some(rest) = line.strip_prefix("breg_request_refusals_total{check=\"") { + let (label, value) = rest.split_once("\"} ").expect("sample line"); + counts.insert(label.to_owned(), value.parse().expect("counter value")); + } + } + counts +} + +struct Observed { + name: &'static str, + expected_check: &'static str, + answer: Value, + counted: BTreeMap, + refusal_lines: Vec, + log_text: String, +} + +async fn observe( + name: &'static str, + expected_check: &'static str, + app: &axum::Router, + request: Request, +) -> Observed { + let captured = CapturedLogs::default(); + let before = refusal_counts().await; + let response = app + .clone() + .oneshot(request) + .with_subscriber(captured.subscriber()) + .await + .expect("router responds"); + let after = refusal_counts().await; + let status = response.status().as_u16(); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("ASCII header").to_owned()) + }; + let content_type = header("content-type"); + let cache_control = header("cache-control"); + let www_authenticate = header("www-authenticate"); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("response body"); + let mut body: Value = serde_json::from_slice(&bytes).expect("problem body is JSON"); + assert!( + body.as_object_mut() + .expect("problem body is an object") + .remove("traceId") + .is_some_and(|trace| trace.as_str().is_some_and(|id| id.len() == 32)), + "{name}: the problem carries the request trace id" + ); + let counted = after + .iter() + .filter_map(|(label, value)| { + let delta = value - before.get(label).copied().unwrap_or(0); + (delta > 0).then(|| (label.clone(), delta)) + }) + .collect(); + let events = captured.events(); + let log_text = events.iter().map(Value::to_string).collect::(); + let refusal_lines = events + .into_iter() + .filter(|event| event["fields"]["message"] == "request refused") + .collect(); + Observed { + name, + expected_check, + answer: json!({ + "status": status, + "contentType": content_type, + "cacheControl": cache_control, + "wwwAuthenticate": www_authenticate, + "body": body, + }), + counted, + refusal_lines, + log_text, + } +} + +#[tokio::test] +async fn every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wire() { + let record = format!("/v1/records/cases/{RECORD_ID}"); + let now = unix_now(); + let harness = Harness::start().await; + let token = |claims: Value| harness.token(claims); + let mut observed = Vec::new(); + + let ok = token(service_claims()); + let tenant_token = |tenant: Option<&str>| { + let claims = service_claims(); + match tenant { + Some(tenant) => token(with(claims, "tenant_claim", json!(tenant))), + None => token(claims), + } + }; + let cases: Vec<(&'static str, &'static str, Request)> = vec![ + ( + "unknown-access-profile", + "access-profile", + read_request(&format!("{record}?accessProfile=nobody"), Some(&ok)), + ), + ( + "missing-scope", + "scope", + read_request(&record, Some(&token(without(service_claims(), "scope")))), + ), + ( + "purpose-not-declared", + "purpose", + read_request(&format!("{record}?accessProfile=purposeful"), Some(&ok)), + ), + ( + "actor-kind-mismatch", + "actor-kind", + read_request(&format!("{record}?accessProfile=human-only"), Some(&ok)), + ), + ( + "requester-client-not-admitted", + "requester-client", + read_request( + &format!("{record}?accessProfile=client-bound"), + Some(&token(with(service_claims(), "azp", json!("other-client")))), + ), + ), + ( + "row-claim-missing", + "row-boundary", + read_request( + &format!("{record}?accessProfile=tenant-bound"), + Some(&tenant_token(None)), + ), + ), + ( + "task-grant-missing", + "task-grant-missing", + read_request( + &format!("{record}?accessProfile=granted"), + Some(&token(with( + with( + with(service_claims(), "registry_actor_kind", json!("agent")), + "registry_purpose", + json!("record-review"), + ), + "act", + json!({"sub": ACTOR_ID, "iss": harness.idp.issuer()}), + ))), + ), + ), + ( + "task-grant-from-another-issuer", + "task-grant-binding", + read_request( + &format!("{record}?accessProfile=granted"), + Some(&token(with( + grant_claims(now), + "registry_grant_source_issuer", + json!("https://other.example"), + ))), + ), + ), + ( + "task-grant-bounds-do-not-cover-the-profile", + "task-grant-scope", + read_request( + &format!("{record}?accessProfile=granted"), + Some(&token(with( + grant_claims(now), + "registry_grant_bounds", + json!({"type":"breg","permissions":[{"collection":"cases","operations":["list"]}]}), + ))), + ), + ), + ( + "select-beyond-the-readable-fields", + "disclosure", + read_request(&format!("{record}?$select=tenant"), Some(&ok)), + ), + ( + "record-id-is-not-a-uuid", + "visibility", + read_request("/v1/records/cases/not-a-uuid", Some(&ok)), + ), + ( + "record-is-absent-or-outside-the-boundary", + "visibility", + read_request(&record, Some(&ok)), + ), + ( + "schema-of-a-record-type-the-caller-cannot-read", + "visibility", + read_request( + "/v1/schemas/cases", + Some(&token(without(service_claims(), "scope"))), + ), + ), + ]; + for (name, check, request) in cases { + observed.push(observe(name, check, &harness.app, request).await); + } + + // The answers, frozen. + let answers: BTreeMap<&str, &Value> = observed + .iter() + .map(|case| (case.name, &case.answer)) + .collect(); + let golden_path = format!("{}/{GOLDEN}", env!("CARGO_MANIFEST_DIR")); + if std::env::var_os("REGISTRY_BREG_WRITE_GOLDEN").is_some() { + let mut text = serde_json::to_string_pretty(&answers).expect("answers serialize"); + text.push('\n'); + std::fs::write(&golden_path, text).expect("golden file is writable"); + } else { + let frozen: Value = serde_json::from_str( + &std::fs::read_to_string(&golden_path).expect("golden file exists"), + ) + .expect("golden file is JSON"); + assert_eq!( + serde_json::to_value(&answers).expect("answers serialize"), + frozen, + "a concealed refusal changed on the wire" + ); + } + + // The recording: one count, one line, no caller value. + let mut used: BTreeSet<&str> = BTreeSet::new(); + for case in &observed { + used.insert(case.expected_check); + assert_eq!( + case.counted, + BTreeMap::from([(case.expected_check.to_owned(), 1)]), + "{}: the refusal counts once under its check", + case.name + ); + assert_eq!( + case.refusal_lines.len(), + 1, + "{}: one refusal line", + case.name + ); + let line = &case.refusal_lines[0]; + assert_eq!(line["level"], "INFO", "{}", case.name); + let fields = line["fields"].as_object().expect("line fields"); + assert_eq!(fields["decision"], "refused", "{}", case.name); + assert_eq!(fields["failed_check"], case.expected_check, "{}", case.name); + assert_eq!(fields["suppressed"], 0, "{}", case.name); + let keys: BTreeSet<&str> = fields.keys().map(String::as_str).collect(); + assert_eq!( + keys, + BTreeSet::from([ + "decision", + "failed_check", + "message", + "suppressed", + "trace_id" + ]), + "{}: the line carries only the fixed fields", + case.name + ); + for canary in [ + PRINCIPAL, + "agent-client", + "other-client", + "nobody", + "not-a-uuid", + "https://other.example", + "Bearer", + ] { + assert!( + !case.log_text.contains(canary), + "{}: the log exposed {canary}", + case.name + ); + } + } + assert!( + used.len() >= 11, + "the cases cover every concealment check of the read routes" + ); +} diff --git a/crates/registry-breg/tests/golden/concealment_refusals.json b/crates/registry-breg/tests/golden/concealment_refusals.json new file mode 100644 index 0000000000..8506ae0388 --- /dev/null +++ b/crates/registry-breg/tests/golden/concealment_refusals.json @@ -0,0 +1,171 @@ +{ + "actor-kind-mismatch": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "missing-scope": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "purpose-not-declared": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "record-id-is-not-a-uuid": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "record-is-absent-or-outside-the-boundary": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "requester-client-not-admitted": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "row-claim-missing": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "schema-of-a-record-type-the-caller-cannot-read": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "select-beyond-the-readable-fields": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "task-grant-bounds-do-not-cover-the-profile": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "task-grant-from-another-issuer": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "task-grant-missing": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "unknown-access-profile": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + } +} diff --git a/crates/registry-breg/tests/postgres_mutation.rs b/crates/registry-breg/tests/postgres_mutation.rs index 7bb2f05333..41b093d380 100644 --- a/crates/registry-breg/tests/postgres_mutation.rs +++ b/crates/registry-breg/tests/postgres_mutation.rs @@ -1320,6 +1320,7 @@ async fn real_postgres_row_boundary_write_refusals_are_safe_audited_and_atomic() let before_create = durable_counts(&database, &table).await; let before_create_refusals = refusal_audit_count(&database).await; + let counted_before_create = refusal_counts().await; let refused_create = send( &app, Method::POST, @@ -1336,6 +1337,12 @@ async fn real_postgres_row_boundary_write_refusals_are_safe_audited_and_atomic() assert_eq!(refused_create.status(), StatusCode::FORBIDDEN); let refused_create = body_json(refused_create).await; assert_eq!(refused_create["code"], "write.outside-boundary"); + assert_refusal_counted( + &counted_before_create, + "row-boundary", + "create outside boundary", + ) + .await; assert_eq!( refused_create["detail"], "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition." @@ -2138,6 +2145,48 @@ async fn real_postgres_row_local_constraint_problems_name_only_readable_declarat database.cleanup().await; } +/// The refusal counter, read the way an operator reads it: from the metrics +/// listener. The recorder is process-wide, so a test that shares its process +/// with others asserts a rise of at least one. +async fn refusal_counts() -> std::collections::BTreeMap { + use tower::ServiceExt as _; + let response = registry_breg::metrics::metrics_app(Arc::new( + registry_breg::metrics::Metrics::without_pool_for_test(), + )) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .expect("scrape request"), + ) + .await + .expect("metrics respond"); + let bytes = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("metrics body"); + String::from_utf8(bytes.to_vec()) + .expect("metrics are UTF-8") + .lines() + .filter_map(|line| { + let rest = line.strip_prefix("breg_request_refusals_total{check=\"")?; + let (label, value) = rest.split_once("\"} ")?; + Some((label.to_owned(), value.parse().expect("counter value"))) + }) + .collect() +} + +async fn assert_refusal_counted( + before: &std::collections::BTreeMap, + check: &str, + context: &str, +) { + let after = refusal_counts().await; + assert!( + after.get(check).copied().unwrap_or(0) > before.get(check).copied().unwrap_or(0), + "{context}: the refusal counts under {check}" + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { let database = TestDatabase::create(12).await; @@ -3060,6 +3109,7 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { .any(|window| window == b"http-patched")); let before_bad_query = durable_counts(&database, &table).await; + let counted_before_bad_query = refusal_counts().await; let bad_query = send( &app, Method::POST, @@ -3074,6 +3124,7 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { .await; assert_eq!(bad_query.status(), StatusCode::NOT_FOUND); assert_eq!(body_json(bad_query).await["code"], "resource.not_found"); + assert_refusal_counted(&counted_before_bad_query, "visibility", "bad query").await; assert_eq!( durable_counts(&database, &table).await.audit, before_bad_query.audit + 1 @@ -3114,24 +3165,28 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { "refusal audit failure releases no intended refusal and commits no mutation packet" ); - for (label, uri, blocked_claims) in [ + for (label, uri, blocked_claims, expected_check) in [ ( "wrong purpose", "/v1/records/widgets?accessProfile=operator", api_claims("wrong-purpose", Some("zone-a")), + "purpose", ), ( "wrong profile", "/v1/records/widgets?accessProfile=missing", api_claims("case-management", Some("zone-a")), + "access-profile", ), ( "missing boundary", "/v1/records/widgets?accessProfile=operator", api_claims("case-management", None), + "row-boundary", ), ] { let before = durable_counts(&database, &table).await; + let counted_before = refusal_counts().await; let response = send( &app, Method::POST, @@ -3145,6 +3200,7 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { ) .await; assert_eq!(response.status(), StatusCode::NOT_FOUND, "{label}"); + assert_refusal_counted(&counted_before, expected_check, label).await; assert_eq!( durable_counts(&database, &table).await.current, before.current diff --git a/crates/registry-casework/src/assignment.rs b/crates/registry-casework/src/assignment.rs index 4cee5052b1..a4ca903ea2 100644 --- a/crates/registry-casework/src/assignment.rs +++ b/crates/registry-casework/src/assignment.rs @@ -2,6 +2,7 @@ use crate::{CaseworkService, PostgresStore, ServiceError, StoreError}; use chrono::{TimeDelta, Utc}; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; @@ -140,7 +141,7 @@ impl PostgresStore { CaseworkActsAs::Administrator | CaseworkActsAs::Requester => false, }; if !authorized { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } transaction .query( @@ -174,12 +175,12 @@ impl PostgresStore { ) .await? } - CaseworkActsAs::Requester => return Err(StoreError::Forbidden), + CaseworkActsAs::Requester => return Err(StoreError::Forbidden(FailedCheck::Operation)), }, DirectoryTargetPurpose::AbsenceCover => { let person = person.ok_or(StoreError::Invalid)?; if !can_manage_person(&transaction, actor, person).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } if actor.role == CaseworkActsAs::Supervisor { // A supervisor covers only inside the teams they lead, so a @@ -250,7 +251,7 @@ impl PostgresStore { idempotency_key: &str, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } validate_reason( idempotency_key, @@ -380,7 +381,7 @@ impl PostgresStore { actor.role, CaseworkActsAs::Staff | CaseworkActsAs::Supervisor | CaseworkActsAs::Administrator ) { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } if !(1..=1_000).contains(&limit) { return Err(StoreError::Invalid); @@ -587,7 +588,7 @@ impl PostgresStore { if !can_manage_person(&transaction, actor, managed_person).await? || !valid_absence_cover(&transaction, actor, managed_person, &input.cover).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } if let Some(response) = assignment_replay( &transaction, @@ -697,7 +698,7 @@ impl PostgresStore { let replay: AbsenceDeleteReplay = serde_json::from_value(response).map_err(StoreError::Json)?; if !can_manage_person(&transaction, actor, &replay.person).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } audit.record_outcome(crate::audit::AuditOutcome::Replayed); audit.commit(transaction).await?; @@ -716,7 +717,7 @@ impl PostgresStore { let row=transaction.query_opt("SELECT absence_id,person_issuer,person_subject,starts_at,ends_at,cover_issuer,cover_subject,revision FROM casework_absences WHERE absence_id=$1 FOR UPDATE",&[&absence_id]).await?.ok_or(StoreError::NotFound)?; let record = absence_from_row(row)?; if !can_manage_person(&transaction, actor, &record.person).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } let next = actual.checked_add(1).ok_or(StoreError::Corrupt)?; transaction @@ -769,7 +770,7 @@ impl CaseworkService { idempotency_key: &str, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden.into()); + return Err(StoreError::Forbidden(FailedCheck::Operation).into()); } if expected_directory_revision < 0 || !valid_directory_identifier(&request.team_id) @@ -798,7 +799,7 @@ impl CaseworkService { idempotency_key: &str, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden.into()); + return Err(StoreError::Forbidden(FailedCheck::Operation).into()); } if expected_directory_revision < 0 || !valid_directory_identifier(team_id) diff --git a/crates/registry-casework/src/auth/delegated.rs b/crates/registry-casework/src/auth/delegated.rs index a5e3463ed5..98cf012561 100644 --- a/crates/registry-casework/src/auth/delegated.rs +++ b/crates/registry-casework/src/auth/delegated.rs @@ -127,7 +127,7 @@ impl crate::CaseworkService { Err(error) => Err(error), } } - Ok(_) => Err(crate::ReviewRuntimeError::NotFound), + Ok(_) => Err(crate::ReviewRuntimeError::NotHeldByReader), Err(error) => Err(error), }; let terminal = delegated_audit_outcome(&outcome); @@ -142,8 +142,9 @@ fn delegated_audit_outcome( match outcome { Ok(_) => crate::audit::AuditOutcome::Succeeded, Err( - crate::ReviewRuntimeError::Forbidden + crate::ReviewRuntimeError::Forbidden(_) | crate::ReviewRuntimeError::NotFound + | crate::ReviewRuntimeError::NotHeldByReader | crate::ReviewRuntimeError::SourceProfileRequired | crate::ReviewRuntimeError::ResultExpired | crate::ReviewRuntimeError::Invalid, @@ -159,7 +160,7 @@ fn delegated_recheck( Ok(true) => Ok(()), Ok(false) | Err( - crate::ReviewRuntimeError::Forbidden + crate::ReviewRuntimeError::Forbidden(_) | crate::ReviewRuntimeError::NotFound | crate::ReviewRuntimeError::ResultExpired, ) => Err(crate::ReviewRuntimeError::NotFound), @@ -346,12 +347,14 @@ mod tests { use super::{delegated_audit_outcome, delegated_recheck}; use crate::audit::AuditOutcome; use crate::{ReviewRuntimeError, StoreError}; + use registry_platform_authcommon::FailedCheck; #[test] fn delegated_caller_refusals_are_not_audited_as_runtime_failures() { for error in [ - ReviewRuntimeError::Forbidden, + ReviewRuntimeError::Forbidden(FailedCheck::Operation), ReviewRuntimeError::NotFound, + ReviewRuntimeError::NotHeldByReader, ReviewRuntimeError::SourceProfileRequired, ReviewRuntimeError::ResultExpired, ReviewRuntimeError::Invalid, @@ -377,7 +380,7 @@ mod tests { Err(ReviewRuntimeError::NotFound) )); assert!(matches!( - delegated_recheck(Err(ReviewRuntimeError::Forbidden)), + delegated_recheck(Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation))), Err(ReviewRuntimeError::NotFound) )); assert!(matches!( diff --git a/crates/registry-casework/src/clocks.rs b/crates/registry-casework/src/clocks.rs index 2d9c47ee65..02cb6f7e21 100644 --- a/crates/registry-casework/src/clocks.rs +++ b/crates/registry-casework/src/clocks.rs @@ -1,6 +1,7 @@ use crate::{CaseworkService, PostgresStore, ServiceError, StoreError}; use chrono::Utc; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use tokio_postgres::Transaction; @@ -13,7 +14,7 @@ impl PostgresStore { idempotency_key: &str, ) -> Result<(), StoreError> { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } if document.holiday_set.is_empty() || document.holiday_set.len() > 64 @@ -146,7 +147,7 @@ impl CaseworkService { revision: u64, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden.into()); + return Err(StoreError::Forbidden(FailedCheck::Operation).into()); } self.store .holiday_set(holiday_set, revision) diff --git a/crates/registry-casework/src/http.rs b/crates/registry-casework/src/http.rs index 6ed29a0a8c..3de5a34dda 100644 --- a/crates/registry-casework/src/http.rs +++ b/crates/registry-casework/src/http.rs @@ -841,7 +841,7 @@ async fn get_review_result( Ok(ReviewResultRead::Available(result)) => Ok(Json(result).into_response()), Ok(ReviewResultRead::Pending) => Ok(StatusCode::ACCEPTED.into_response()), Ok(ReviewResultRead::Expired) => Ok(StatusCode::GONE.into_response()), - Err(ReviewRuntimeError::NotFound) => Ok(StatusCode::NOT_FOUND.into_response()), + Err(ReviewRuntimeError::NotFound) => Ok(bare_not_found()), Err(error) => Err(HttpError::from(error)), } } @@ -963,6 +963,15 @@ async fn delegate_review_task( )) } +/// A 404 with no body, counted as a concealed target. +fn bare_not_found() -> Response { + let mut response = StatusCode::NOT_FOUND.into_response(); + response + .extensions_mut() + .insert(RefusalNote::new(FailedCheck::Visibility)); + response +} + async fn get_review_task_draft( RequestState(state): RequestState, headers: HeaderMap, @@ -976,6 +985,8 @@ async fn get_review_task_draft( .await? { Some(draft) => Ok(Json(draft).into_response()), + // No saved draft on a task the reviewer may read is absence, not a + // refusal, so it is not counted. None => Ok(StatusCode::NOT_FOUND.into_response()), } } @@ -1715,9 +1726,9 @@ pub enum HttpError { Internal, Validation(ReviewValidationError), } -// Store, service and review errors do not yet carry their own check: a refused -// operation is recorded as `operation`, and an absent or concealed target as -// `visibility`. +// A refused operation carries the check its producer named. An absent or +// concealed target is recorded as `visibility`, unless the producer named the +// check that hid it. impl From for HttpError { fn from(e: StoreError) -> Self { match e { @@ -1726,7 +1737,7 @@ impl From for HttpError { StoreError::CursorInvalid => Self::CursorInvalid, StoreError::IdempotencyExpired => Self::IdempotencyExpired, StoreError::NotFound => Self::NotFound(FailedCheck::Visibility), - StoreError::Forbidden => Self::Forbidden(FailedCheck::Operation), + StoreError::Forbidden(check) => Self::Forbidden(check), StoreError::Conflict => Self::PreconditionFailed, StoreError::AlreadyClaimed | StoreError::NotHolder => Self::ReviewTaskNotHeld, StoreError::IdempotencyConflict => Self::IdempotencyKeyReused, @@ -1745,8 +1756,8 @@ impl From for HttpError { fn from(e: ServiceError) -> Self { match e { ServiceError::Store(e) => e.into(), - ServiceError::NotFound => Self::NotFound(FailedCheck::Visibility), - ServiceError::Forbidden => Self::Forbidden(FailedCheck::Operation), + ServiceError::NotFound(check) => Self::NotFound(check), + ServiceError::Forbidden(check) => Self::Forbidden(check), ServiceError::ReviewValidation(e) => Self::Validation(e), ServiceError::Configuration => Self::Internal, ServiceError::Context(ReviewContextError::VersionMismatch) => { @@ -1767,7 +1778,8 @@ impl From for HttpError { fn from(e: ReviewRuntimeError) -> Self { match e { ReviewRuntimeError::NotFound => Self::NotFound(FailedCheck::Visibility), - ReviewRuntimeError::Forbidden => Self::Forbidden(FailedCheck::Operation), + ReviewRuntimeError::NotHeldByReader => Self::NotFound(FailedCheck::Ownership), + ReviewRuntimeError::Forbidden(check) => Self::Forbidden(check), ReviewRuntimeError::SubmissionConflict => Self::ReviewSubmissionConflict, ReviewRuntimeError::ResultExpired => Self::ReviewResultExpired, ReviewRuntimeError::TaskNotHeld => Self::ReviewTaskNotHeld, @@ -2866,6 +2878,63 @@ mod tests { Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")) } + #[test] + fn store_service_and_review_refusals_keep_the_check_their_producer_named() { + for check in [ + FailedCheck::Operation, + FailedCheck::AccessProfile, + FailedCheck::SeparationOfDuties, + FailedCheck::TaskGrantExpired, + FailedCheck::TaskGrantStatus, + FailedCheck::RequesterClient, + ] { + assert_eq!( + HttpError::from(StoreError::Forbidden(check)).failed_check(), + Some(check) + ); + assert_eq!( + HttpError::from(ServiceError::Forbidden(check)).failed_check(), + Some(check) + ); + assert_eq!( + HttpError::from(ReviewRuntimeError::Forbidden(check)).failed_check(), + Some(check) + ); + } + for check in [FailedCheck::TaskGrantBinding, FailedCheck::AccessProfile] { + assert_eq!( + HttpError::from(ServiceError::NotFound(check)).failed_check(), + Some(check) + ); + } + assert_eq!( + HttpError::from(ReviewRuntimeError::NotHeldByReader).failed_check(), + Some(FailedCheck::Ownership) + ); + assert_eq!( + HttpError::from(ReviewRuntimeError::NotFound).failed_check(), + Some(FailedCheck::Visibility) + ); + assert_eq!( + HttpError::from(ReviewRuntimeError::NotHeldByReader).problem(), + ProblemCode::RequestNotFound + ); + } + + #[tokio::test] + async fn a_bare_not_found_is_empty_and_counted_as_concealed() { + let response = bare_not_found(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!( + response.extensions().get::().map(|n| n.check), + Some(FailedCheck::Visibility) + ); + let body = axum::body::to_bytes(response.into_body(), 1024) + .await + .unwrap(); + assert!(body.is_empty()); + } + #[tokio::test] async fn each_refusal_is_counted_once_under_its_own_check() { let recorder = recorder(); diff --git a/crates/registry-casework/src/review.rs b/crates/registry-casework/src/review.rs index 56cbde2218..be918ed818 100644 --- a/crates/registry-casework/src/review.rs +++ b/crates/registry-casework/src/review.rs @@ -5,6 +5,7 @@ use chrono::{DateTime, TimeDelta, Utc}; use deadpool_postgres::GenericClient; use deadpool_postgres::Transaction; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest as _, Sha256}; @@ -107,8 +108,10 @@ pub enum ReviewRuntimeError { QueryTooBroad, #[error("the review resource was not found")] NotFound, + #[error("the review resource was not found")] + NotHeldByReader, #[error("the caller is not authorized for this review operation")] - Forbidden, + Forbidden(FailedCheck), #[error("the retained submission has different canonical content")] SubmissionConflict, #[error("the retained review result has expired")] @@ -175,8 +178,12 @@ fn map_review_decision_error(error: ReviewDecisionError) -> ReviewRuntimeError { } ReviewDecisionError::InitiatorExcluded => ReviewRuntimeError::InitiatorExcluded, ReviewDecisionError::DuplicateReviewer - | ReviewDecisionError::PreviousStageReviewerExcluded - | ReviewDecisionError::ProfileNotEligible => ReviewRuntimeError::Forbidden, + | ReviewDecisionError::PreviousStageReviewerExcluded => { + ReviewRuntimeError::Forbidden(FailedCheck::SeparationOfDuties) + } + ReviewDecisionError::ProfileNotEligible => { + ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile) + } ReviewDecisionError::Validation(error) => review_validation_error(error), ReviewDecisionError::Policy(_) => ReviewRuntimeError::Corrupt, ReviewDecisionError::OutcomeNotAllowed { declared, .. } => ReviewRuntimeError::Validation( @@ -492,7 +499,7 @@ impl CaseworkService { ) -> Result { require_human_reviewer(actor)?; if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let page = self .review_task_page( @@ -620,7 +627,7 @@ impl CaseworkService { match tokio::time::timeout_at(deadline_at, preflight).await { Ok(Ok(())) => {} Ok(Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired | ReviewRuntimeError::SourceProfileRequired @@ -764,7 +771,7 @@ impl CaseworkService { } Ok(_) => {} Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired, ) => { @@ -799,7 +806,7 @@ impl CaseworkService { skipped_without_source_profile = true; } Ok(Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::SourceProfileNotApplicable, )) => { @@ -964,7 +971,7 @@ impl CaseworkService { .await { Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired, ) => { @@ -1135,7 +1142,7 @@ impl CaseworkService { .source_namespaces .contains(&request.subject.source) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } self.store .cancel_review( @@ -1359,7 +1366,7 @@ impl CaseworkService { event_id: Uuid, ) -> Result { if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } self.store.review_accountability(actor, event_id).await } @@ -1379,7 +1386,7 @@ impl CaseworkService { } let producer = self.producer_for_actor(actor)?.producer; if request.audience != ReviewHistoryAudience::Requester { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } Some(producer) } else { @@ -1671,7 +1678,7 @@ impl CaseworkService { .contains(&request.subject.source) || request.subject.source != request.subject.source.trim() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } Ok(admission) } @@ -1681,7 +1688,7 @@ impl CaseworkService { actor: &ActorContext, ) -> Result { if actor.role != registry_casework_core::CaseworkActsAs::Requester { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } self.project .trusted_producers @@ -1693,7 +1700,7 @@ impl CaseworkService { }) .cloned() .map(|producer| ProducerAdmission { producer }) - .ok_or(ReviewRuntimeError::Forbidden) + .ok_or(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)) } /// The producer itself, or else a person whose profile some producer @@ -1705,7 +1712,7 @@ impl CaseworkService { ) -> Result { match self.producer_for_actor(actor) { Ok(admission) => return Ok(RequesterReader::Producer(Box::new(admission.producer))), - Err(ReviewRuntimeError::Forbidden) => {} + Err(ReviewRuntimeError::Forbidden(_)) => {} Err(error) => return Err(error), } let producers = self @@ -1716,7 +1723,7 @@ impl CaseworkService { .map(|producer| producer.id.clone()) .collect::>(); if producers.is_empty() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)); } Ok(RequesterReader::Initiator(producers)) } @@ -1820,7 +1827,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; // The UUID names an immutable scan position, not a claim about the @@ -1888,7 +1895,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; let supervisory = view.is_supervisory(); @@ -1978,7 +1985,7 @@ impl PostgresStore { let membership = match actor.role { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", - _ => return Err(ReviewRuntimeError::Forbidden), + _ => return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)), }; let position = match cursor { Some(id) => Some( @@ -2049,7 +2056,7 @@ impl PostgresStore { let membership = match actor.role { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", - _ => return Err(ReviewRuntimeError::Forbidden), + _ => return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)), }; let client = self.client().await?; client @@ -2180,7 +2187,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; let client = self.client().await?; @@ -2681,7 +2688,7 @@ impl PostgresStore { .review_policies .iter() .find(|policy| policy.id == request.policy.id) - .ok_or(ReviewRuntimeError::Forbidden)?; + .ok_or(ReviewRuntimeError::Forbidden(FailedCheck::Operation))?; let snapshot = project .compile_policy(&policy.id) .map_err(|_| ReviewRuntimeError::Corrupt)?; @@ -2719,7 +2726,7 @@ impl PostgresStore { .as_ref() .ok_or(ReviewRuntimeError::Corrupt)?; if request.subject.source != provider.source_namespace { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } } _ => return Err(ReviewRuntimeError::Invalid), @@ -3291,7 +3298,7 @@ impl PostgresStore { .get(usize::from(stage_index)) .ok_or(ReviewRuntimeError::Corrupt)?; if !stage.deciding_profiles.contains(&actor.profile_id) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)); } ensure_actor_serves_review_queue(&transaction, actor, &row.get::<_, String>(2)).await?; if stage.exclude_initiator && record.initiator.as_ref() == Some(&actor.principal) { @@ -3315,14 +3322,14 @@ impl PostgresStore { return Err(if previous.get::<_, i32>(0) == i32::from(stage_index) { ReviewRuntimeError::DistinctApproverRequired } else { - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(FailedCheck::SeparationOfDuties) }); } if !active_review_absences(&transaction, &actor.principal, now) .await? .is_empty() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let state: String = row.get(3); let held_by_caller = state == "claimed" @@ -3515,7 +3522,7 @@ impl PostgresStore { ensure_review_mutation_actor_authorized(&transaction, &record, actor, task_id).await?; } else { if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } ensure_actor_serves_review_queue(&transaction, actor, &task_queue).await?; } @@ -3558,10 +3565,10 @@ impl PostgresStore { .get(usize::from(stage_index)) .ok_or(ReviewRuntimeError::Corrupt)?; if delegate && !stage.deciding_profiles.contains(&actor.profile_id) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)); } if !delegate && actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let holder = match ( row.get::<_, Option>(4), @@ -3574,7 +3581,7 @@ impl PostgresStore { let queue = row.get::<_, String>(2); if delegate { if holder.as_ref() != Some(&actor.principal) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Ownership)); } ensure_actor_serves_review_queue(&transaction, actor, &queue).await?; } else if transaction @@ -3588,7 +3595,7 @@ impl PostgresStore { .await? .is_none() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } ensure_review_identity_eligible( &transaction, @@ -4172,7 +4179,7 @@ impl PostgresStore { .await { Ok(()) => {} - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) => return Ok(()), + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) => return Ok(()), Err(error) => return Err(error), } @@ -5037,7 +5044,7 @@ async fn insert_stage_tasks( .map_err(map_review_source_error)?; observed.check(&expected).map_err(map_review_source_error)?; if !observed.reviewable { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::SourceAuthority)); } observed.fields } @@ -5896,7 +5903,9 @@ async fn ensure_review_identity_eligible( membership_kinds: &[String], ) -> Result<(), ReviewRuntimeError> { if stage.exclude_initiator && record.initiator.as_ref() == Some(person) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties, + )); } if transaction .query_opt( @@ -5914,7 +5923,9 @@ async fn ensure_review_identity_eligible( .await? .is_some() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties, + )); } if transaction .query_opt( @@ -5927,7 +5938,7 @@ async fn ensure_review_identity_eligible( .await? .is_none() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } Ok(()) } @@ -5941,7 +5952,7 @@ async fn ensure_actor_serves_review_queue( CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; if transaction @@ -5960,7 +5971,7 @@ async fn ensure_actor_serves_review_queue( .await? .is_none() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } Ok(()) } @@ -6315,7 +6326,7 @@ fn require_human_reviewer(actor: &ActorContext) -> Result<(), ReviewRuntimeError | registry_casework_core::CaseworkActsAs::Supervisor ) .then_some(()) - .ok_or(ReviewRuntimeError::Forbidden) + .ok_or(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) } fn ensure_review_result_retained(record: &ReviewRequestRecord) -> Result<(), ReviewRuntimeError> { @@ -6368,7 +6379,7 @@ async fn ensure_review_stage_queue_access( CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; if eligible_stages.is_empty() { @@ -6411,7 +6422,9 @@ async fn ensure_review_mutation_actor_authorized( task_id: Uuid, ) -> Result<(), ReviewRuntimeError> { match ensure_review_reviewer_access(transaction, record, actor, Some(task_id), true).await { - Err(ReviewRuntimeError::NotFound) => Err(ReviewRuntimeError::Forbidden), + Err(ReviewRuntimeError::NotFound) => { + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) + } result => result, } } @@ -6475,7 +6488,7 @@ fn map_reviewer_conflict(error: tokio_postgres::Error) -> ReviewRuntimeError { .as_db_error() .is_some_and(|error| error.code() == &tokio_postgres::error::SqlState::UNIQUE_VIOLATION) { - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(FailedCheck::SeparationOfDuties) } else { ReviewRuntimeError::Store(StoreError::Postgres(error)) } @@ -6622,7 +6635,7 @@ impl CaseworkService { .get(field) .cloned() .map(|value| (field.clone(), value)) - .ok_or(crate::ServiceError::Forbidden) + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation)) }) .collect(), ( @@ -6652,7 +6665,7 @@ impl CaseworkService { return Err(ReviewContextError::Invalid.into()); } if !observed.reviewable { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::SourceAuthority)); } return Ok(Default::default()); } @@ -6678,7 +6691,7 @@ impl CaseworkService { .map_err(|_| crate::ServiceError::Context(ReviewContextError::Unavailable))??; observed.check(&expected)?; if !observed.reviewable { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::SourceAuthority)); } Ok(observed.fields) } @@ -6696,10 +6709,11 @@ fn review_service_error(error: ReviewRuntimeError) -> crate::ServiceError { ReviewContextError::VersionUnavailable.into() } ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired => { - crate::ServiceError::NotFound + crate::ServiceError::NotFound(FailedCheck::Visibility) } ReviewRuntimeError::RevisionConflict => StoreError::Conflict.into(), - _ => crate::ServiceError::Forbidden, + ReviewRuntimeError::Forbidden(check) => crate::ServiceError::Forbidden(check), + _ => crate::ServiceError::Forbidden(FailedCheck::Operation), } } @@ -6792,4 +6806,75 @@ mod tests { assert_ne!(actor_reference(&first), actor_reference(&second)); assert!(!actor_reference(&first).contains("person")); } + + fn refused_check(error: ReviewRuntimeError) -> FailedCheck { + match error { + ReviewRuntimeError::Forbidden(check) => check, + other => panic!("expected a forbidden answer, got {other:?}"), + } + } + + fn actor(role: CaseworkActsAs) -> ActorContext { + ActorContext { + principal: IssuerPrincipal { + issuer: "https://issuer.example".to_owned(), + subject: "person".to_owned(), + }, + profile_id: "profile".to_owned(), + role, + } + } + + #[test] + fn a_reviewer_who_already_acted_is_refused_for_separation_of_duties() { + for error in [ + ReviewDecisionError::DuplicateReviewer, + ReviewDecisionError::PreviousStageReviewerExcluded, + ] { + assert_eq!( + refused_check(map_review_decision_error(error)), + FailedCheck::SeparationOfDuties + ); + } + } + + #[test] + fn a_profile_outside_the_stage_is_refused_for_its_access_profile() { + assert_eq!( + refused_check(map_review_decision_error( + ReviewDecisionError::ProfileNotEligible + )), + FailedCheck::AccessProfile + ); + } + + #[test] + fn only_staff_and_supervisors_pass_the_human_reviewer_check() { + assert!(require_human_reviewer(&actor(CaseworkActsAs::Staff)).is_ok()); + assert!(require_human_reviewer(&actor(CaseworkActsAs::Supervisor)).is_ok()); + for role in [CaseworkActsAs::Administrator, CaseworkActsAs::Requester] { + assert_eq!( + refused_check(require_human_reviewer(&actor(role)).unwrap_err()), + FailedCheck::Operation + ); + } + } + + #[test] + fn a_service_refusal_keeps_the_check_the_review_layer_named() { + for check in [ + FailedCheck::SeparationOfDuties, + FailedCheck::AccessProfile, + FailedCheck::Ownership, + ] { + assert!(matches!( + review_service_error(ReviewRuntimeError::Forbidden(check)), + crate::ServiceError::Forbidden(kept) if kept == check + )); + } + assert!(matches!( + review_service_error(ReviewRuntimeError::TaskNotHeld), + crate::ServiceError::Forbidden(FailedCheck::Operation) + )); + } } diff --git a/crates/registry-casework/src/review/inbox.rs b/crates/registry-casework/src/review/inbox.rs index a15de044b7..9dd3e0c7f5 100644 --- a/crates/registry-casework/src/review/inbox.rs +++ b/crates/registry-casework/src/review/inbox.rs @@ -306,7 +306,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; let client = self.client().await?; @@ -402,7 +402,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; let supervisory = view.is_supervisory(); diff --git a/crates/registry-casework/src/review/staffing.rs b/crates/registry-casework/src/review/staffing.rs index 83d8042be4..8e990a5bdf 100644 --- a/crates/registry-casework/src/review/staffing.rs +++ b/crates/registry-casework/src/review/staffing.rs @@ -140,7 +140,7 @@ impl CaseworkService { match tokio::time::timeout_at(until, check).await { Ok(Ok(())) => {} Ok(Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::SourceProfileRequired | ReviewRuntimeError::SourceProfileNotApplicable, @@ -232,7 +232,7 @@ impl CaseworkService { skipped_without_source_profile = true; continue; } - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) => { + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) => { continue } Err(error) => return Err(error), @@ -366,7 +366,7 @@ impl CaseworkService { ) -> Result { request.check().map_err(|_| ReviewRuntimeError::Invalid)?; if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let client = self.store.client().await?; let rows=client.query("SELECT task_id FROM casework_review_tasks WHERE state='claimed' AND holder_issuer=$1 AND holder_subject=$2 AND ($3::text IS NULL OR queue_id=$3) ORDER BY task_id LIMIT 101",&[&request.from.issuer,&request.from.subject,&request.queue]).await?; @@ -421,7 +421,7 @@ impl CaseworkService { ) -> Result { request.check().map_err(|_| ReviewRuntimeError::Invalid)?; if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let (movement, tasks, directory_revision) = self .store @@ -559,7 +559,9 @@ async fn validate_caseload_set( let stage_index = u16::try_from(row.get::<_, i32>(1)).map_err(|_| ReviewRuntimeError::Corrupt)?; if !selected_stages.insert((request_id, stage_index)) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties, + )); } let queue: String = row.get(2); if record.lifecycle != ReviewRequestLifecycle::Reviewing @@ -601,7 +603,7 @@ async fn validate_caseload_set( .await? .is_empty() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } ensure_review_identity_eligible( tx, @@ -613,7 +615,7 @@ async fn validate_caseload_set( &membership_kinds, ) .await?; - if tx.query_opt("SELECT 1 FROM casework_review_tasks WHERE request_id=$1 AND stage_index=$2 AND task_id<>$3 AND holder_issuer=$4 AND holder_subject=$5 AND state IN('open','claimed')",&[&request_id,&i32::from(stage_index),&task.task_id,&movement.to.issuer,&movement.to.subject]).await?.is_some(){return Err(ReviewRuntimeError::Forbidden)} + if tx.query_opt("SELECT 1 FROM casework_review_tasks WHERE request_id=$1 AND stage_index=$2 AND task_id<>$3 AND holder_issuer=$4 AND holder_subject=$5 AND state IN('open','claimed')",&[&request_id,&i32::from(stage_index),&task.task_id,&movement.to.issuer,&movement.to.subject]).await?.is_some(){return Err(ReviewRuntimeError::Forbidden(FailedCheck::SeparationOfDuties))} } Ok(()) } @@ -647,7 +649,7 @@ impl CaseworkService { ) -> Result { request.check().map_err(|_| ReviewRuntimeError::Invalid)?; if actor.role != CaseworkActsAs::Administrator { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } for id in &request.task_ids { let record = self.store.review_request_for_task(*id).await?; @@ -707,7 +709,7 @@ impl CaseworkService { ) -> Result { request.check().map_err(|_| ReviewRuntimeError::Invalid)?; if actor.role != CaseworkActsAs::Administrator { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let (inputs, tasks, directory_revision) = self .store diff --git a/crates/registry-casework/src/service.rs b/crates/registry-casework/src/service.rs index 034514739a..5bda92e684 100644 --- a/crates/registry-casework/src/service.rs +++ b/crates/registry-casework/src/service.rs @@ -1,5 +1,6 @@ use crate::{PostgresStore, StoreError}; use registry_casework_core::{CaseworkProject, InboxPolicy, ReviewContextProvider}; +use registry_platform_authcommon::FailedCheck; use std::collections::BTreeMap; use std::sync::Arc; #[derive(Clone)] @@ -76,9 +77,9 @@ pub enum ServiceError { #[error("the Casework service configuration is invalid")] Configuration, #[error("the requested review task was not found")] - NotFound, + NotFound(FailedCheck), #[error("the caller is not authorized")] - Forbidden, + Forbidden(FailedCheck), #[error(transparent)] ReviewValidation(#[from] registry_casework_core::ReviewValidationError), #[error(transparent)] diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index 90639d572d..a52d472c11 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -5,6 +5,7 @@ use registry_casework_core::{ ActorContext, BootstrapDirectoryRequest, CaseworkActsAs, DirectoryMember, DirectoryResponse, IssuerPrincipal, TeamRecord, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::SecretResolver; use serde_json::{json, Value}; use std::str::FromStr; @@ -425,7 +426,7 @@ impl PostgresStore { idempotency_key: &str, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } let request_hash = request_hash(request)?; let mut audit = self @@ -528,7 +529,7 @@ impl PostgresStore { actor: &ActorContext, ) -> Result<(i64, Vec), StoreError> { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } let mut client = self.client().await?; let transaction = client.transaction().await?; @@ -548,7 +549,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } }; let client = self.client().await?; @@ -756,7 +757,7 @@ pub enum StoreError { #[error("the requested resource was not found")] NotFound, #[error("the caller is not authorized for this operation")] - Forbidden, + Forbidden(FailedCheck), #[error("the expected revision is no longer current")] Conflict, #[error("the review task is already claimed")] diff --git a/crates/registry-casework/src/task_grants.rs b/crates/registry-casework/src/task_grants.rs index d71c7ad2a0..f1d5eaa3fc 100644 --- a/crates/registry-casework/src/task_grants.rs +++ b/crates/registry-casework/src/task_grants.rs @@ -2,6 +2,7 @@ use crate::{PostgresStore, StoreError}; use chrono::{DateTime, Utc}; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use tokio_postgres::Transaction; @@ -273,7 +274,7 @@ impl PostgresStore { .await? .ok_or(StoreError::NotFound)?; if !template_active(&transaction, &grant.template).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } // The revision-agnostic eligibility call confirms the caller's current // authority without binding it to the retry's original revision. @@ -287,7 +288,7 @@ impl PostgresStore { ) .await? else { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::AccessProfile)); }; let mut request = json!({ "reviewTaskId": grant.task_id, @@ -372,7 +373,8 @@ impl PostgresStore { if serde_json::to_vec(&record)?.len() > 65_536 { return Err(StoreError::Invalid); } - let role = membership_kind(actor.role).ok_or(StoreError::Forbidden)?; + let role = + membership_kind(actor.role).ok_or(StoreError::Forbidden(FailedCheck::Operation))?; transaction .execute( "INSERT INTO casework_review_task_grants( @@ -591,7 +593,7 @@ impl PostgresStore { let grant: ReviewTaskGrant = serde_json::from_value(row.get(0))?; if let Some(actor) = actor { let Some(kind) = membership_kind(actor.role) else { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); }; if !template_active(&transaction, &grant.template).await? || !grant.template.eligible_profiles.contains(&actor.profile_id) @@ -625,7 +627,7 @@ impl PostgresStore { .await? .get::<_, bool>(0) { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::AccessProfile)); } } let first_invalidation = transaction @@ -799,7 +801,7 @@ impl TaskAuthority { ) -> Result { use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; if now >= grant_expires_at { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::TaskGrantExpired)); } // Evidence checks only the grant deadline and no grant status, so an // Evidence grant is never signed under the deferred window. @@ -809,7 +811,7 @@ impl TaskAuthority { registry_casework_core::TaskGrantBounds::Evidence { .. } ) { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } let expires = grant_expires_at.min( now.checked_add(registry_casework_core::TASK_ASSERTION_LIFETIME_SECONDS) @@ -851,7 +853,7 @@ impl crate::CaseworkService { pub(crate) fn task_jwks(&self) -> Result { self.task_authority .as_ref() - .ok_or(crate::ServiceError::NotFound)? + .ok_or(crate::ServiceError::NotFound(FailedCheck::Visibility))? .jwks() .map_err(Into::into) } @@ -955,7 +957,7 @@ impl crate::CaseworkService { let authority = self .task_authority .as_ref() - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation))?; let template = self .project .task_templates @@ -965,13 +967,13 @@ impl crate::CaseworkService { && template.id == request.template_id && template.version == request.template_version }) - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation))?; let Some((request_id, current_revision, subject, assignment_generation)) = self .store .eligible_review_task_template(actor, task_id, template) .await? else { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::AccessProfile)); }; if current_revision != revision { return Err(StoreError::Conflict.into()); @@ -988,7 +990,7 @@ impl crate::CaseworkService { let values = self.review_grant_fields(task_id, revision, &fields).await?; let subjects = template .disclosed_subjects(&values) - .map_err(|_| crate::ServiceError::Forbidden)?; + .map_err(|_| crate::ServiceError::Forbidden(FailedCheck::Operation))?; let now = now_seconds()?; let grant = ReviewTaskGrant { id: Uuid::new_v4(), @@ -1027,7 +1029,7 @@ impl crate::CaseworkService { .preview_review_task_templates(actor, task_id, source_profile, token) .await?; if previews.task_revision == 0 { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::Visibility)); } let grants = self.store.review_task_grants_for_task(task_id).await?; let mut eligible = false; @@ -1048,7 +1050,7 @@ impl crate::CaseworkService { } } if !eligible { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::AccessProfile)); } Ok(TaskGrantList { grants: grants.iter().map(review_grant_view).collect(), @@ -1063,7 +1065,7 @@ impl crate::CaseworkService { ) -> Result { let stored = self.store.review_task_grant(id).await?; if stored.grant.task_id != task_id { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::TaskGrantBinding)); } self.store .invalidate_review_task_grant(id, "revoked", Some(actor)) @@ -1079,8 +1081,13 @@ impl crate::CaseworkService { id: Uuid, ) -> Result { let stored = self.store.review_task_grant(id).await?; - if stored.invalidated || now_seconds()? >= stored.grant.expires_at { - return Err(crate::ServiceError::Forbidden); + if stored.invalidated { + return Err(crate::ServiceError::Forbidden(FailedCheck::TaskGrantStatus)); + } + if now_seconds()? >= stored.grant.expires_at { + return Err(crate::ServiceError::Forbidden( + FailedCheck::TaskGrantExpired, + )); } let grant = &stored.grant; let Some(template) = self.project.task_templates.iter().find(|template| { @@ -1090,7 +1097,7 @@ impl crate::CaseworkService { self.store .invalidate_review_task_grant(id, "template", None) .await?; - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::TaskGrantStatus)); }; let configured_approver_role = self .project @@ -1103,7 +1110,7 @@ impl crate::CaseworkService { .check_review_task_grant_eligibility(grant, template, configured_approver_role) .await? { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::AccessProfile)); } let fields = template .subjects @@ -1137,15 +1144,19 @@ impl crate::CaseworkService { self.store .invalidate_review_task_grant(id, "source", None) .await?; - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::TaskGrantStatus)); } if !self .store .check_review_task_grant_eligibility(grant, template, configured_approver_role) .await? - || now_seconds()? >= grant.expires_at { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::AccessProfile)); + } + if now_seconds()? >= grant.expires_at { + return Err(crate::ServiceError::Forbidden( + FailedCheck::TaskGrantExpired, + )); } Ok(stored) } @@ -1157,7 +1168,7 @@ impl crate::CaseworkService { let authority = self .task_authority .as_ref() - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation))?; let stored = self.store.review_task_grant(id).await?; require_grant_client(client, &stored.grant.template)?; let stored = self.active_review_task(id).await?; @@ -1174,20 +1185,20 @@ impl crate::CaseworkService { let authority = self .task_authority .as_ref() - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation))?; let client = client .matched_client_id() .ok() .flatten() - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::RequesterClient))?; let resource = authority .config .status_clients .get(client) - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::RequesterClient))?; let stored = self.store.review_task_grant(id).await?; if stored.grant.template.resource != *resource { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::RequesterClient)); } match self.active_review_task(id).await { Ok(stored) => Ok(active_grant_status( @@ -1197,7 +1208,7 @@ impl crate::CaseworkService { stored.grant.subjects, stored.grant.expires_at, )), - Err(crate::ServiceError::Forbidden) => Ok(inactive_grant_status()), + Err(crate::ServiceError::Forbidden(_)) => Ok(inactive_grant_status()), Err(error) => Err(error), } } @@ -1211,7 +1222,7 @@ fn require_grant_client( || client.claims.sub.as_deref() != Some(template.agent.subject.as_str()) || client.claims.iss.as_deref() != Some(template.agent.issuer.as_str()) { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::TaskGrantBinding)); } Ok(()) } @@ -1362,7 +1373,7 @@ mod evidence_assertion_tests { template.authorization_mode = registry_casework_core::TaskAuthorizationMode::Deferred; assert!(matches!( authority.assertion_for(Uuid::new_v4(), &template, &holder, &fields, 1000, 200), - Err(StoreError::Forbidden) + Err(StoreError::Forbidden(FailedCheck::Operation)) )); } #[test] @@ -1394,7 +1405,7 @@ mod evidence_assertion_tests { assert!(payload.get("registry_grant_authority").is_none()); assert!(matches!( authority.assertion_for(Uuid::new_v4(), &template(), &holder, &fields, 200, 200), - Err(StoreError::Forbidden) + Err(StoreError::Forbidden(FailedCheck::TaskGrantExpired)) )); } } diff --git a/crates/registry-casework/src/task_grants/http_tests.rs b/crates/registry-casework/src/task_grants/http_tests.rs index bac3d445d9..bace8c3ab7 100644 --- a/crates/registry-casework/src/task_grants/http_tests.rs +++ b/crates/registry-casework/src/task_grants/http_tests.rs @@ -1848,7 +1848,7 @@ async fn review_task_grant_approval_recovers_a_lost_response_after_the_task_revi f.store .approve_review_task_grant(&actor, "lost-response", grant) .await, - Err(StoreError::Forbidden) + Err(StoreError::Forbidden(_)) )); f.admin diff --git a/crates/registry-casework/src/task_grants/lock_order_tests.rs b/crates/registry-casework/src/task_grants/lock_order_tests.rs index dd74f8df4e..ac11aa9904 100644 --- a/crates/registry-casework/src/task_grants/lock_order_tests.rs +++ b/crates/registry-casework/src/task_grants/lock_order_tests.rs @@ -287,7 +287,7 @@ async fn grant_approval_and_decision_lock_request_before_task_without_deadlock() .expect("lock-order interleaving task"); let approval_outcome = match &approval_result { Ok(_) => "approved".to_owned(), - Err(StoreError::Forbidden) => "forbidden".to_owned(), + Err(StoreError::Forbidden(_)) => "forbidden".to_owned(), Err(StoreError::Postgres(error)) if error.code() == Some(&SqlState::T_R_DEADLOCK_DETECTED) => { @@ -303,7 +303,7 @@ async fn grant_approval_and_decision_lock_request_before_task_without_deadlock() ); assert_eq!(decision_status, StatusCode::NO_CONTENT); assert!( - matches!(approval_result, Err(StoreError::Forbidden)), + matches!(approval_result, Err(StoreError::Forbidden(_))), "the queued approval must recheck and refuse the terminal task" ); } diff --git a/crates/registry-casework/tests/golden/refusal_responses.json b/crates/registry-casework/tests/golden/refusal_responses.json index cf90339a48..a04dcbaedb 100644 --- a/crates/registry-casework/tests/golden/refusal_responses.json +++ b/crates/registry-casework/tests/golden/refusal_responses.json @@ -334,6 +334,38 @@ "name": "delegated-read-unknown-policy", "status": 403 }, + { + "body": { + "code": "operation.not-authorized", + "detail": "Your current Casework authority does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/operation/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "supervision-list-on-a-staff-profile", + "status": 403 + }, + { + "body": { + "code": "operation.not-authorized", + "detail": "Your current Casework authority does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/operation/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "reviewer-list-on-a-requester-profile", + "status": 403 + }, { "body": { "code": "authentication.refused", diff --git a/crates/registry-casework/tests/refusal_golden.rs b/crates/registry-casework/tests/refusal_golden.rs index 7a97bec77f..03ed463da0 100644 --- a/crates/registry-casework/tests/refusal_golden.rs +++ b/crates/registry-casework/tests/refusal_golden.rs @@ -282,6 +282,23 @@ fn cases(idp: &MockIdp) -> Vec { (DELEGATED_READER_HEADER, "reader".to_owned()), ], ), + case( + "supervision-list-on-a-staff-profile", + "operation", + "GET", + "/v1/review-tasks/supervision", + as_staff(&staff), + ), + case( + "reviewer-list-on-a-requester-profile", + "operation", + "GET", + list, + vec![ + ("authorization", bearer(&requester)), + (PROFILE_HEADER, "requester".to_owned()), + ], + ), case( "source-bearer-with-two-tokens", "credential-malformed", diff --git a/crates/registry-casework/tests/review_acceptance_postgres.rs b/crates/registry-casework/tests/review_acceptance_postgres.rs index 3b3e251cf7..6a79fc3ec6 100644 --- a/crates/registry-casework/tests/review_acceptance_postgres.rs +++ b/crates/registry-casework/tests/review_acceptance_postgres.rs @@ -348,7 +348,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { "reviewer-create" ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let accepted = f.create("notice").await; assert!(f.request("notice").policy.matches(&accepted.policy)); @@ -370,7 +370,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { accepted.request_id ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert!(matches!( f.service @@ -383,7 +383,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { "producer-claim" ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); } #[tokio::test] @@ -520,7 +520,7 @@ async fn current_policy_selection_recovers_before_updates_and_requires_live_auth revoked .create_review_request(&producer, request, "current-policy") .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!( f.db.query_one("SELECT count(*) FROM casework_review_requests", &[]) @@ -582,7 +582,7 @@ async fn concurrent_current_policy_acceptance_freezes_one_binding_and_refuses_in f.service .create_review_request(&producer, wrong_subject, "incompatible-subject") .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); } @@ -632,7 +632,7 @@ async fn submitted_two_stage_review_pins_policy_receipts_and_terminal_feed() { "same-reviewer" ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let held = f.claim(second, "b").await; f.service @@ -1204,7 +1204,7 @@ async fn source_visibility_and_directory_authority_are_both_live_at_caseload_app } ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!(before, f.holders().await); } @@ -1471,7 +1471,7 @@ async fn admission_namespace_cannot_substitute_the_pinned_provider_namespace() { "wrong-namespace" ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!( f.db.query_one("SELECT count(*) FROM casework_review_requests", &[]) @@ -1655,7 +1655,7 @@ async fn clock_recompute_uses_pinned_calendar_and_fences_changed_holiday_inputs( } ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); } diff --git a/crates/registry-casework/tests/review_directory_postgres.rs b/crates/registry-casework/tests/review_directory_postgres.rs index 5df3ea1702..203eab3d5c 100644 --- a/crates/registry-casework/tests/review_directory_postgres.rs +++ b/crates/registry-casework/tests/review_directory_postgres.rs @@ -527,7 +527,7 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden(_))) )); let bulk_a = (0..100) @@ -553,7 +553,7 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden(_))) )); let staff_absence_people = fixture .service @@ -583,7 +583,7 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden(_))) )); let revision = fixture .service @@ -743,7 +743,7 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden(_))) )); let unrelated_supervisor = actor("unrelated", CaseworkActsAs::Supervisor, "supervisor"); let empty = fixture @@ -1006,7 +1006,7 @@ async fn supervisor_cannot_record_cover_from_an_unsupervised_shared_team() { "unsupervised-shared-cover", ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden(_))) )); } @@ -1166,7 +1166,7 @@ async fn absence_update_preserves_owner_and_delete_replay_rechecks_current_autho "delete-own-absence", ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden(_))) )); } diff --git a/crates/registry-casework/tests/review_postgres.rs b/crates/registry-casework/tests/review_postgres.rs index e2261c0c35..a337636b75 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -1995,7 +1995,7 @@ async fn recovery_pins_policy_and_terminal_settlement_emits_atomically() { .service_v1 .review_accountability(&fixture.reviewer_b, accountability_event) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let result = fixture @@ -4325,7 +4325,7 @@ async fn accountability_receipts_pin_selected_outcomes_through_independent_reten service .review_accountability(&fixture.reviewer_b, *event) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let outsider = actor("outside-team", CaseworkActsAs::Supervisor, "supervisor"); assert!(matches!( @@ -4692,7 +4692,7 @@ async fn own_decisions_filter_authors_scope_and_continue_past_hidden_source_cand source .own_review_decisions(&fixture.producer, None, "", None, None, 1) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert!(matches!( source @@ -4705,7 +4705,7 @@ async fn own_decisions_filter_authors_scope_and_continue_past_hidden_source_cand 1 ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let wrong_profile = actor("reviewer-a", CaseworkActsAs::Staff, "not-pinned"); assert!(source @@ -7187,7 +7187,7 @@ async fn prior_stage_identity_and_invalid_structured_result_emit_nothing() { "claim-excluded-secondary", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!( count_for_request( @@ -7419,7 +7419,7 @@ async fn claim_and_decide_require_current_exact_queue_membership() { "nonmember-claim", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let assigned = fixture @@ -7484,7 +7484,7 @@ async fn claim_and_decide_require_current_exact_queue_membership() { "removed-holder-decision", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!( count_for_request( @@ -7547,7 +7547,7 @@ async fn delegation_requires_the_selected_profile_in_pinned_deciding_profiles() "delegate-ineligible-profile", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let unchanged = fixture .service_v1 @@ -7674,7 +7674,7 @@ async fn delegation_requires_membership_matching_the_selected_role_in_a_mixed_st "delegate-cross-role-membership", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) )); let persisted = fixture .database @@ -7755,7 +7755,7 @@ async fn delegation_requires_membership_matching_the_selected_role_in_a_mixed_st "delegate-exact-role-membership", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; assert_eq!( @@ -7816,7 +7816,7 @@ async fn assignment_requires_a_selected_supervisor_profile_despite_directory_mem "assign-staff-scoped-supervisor", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let unchanged = fixture .service_v1 @@ -7875,7 +7875,7 @@ async fn assignment_requires_a_selected_supervisor_profile_despite_directory_mem "assign-supervisor-scoped", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.supervisor, "supervisor", true).await; assert_eq!( @@ -7954,7 +7954,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "claim-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, project("1")); @@ -8042,7 +8042,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "release-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, project("1")); @@ -8166,7 +8166,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "decide-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, answer_project(false)); @@ -11516,7 +11516,7 @@ async fn review_task_coordination_preserves_exclusions_drafts_history_and_absenc "assign-initiator", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let assigned = fixture .service_v1 @@ -11557,7 +11557,7 @@ async fn review_task_coordination_preserves_exclusions_drafts_history_and_absenc "delegate-initiator", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); let delegated = fixture .service_v1 @@ -12019,7 +12019,7 @@ async fn staffing_diagnostic_is_disclosed_and_clears_when_responsibility_resumes 100 ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); // A diagnostic adds no authority. Concealed work matches unknown work for diff --git a/crates/registry-casework/tests/support/authority_closure_regressions.rs b/crates/registry-casework/tests/support/authority_closure_regressions.rs index d54e7a4c35..5565751833 100644 --- a/crates/registry-casework/tests/support/authority_closure_regressions.rs +++ b/crates/registry-casework/tests/support/authority_closure_regressions.rs @@ -283,7 +283,7 @@ async fn assignment_roles_stay_pinned_and_activation_refuses_changed_deciding_au let before = f.holders().await; assert!(matches!( assign(&service, task, "supervisor", "wrong-role").await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!(f.holders().await, before); let candidate = ActivationCandidate { diff --git a/crates/registry-casework/tests/support/inbox_pagination.rs b/crates/registry-casework/tests/support/inbox_pagination.rs index b3083be51a..a11b5d9138 100644 --- a/crates/registry-casework/tests/support/inbox_pagination.rs +++ b/crates/registry-casework/tests/support/inbox_pagination.rs @@ -574,7 +574,7 @@ async fn directory_revocation_during_source_io_is_rechecked_in_both_paths() { Ok(page) => assert!(page.items.is_empty()), Err(error) => assert!(matches!( error, - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired )), diff --git a/crates/registry-casework/tests/support/independent_staffing_activation.rs b/crates/registry-casework/tests/support/independent_staffing_activation.rs index d94b2076aa..a1ffcd90a7 100644 --- a/crates/registry-casework/tests/support/independent_staffing_activation.rs +++ b/crates/registry-casework/tests/support/independent_staffing_activation.rs @@ -25,7 +25,7 @@ async fn caseload_target_membership_must_match_the_pinned_deciding_profiles() { movement("supervisor", CaseworkActsAs::Supervisor), ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!(before, f.holders().await); @@ -43,7 +43,7 @@ async fn caseload_target_membership_must_match_the_pinned_deciding_profiles() { movement("supervisor", CaseworkActsAs::Supervisor), ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); // Explicit supervisor eligibility is supported for newly admitted work. @@ -92,7 +92,7 @@ async fn caseload_refuses_active_absence_and_rechecks_scheduled_absence_at_apply f.service .preview_review_caseload(&supervisor, None, "", movement("b", CaseworkActsAs::Staff)) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!(before, f.holders().await); @@ -123,7 +123,7 @@ async fn caseload_refuses_active_absence_and_rechecks_scheduled_absence_at_apply } ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(_)) )); assert_eq!(before, f.holders().await); } diff --git a/crates/registry-documents/Cargo.toml b/crates/registry-documents/Cargo.toml index a6d0b44bfa..b502e88031 100644 --- a/crates/registry-documents/Cargo.toml +++ b/crates/registry-documents/Cargo.toml @@ -52,6 +52,11 @@ name = "restore_drill" path = "tests/restore_drill.rs" required-features = ["postgres-test"] +[[test]] +name = "refusal_golden" +path = "tests/refusal_golden.rs" +required-features = ["postgres-test"] + [features] default = [] postgres-test = [] @@ -79,7 +84,7 @@ jsonwebtoken.workspace = true registry-documents-core.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true diff --git a/crates/registry-documents/src/auth.rs b/crates/registry-documents/src/auth.rs index 7626a62460..f62856f78a 100644 --- a/crates/registry-documents/src/auth.rs +++ b/crates/registry-documents/src/auth.rs @@ -18,10 +18,9 @@ use std::sync::Arc; use registry_documents_core::{ - AccessProfiles, AccessRefusal, ActorKind, ActorKindClaim, Caller, MissingScope, - VerifiedTokenFacts, + AccessProfiles, AccessRefusal, ActorKind, ActorKindClaim, Caller, VerifiedTokenFacts, }; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; use registry_platform_oidc::{ actor_kind, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, @@ -30,9 +29,6 @@ use thiserror::Error; pub struct DocumentsAuthenticator { verifier: TokenVerifier, - /// The configured claim the verifier reads scopes from, named in the - /// refusal log of a token that lacks a scope its profile requires. - scope_claim: String, claim_names: ClaimNames, profiles: AccessProfiles, /// Whether the deployment declared any assertion authority at all. @@ -52,7 +48,6 @@ impl DocumentsAuthenticator { .validate() .expect("the default contextual claim names are valid"); Self { - scope_claim: verifier.scope_claim.clone(), verifier: TokenVerifier::new(verifier, keys), claim_names, profiles, @@ -61,12 +56,16 @@ impl DocumentsAuthenticator { } /// Verify one credential and resolve it to exactly one access profile. + /// A refusal names the check it failed, for the operator's counter and + /// log line. The answer to the caller does not carry it. pub async fn authenticate(&self, token: &str) -> Result { - validate_compact_access_token(token).map_err(|_| AuthenticationError::Refused)?; - let verified = self.verifier.verify(token).await.map_err(|error| { - tracing::debug!(error = %error, "the Document Store bearer credential did not verify"); - verifier_failure(&error) - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| verifier_failure(&error))?; // An exchanged token names the authority whose assertion produced it. // The platform applies no rule while the deployment's map is empty, // so an empty map would trust every authority the issuer federates. @@ -77,11 +76,13 @@ impl DocumentsAuthenticator { tracing::debug!( "an exchanged credential arrived at a deployment that declared no assertion authority" ); - return Err(AuthenticationError::Profile); + return Err(AuthenticationError::Profile( + FailedCheck::TokenAssertionIssuer, + )); } let client_id = verified .matched_client_id() - .map_err(|_| AuthenticationError::Claims)?; + .map_err(|_| AuthenticationError::Claims(FailedCheck::TokenClient))?; let facts = VerifiedTokenFacts { issuer: verified.claims.iss.as_deref(), subject: verified.claims.sub.as_deref(), @@ -93,39 +94,45 @@ impl DocumentsAuthenticator { self.profiles .resolve(&facts) .map_err(|refusal| match refusal { - AccessRefusal::Profile => { - // A scope miss is the refusal an operator can fix. Log - // the configured claim and scope, never the token's own. - if let Some(missing) = self.profiles.missing_scope(&facts) { - tracing::info!( - "{}", - ScopeRefusal { - claim: &self.scope_claim, - missing, - } - ); - } - AuthenticationError::Profile - } - AccessRefusal::Claims => AuthenticationError::Claims, + AccessRefusal::Profile => AuthenticationError::Profile(self.profile_check(&facts)), + AccessRefusal::Claims => AuthenticationError::Claims(claims_check(&facts)), }) } -} -/// The value-free sentence logged when a token lacks a scope its access -/// profile requires. -struct ScopeRefusal<'a> { - claim: &'a str, - missing: MissingScope<'a>, + /// Which check a profile refusal failed. The access profiles answer only + /// that no profile admits the token. A missing scope is the one the + /// profiles name themselves. Resolving the same facts under each kind a + /// profile can admit separates a client no profile lists from a profile + /// that wants another actor kind: when no kind reaches past the profile + /// lookup, the client has no profile. + fn profile_check(&self, facts: &VerifiedTokenFacts<'_>) -> FailedCheck { + if self.profiles.missing_scope(facts).is_some() { + return FailedCheck::Scope; + } + let profile_exists = [ActorKind::Human, ActorKind::Service] + .into_iter() + .any(|kind| { + let probe = VerifiedTokenFacts { + actor_kind: ActorKindClaim::Present(kind), + ..*facts + }; + !matches!(self.profiles.resolve(&probe), Err(AccessRefusal::Profile)) + }); + if profile_exists { + FailedCheck::ActorKind + } else { + FailedCheck::AccessProfile + } + } } -impl std::fmt::Display for ScopeRefusal<'_> { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "a Document Store request was refused because the token's `{}` claim does not carry the `{}` scope access profile `{}` requires; issue that scope to the client, or set authentication.oidc.scopeClaim to the claim the issuer emits", - self.claim, self.missing.scope, self.missing.profile - ) +/// Which check an identity-claims refusal failed: a malformed actor-kind +/// claim, or a principal or issuer the profile cannot use. +fn claims_check(facts: &VerifiedTokenFacts<'_>) -> FailedCheck { + if facts.actor_kind == ActorKindClaim::Malformed { + FailedCheck::ActorKind + } else { + FailedCheck::TokenClaims } } @@ -139,25 +146,42 @@ impl std::fmt::Debug for DocumentsAuthenticator { } } +/// Why authentication did not admit a caller. Each refusal carries the check +/// it failed, which is operator-side only and never written to a response. #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] - Refused, + Refused(FailedCheck), #[error("the verified identity claims are invalid")] - Claims, + Claims(FailedCheck), #[error("the caller's access profile is not authorized for this request")] - Profile, + Profile(FailedCheck), /// The verifier could not reach a verdict at all. #[error("the credential could not be verified because this verifier cannot answer")] Unavailable, } +impl AuthenticationError { + /// The check this refusal failed. A new variant does not compile until it + /// names its check. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn failed_check(&self) -> FailedCheck { + match self { + Self::Refused(check) | Self::Claims(check) | Self::Profile(check) => *check, + Self::Unavailable => FailedCheck::KeySourceUnavailable, + } + } +} + /// Separate a verifier outage from a bad credential. /// /// A 401 tells a caller its credential is the problem, so it is reserved /// for credentials. When the issuer's discovery document or key set cannot /// be fetched, read, parsed, or used, nothing has been learned about the /// credential. +/// +/// A refusal of the credential names the check the verifier says it failed. fn verifier_failure(error: &OidcError) -> AuthenticationError { match error { OidcError::Transport(_) @@ -174,7 +198,7 @@ fn verifier_failure(error: &OidcError) -> AuthenticationError { // an unknown `kid`: a key the issuer never published is a forgery // signal. A variant the platform adds later reads as a refusal until // it is classified here, so a new outcome can never widen the door. - _ => AuthenticationError::Refused, + _ => AuthenticationError::Refused(error.failed_check()), } } @@ -289,53 +313,110 @@ pub(crate) mod tests { assert_eq!(caller.kind, ActorKind::Human); } + /// The check `authenticate` reports for `claims`, signed as a real token. + async fn refused_check(claims: serde_json::Value) -> FailedCheck { + authenticator() + .authenticate(&token(claims)) + .await + .expect_err("the token is refused") + .failed_check() + } + #[tokio::test] async fn a_malformed_or_foreign_credential_is_refused() { let authenticator = authenticator(); assert_eq!( authenticator.authenticate("not-a-token").await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused( + FailedCheck::CredentialMalformed + )) ); let mut foreign = citizen_claims(); foreign["iss"] = json!("https://other.example.test"); assert_eq!( authenticator.authenticate(&token(foreign)).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(FailedCheck::TokenIssuer)) ); let mut expired = citizen_claims(); expired["exp"] = json!(chrono::Utc::now().timestamp() - 3_600); assert_eq!( authenticator.authenticate(&token(expired)).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(FailedCheck::TokenTime)) + ); + let mut elsewhere = citizen_claims(); + elsewhere["aud"] = json!("urn:example:elsewhere"); + assert_eq!( + authenticator.authenticate(&token(elsewhere)).await, + Err(AuthenticationError::Refused(FailedCheck::TokenAudience)) ); } #[tokio::test] async fn a_token_outside_every_profile_is_a_profile_refusal() { - let authenticator = authenticator(); let mut unscoped = citizen_claims(); unscoped["scope"] = json!("documents:read"); assert_eq!( - authenticator.authenticate(&token(unscoped)).await, - Err(AuthenticationError::Profile) + authenticator().authenticate(&token(unscoped)).await, + Err(AuthenticationError::Profile(FailedCheck::Scope)) ); + // The verifier admits this client and no access profile lists it. let mut unprofiled = citizen_claims(); unprofiled["azp"] = json!("unprofiled-client"); assert_eq!( - authenticator.authenticate(&token(unprofiled)).await, - Err(AuthenticationError::Profile) + authenticator().authenticate(&token(unprofiled)).await, + Err(AuthenticationError::Profile(FailedCheck::AccessProfile)) ); let mut agent = citizen_claims(); agent["registry_actor_kind"] = json!("agent"); assert_eq!( - authenticator.authenticate(&token(agent)).await, - Err(AuthenticationError::Profile) + authenticator().authenticate(&token(agent)).await, + Err(AuthenticationError::Profile(FailedCheck::ActorKind)) ); let mut service = citizen_claims(); service["registry_actor_kind"] = json!("service"); assert_eq!( - authenticator.authenticate(&token(service)).await, - Err(AuthenticationError::Profile) + authenticator().authenticate(&token(service)).await, + Err(AuthenticationError::Profile(FailedCheck::ActorKind)) + ); + let mut absent = citizen_claims(); + absent + .as_object_mut() + .unwrap() + .remove("registry_actor_kind"); + assert_eq!(refused_check(absent).await, FailedCheck::ActorKind); + } + + #[tokio::test] + async fn a_client_no_profile_lists_is_not_a_missing_actor_kind() { + // With no actor kind either, the profile lookup still fails first. + let mut unprofiled = citizen_claims(); + unprofiled["azp"] = json!("unprofiled-client"); + unprofiled + .as_object_mut() + .unwrap() + .remove("registry_actor_kind"); + assert_eq!(refused_check(unprofiled).await, FailedCheck::AccessProfile); + } + + #[tokio::test] + async fn identity_claims_a_profile_cannot_use_are_claims_refusals() { + let mut malformed = citizen_claims(); + malformed["registry_actor_kind"] = json!(7); + assert_eq!( + authenticator().authenticate(&token(malformed)).await, + Err(AuthenticationError::Claims(FailedCheck::ActorKind)) + ); + let mut principal = citizen_claims(); + principal["sub"] = json!("a principal\u{7}with a control"); + assert_eq!( + authenticator().authenticate(&token(principal)).await, + Err(AuthenticationError::Claims(FailedCheck::TokenClaims)) + ); + let mut unlisted = citizen_claims(); + unlisted["azp"] = json!("unlisted-client"); + assert_eq!( + authenticator().authenticate(&token(unlisted)).await, + Err(AuthenticationError::Refused(FailedCheck::TokenClient)) ); } @@ -345,7 +426,9 @@ pub(crate) mod tests { exchanged[ASSERTION_ISSUER_CLAIM] = json!("https://partner.example.test"); assert_eq!( authenticator().authenticate(&token(exchanged)).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile( + FailedCheck::TokenAssertionIssuer + )) ); } @@ -359,5 +442,31 @@ pub(crate) mod tests { verifier_failure(&OidcError::Parse), AuthenticationError::Unavailable ); + assert_eq!( + AuthenticationError::Unavailable.failed_check(), + FailedCheck::KeySourceUnavailable + ); + } + + #[test] + fn a_refused_credential_carries_the_check_the_verifier_names() { + assert_eq!( + verifier_failure(&OidcError::SignatureInvalid), + AuthenticationError::Refused(FailedCheck::TokenSignature) + ); + assert_eq!( + verifier_failure(&OidcError::UnknownKid), + AuthenticationError::Refused(FailedCheck::TokenKey) + ); + } + + #[test] + fn no_refusal_prints_a_value_the_caller_sent() { + let canary = "canary-issuer.example.test"; + let error = verifier_failure(&OidcError::IssuerMismatch { + expected: "expected".to_owned(), + actual: canary.to_owned(), + }); + assert!(!format!("{error} {error:?}").contains(canary)); } } diff --git a/crates/registry-documents/src/config.rs b/crates/registry-documents/src/config.rs index fe1ee81189..8363b9b863 100644 --- a/crates/registry-documents/src/config.rs +++ b/crates/registry-documents/src/config.rs @@ -33,7 +33,8 @@ use registry_platform_config::{ use registry_platform_objectstore::{s3::S3Settings, verifier::HttpVerifierSettings}; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifierConfig, }; use registry_platform_yaml::{BoundedU32, BoundedU64, Diagnostic, ExternalId, LocalId, Report}; use serde::Deserialize; @@ -510,6 +511,18 @@ pub enum RuntimeConfigError { OidcJwksSecret(String), } +/// The static key set the operator pinned. A document that breaks a key set +/// rule is the operator's to fix, so the refusal says which rule: it never +/// holds a key value. +fn parse_static_key_set(document: &[u8]) -> Result { + parse_static_jwks(document).map_err(|error| match error { + OidcError::StaticKeySet(refusal) => RuntimeConfigError::OidcJwksSecret(format!( + "the document at authentication.oidc.jwksSource.documentRef was refused: {refusal}" + )), + _ => RuntimeConfigError::Oidc, + }) +} + fn refused(findings: &[Finding]) -> String { match findings { [] => "the runtime configuration was refused".to_owned(), @@ -596,8 +609,7 @@ impl RuntimeConfig { &error, )) })?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| RuntimeConfigError::Oidc)?; + let jwks = parse_static_key_set(document.expose_secret())?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -1155,6 +1167,46 @@ pub(crate) mod tests { ); } + const PUBLIC_KEY: &str = r#"{"kty":"EC","crv":"P-256","kid":"k1","alg":"ES256","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}"#; + + fn key_set(extra: &str) -> String { + let key = if extra.is_empty() { + PUBLIC_KEY.to_owned() + } else { + PUBLIC_KEY.replacen('}', &format!(",{extra}}}"), 1) + }; + format!(r#"{{"keys":[{key}]}}"#) + } + + #[test] + fn a_static_key_set_with_unknown_public_members_loads() { + let document = key_set(r#""ext":true,"x5t":"abc","x5c":["AAAA"]"#); + let jwks = parse_static_key_set(document.as_bytes()).expect("unknown public members load"); + assert_eq!(jwks.keys.len(), 1); + } + + #[test] + fn a_static_key_set_that_holds_a_private_member_is_refused_by_rule_and_not_by_value() { + let secret = "private-canary-value"; + let document = key_set(&format!(r#""d":"{secret}""#)); + let RuntimeConfigError::OidcJwksSecret(message) = + parse_static_key_set(document.as_bytes()).expect_err("a private member is refused") + else { + panic!("a refused key set is not an issuer outage"); + }; + assert!(message.contains(r#"private-key member "d""#), "{message}"); + assert!(message.contains("authentication.oidc.jwksSource.documentRef")); + assert!(!message.contains(secret), "{message}"); + } + + #[test] + fn a_static_key_set_that_is_not_json_is_not_an_issuer_outage() { + assert!(matches!( + parse_static_key_set(b"not json"), + Err(RuntimeConfigError::OidcJwksSecret(_)) + )); + } + #[test] fn the_starter_runtime_document_is_accepted() { let config = parse(STARTER_RUNTIME).expect("the starter runtime document"); diff --git a/crates/registry-documents/src/http.rs b/crates/registry-documents/src/http.rs index a53d002877..27cdc5b94e 100644 --- a/crates/registry-documents/src/http.rs +++ b/crates/registry-documents/src/http.rs @@ -26,7 +26,9 @@ use registry_documents_core::{ type_uri, Caller, IssueGrantRequest, ProblemCode, ReserveDocumentRequest, HEALTH_PATH, READY_PATH, }; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, BearerParseError, FailedCheck, RefusalNote, +}; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, FrameworkRejection, ProblemBody, TraceContext, @@ -39,7 +41,7 @@ use uuid::Uuid; use crate::audit::DocumentsAudit; use crate::auth::{AuthenticationError, DocumentsAuthenticator}; use crate::metrics::{serve_metrics, MetricsState, METRICS_PATH}; -use crate::service::{DocumentService, PageRequest}; +use crate::service::{DocumentService, PageRequest, ServiceError}; use crate::store::PostgresStore; tokio::task_local! { @@ -251,31 +253,47 @@ impl DocumentRoutes { /// The verified caller, before anything else of the request is read. /// A missing or refused credential is `authentication.refused`; a token /// that resolves to no access profile is `profile.not-authorized`. - async fn caller(&self, headers: &HeaderMap) -> Result { - let token = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .and_then(|value| parse_bearer_token(value).ok()) - .ok_or(ProblemCode::AuthenticationRefused)?; + async fn caller(&self, headers: &HeaderMap) -> Result { + let token = bearer_token(headers)?; let caller = self .authenticator .authenticate(token) .await - .map_err(|error| match error { - AuthenticationError::Refused | AuthenticationError::Claims => { - ProblemCode::AuthenticationRefused - } - AuthenticationError::Profile => ProblemCode::ProfileNotAuthorized, - AuthenticationError::Unavailable => { - tracing::warn!("the token verifier could not answer; the request was refused"); - ProblemCode::ServiceUnavailable - } - })?; + .map_err(authentication_refusal)?; self.service.admit().await?; Ok(caller) } } +/// The bearer token of the request, or the refusal that names what is wrong +/// with its credential: none, another scheme, or a header that is not a +/// well-formed bearer credential. +fn bearer_token(headers: &HeaderMap) -> Result<&str, ServiceError> { + let credential = |check| ServiceError::unauthenticated(check); + let value = headers + .get(AUTHORIZATION) + .ok_or_else(|| credential(FailedCheck::CredentialMissing))? + .to_str() + .map_err(|_| credential(FailedCheck::CredentialMalformed))?; + parse_bearer_token(value).map_err(|error| match error { + BearerParseError::InvalidScheme => credential(FailedCheck::CredentialMissing), + _ => credential(FailedCheck::CredentialMalformed), + }) +} + +/// How authentication's refusal answers: a credential or claims refusal is +/// `authentication.refused`, a profile refusal is `profile.not-authorized`, +/// and a verifier that cannot answer is `service.unavailable`. +fn authentication_refusal(error: AuthenticationError) -> ServiceError { + match error { + AuthenticationError::Refused(check) | AuthenticationError::Claims(check) => { + ServiceError::unauthenticated(check) + } + AuthenticationError::Profile(check) => ServiceError::not_authorized(check), + AuthenticationError::Unavailable => ServiceError::KeySourceUnavailable, + } +} + /// The served surface: `/health`, `/ready`, and the document routes. pub fn router(routes: DocumentRoutes) -> Router { let probes = Router::new() @@ -298,12 +316,33 @@ pub fn router(routes: DocumentRoutes) -> Router { finish(limited, unlimited) } -fn identifier(text: &str) -> Result { - Uuid::parse_str(text).map_err(|_| ProblemCode::ResourceNotFound) +/// An id in a path. One that is not an id names nothing, and the answer +/// does not say whether anything exists. +fn identifier(text: &str) -> Result { + Uuid::parse_str(text).map_err(|_| ServiceError::concealed(FailedCheck::Visibility)) } -fn answer(result: Result) -> Response { - result.unwrap_or_else(problem_response) +fn answer(result: Result) -> Response { + result.unwrap_or_else(refusal_response) +} + +/// The remedy the log line of a scope refusal carries. +const SCOPE_REMEDY: &str = "issue the access profile's required scope to the client, or set authentication.oidc.scopeClaim to the claim the issuer emits"; + +/// Render the answer to a failed operation. A refusal of authority puts its +/// check in the response's extensions, which are never serialized, for the +/// layer that records it; the bytes of the answer are those of its problem. +pub(crate) fn refusal_response(error: ServiceError) -> Response { + let mut response = problem_response(error.problem()); + if let Some(check) = error.failed_check() { + let note = RefusalNote::new(check); + let note = match check { + FailedCheck::Scope => note.with_remedy(SCOPE_REMEDY), + _ => note, + }; + response.extensions_mut().insert(note); + } + response } /// The idempotency key a creating request carries: present, bounded, and @@ -755,6 +794,86 @@ mod tests { assert!(response.headers().get(WWW_AUTHENTICATE).is_none()); } + fn authorization(value: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, value.parse().unwrap()); + headers + } + + #[test] + fn a_credential_refusal_names_what_is_wrong_with_the_credential() { + let check = |headers: &HeaderMap| bearer_token(headers).unwrap_err().failed_check(); + assert_eq!( + check(&HeaderMap::new()), + Some(FailedCheck::CredentialMissing) + ); + assert_eq!( + check(&authorization("Basic dXNlcjpwYXNz")), + Some(FailedCheck::CredentialMissing) + ); + for malformed in ["Bearer", "Bearer token", "Bearer a b"] { + assert_eq!( + check(&authorization(malformed)), + Some(FailedCheck::CredentialMalformed), + "{malformed}" + ); + } + let mut unreadable = HeaderMap::new(); + unreadable.insert(AUTHORIZATION, b"Bearer \xff".as_slice().try_into().unwrap()); + assert_eq!(check(&unreadable), Some(FailedCheck::CredentialMalformed)); + assert_eq!(bearer_token(&authorization("bearer abc")), Ok("abc")); + } + + #[test] + fn a_refusal_answers_the_bytes_of_its_problem_and_carries_its_note_apart() { + for (error, problem) in [ + ( + ServiceError::concealed(FailedCheck::Visibility), + ProblemCode::ResourceNotFound, + ), + ( + ServiceError::not_authorized(FailedCheck::Scope), + ProblemCode::ProfileNotAuthorized, + ), + ( + ServiceError::unauthenticated(FailedCheck::TokenSignature), + ProblemCode::AuthenticationRefused, + ), + ( + ServiceError::KeySourceUnavailable, + ProblemCode::ServiceUnavailable, + ), + ] { + let response = refusal_response(error); + let plain = problem_response(problem); + assert_eq!(response.status(), plain.status()); + // Each answer is under its own server-created trace. + for (name, value) in plain.headers() { + if name != "traceparent" && name != "tracestate" { + assert_eq!(response.headers().get(name), Some(value), "{name}"); + } + } + let note = response.extensions().get::().unwrap(); + assert_eq!(Some(note.check), error.failed_check()); + assert_eq!( + note.remedy.is_some(), + note.check == FailedCheck::Scope, + "only a scope refusal carries a remedy" + ); + } + let plain = refusal_response(ServiceError::Problem(ProblemCode::RequestInvalid)); + assert!(plain.extensions().get::().is_none()); + } + + #[test] + fn a_path_id_that_is_not_an_id_names_nothing() { + assert_eq!( + identifier("not-a-uuid"), + Err(ServiceError::concealed(FailedCheck::Visibility)) + ); + assert!(identifier(&Uuid::nil().to_string()).is_ok()); + } + #[test] fn the_idempotency_key_is_present_bounded_and_graphical() { let with = |value: &str| { diff --git a/crates/registry-documents/src/metrics.rs b/crates/registry-documents/src/metrics.rs index 1fee8e7dfe..e011eff2d9 100644 --- a/crates/registry-documents/src/metrics.rs +++ b/crates/registry-documents/src/metrics.rs @@ -39,6 +39,7 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{Method, Request, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; +use registry_platform_authcommon::{record_refusal, RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ sample_error_class, CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CLASS_NO_TIME_LEFT, CLASS_POOL, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -154,6 +155,9 @@ pub struct QueueDepth { pub struct Metrics { requests: CounterVec, sample_failures: CounterVec, + /// Counts and logs each refusal by the check it failed; its counter is + /// `documents_request_refusals_total`. + refusals: RefusalRecorder, started: Instant, /// Seconds after `started` at which each worker last completed a pass. last_success: [AtomicU64; 1], @@ -183,6 +187,7 @@ impl Default for Metrics { LabelSpace::closed_zero_filled(&["sample"], &samples).expect(DECLARATION), ) .expect(DECLARATION), + refusals: RefusalRecorder::new("documents").expect(DECLARATION), started: Instant::now(), last_success: [AtomicU64::new(0)], } @@ -206,6 +211,12 @@ impl Metrics { ); } + /// Count one refusal under the check it failed and write the log line + /// the recorder admits. + pub fn record_refusal(&self, note: RefusalNote) { + record_refusal!(self.refusals, note); + } + /// Record that `worker` just completed a pass. pub fn record_worker_success(&self, worker: Worker) { self.record_worker_success_at(worker, self.started.elapsed().as_secs()); @@ -231,6 +242,7 @@ impl Metrics { let mut out = Exposition::new(); self.requests.write(&mut out).expect(DECLARATION); self.sample_failures.write(&mut out).expect(DECLARATION); + self.refusals.counter().write(&mut out).expect(DECLARATION); write_queue( &mut out, "documents_verification_jobs", @@ -347,7 +359,9 @@ fn status_class(status: StatusCode) -> &'static str { } /// Count every answered request on the serving listener under the route -/// template it matched. +/// template it matched, and every refusal under the check it failed. The +/// refusal rides the response's extensions, which are never serialized, so +/// recording it cannot change a byte of the answer. pub async fn count_requests( State(metrics): State>, request: Request, @@ -361,6 +375,9 @@ pub async fn count_requests( let method = request.method().clone(); let response = next.run(request).await; metrics.record_request(&route, &method, response.status()); + if let Some(note) = response.extensions().get::() { + metrics.record_refusal(*note); + } response } @@ -516,6 +533,7 @@ pub async fn serve_metrics(State(state): State) -> Response { #[cfg(test)] mod tests { use super::*; + use registry_platform_authcommon::FailedCheck; fn depth(by_state: &[(&str, i64)], oldest: i64) -> QueueDepth { QueueDepth { @@ -549,6 +567,29 @@ mod tests { )); } + #[test] + fn the_refusal_counter_lists_every_check_from_zero_and_counts_by_check() { + let metrics = Metrics::default(); + let text = metrics.render(&Sampled::default()); + for check in FailedCheck::ALL { + assert!( + text.contains(&format!( + "documents_request_refusals_total{{check=\"{}\"}} 0", + check.as_str() + )), + "{}", + check.as_str() + ); + } + metrics.record_refusal(RefusalNote::new(FailedCheck::Scope)); + metrics.record_refusal(RefusalNote::new(FailedCheck::Scope)); + metrics.record_refusal(RefusalNote::new(FailedCheck::Visibility)); + let text = metrics.render(&Sampled::default()); + assert!(text.contains("documents_request_refusals_total{check=\"scope\"} 2")); + assert!(text.contains("documents_request_refusals_total{check=\"visibility\"} 1")); + assert!(text.contains("documents_request_refusals_total{check=\"ownership\"} 0")); + } + #[test] fn every_status_has_its_own_bounded_class() { let class = |code: u16| status_class(StatusCode::from_u16(code).unwrap()); diff --git a/crates/registry-documents/src/service.rs b/crates/registry-documents/src/service.rs index 921abefd85..a406aa0e11 100644 --- a/crates/registry-documents/src/service.rs +++ b/crates/registry-documents/src/service.rs @@ -29,6 +29,7 @@ use registry_documents_core::{ ReservationView, ReserveDocumentRequest, Reserver, Standing, UploadState, VerificationState, MAXIMUM_PAGE_SIZE, UPLOAD_CONTENT_PATH, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_canonical_json::canonicalize_json; use registry_platform_dispatch::postgres::{enqueue, JobKey, JobTable}; use registry_platform_objectstore::ObjectStoreError; @@ -218,10 +219,176 @@ fn checked(parsed: Option) -> String { parsed.map_or_else(|| UNPARSED.to_owned(), |value| value.to_string()) } +/// The problem codes that refuse a caller's authority, or conceal a target +/// the caller may not see. A refusal is built with the check it failed +/// ([`ServiceError::Refused`]), never from the bare code, so the operator's +/// counter and log line can name the check. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RefusalCode { + AuthenticationRefused, + CustodyNotPermitted, + ProfileNotAuthorized, + ResourceNotFound, +} + +impl RefusalCode { + /// The problem this refusal answers with. + #[must_use] + pub const fn problem(self) -> ProblemCode { + match self { + Self::AuthenticationRefused => ProblemCode::AuthenticationRefused, + Self::CustodyNotPermitted => ProblemCode::CustodyNotPermitted, + Self::ProfileNotAuthorized => ProblemCode::ProfileNotAuthorized, + Self::ResourceNotFound => ProblemCode::ResourceNotFound, + } + } + + /// Sort a problem into a refusal or a plain answer. The match names every + /// code, so a code added to the vocabulary does not compile until it + /// declares which side it is on. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn of(problem: ProblemCode) -> Option { + match problem { + ProblemCode::AuthenticationRefused => Some(Self::AuthenticationRefused), + ProblemCode::CustodyNotPermitted => Some(Self::CustodyNotPermitted), + ProblemCode::ProfileNotAuthorized => Some(Self::ProfileNotAuthorized), + ProblemCode::ResourceNotFound => Some(Self::ResourceNotFound), + ProblemCode::CustodyQuotaExceeded + | ProblemCode::DocumentGrantExpiryOutOfRange + | ProblemCode::DocumentPolicyUnknown + | ProblemCode::DocumentVersionNotReleasable + | ProblemCode::DocumentContentTypeNotAllowed + | ProblemCode::DocumentTooLarge + | ProblemCode::IdempotencyExpired + | ProblemCode::IdempotencyKeyReused + | ProblemCode::RequestBodyTooLarge + | ProblemCode::RequestInvalid + | ProblemCode::RequestMethodNotAllowed + | ProblemCode::RequestNotFound + | ProblemCode::RequestUnprocessable + | ProblemCode::RequestUnsupportedMediaType + | ProblemCode::ServiceUnavailable + | ProblemCode::UploadContentTypeMismatch + | ProblemCode::UploadDigestMismatch + | ProblemCode::UploadExpired + | ProblemCode::UploadFinalized + | ProblemCode::UploadLengthMismatch => None, + } + } +} + +/// Why an operation answered a problem. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ServiceError { + /// A problem that is not a refusal of authority: validation, a conflict, + /// an idempotency answer, or an outage. A code for which + /// [`RefusalCode::of`] answers `Some` is built as `Refused`. + Problem(ProblemCode), + /// A refusal of authority, with the check it failed. + Refused { + code: RefusalCode, + check: FailedCheck, + }, + /// The verifier could not reach or use its key source. The caller is + /// answered `service.unavailable`, and the operator's record names the + /// check. + KeySourceUnavailable, +} + +impl ServiceError { + /// A refusal that conceals a target the caller may not see: the row is + /// absent or foreign, and the answer does not say which. + #[must_use] + pub const fn concealed(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::ResourceNotFound, + check, + } + } + + /// A refusal of a caller that sees the target but may not act on it. + #[must_use] + pub const fn not_authorized(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::ProfileNotAuthorized, + check, + } + } + + /// A refusal to place a document in custody. + #[must_use] + pub const fn custody(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::CustodyNotPermitted, + check, + } + } + + /// A refusal of a credential or of the identity claims it carries. + #[must_use] + pub const fn unauthenticated(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::AuthenticationRefused, + check, + } + } + + /// The problem the caller is answered with. + #[must_use] + pub const fn problem(&self) -> ProblemCode { + match self { + Self::Problem(problem) => *problem, + Self::Refused { code, .. } => code.problem(), + Self::KeySourceUnavailable => ProblemCode::ServiceUnavailable, + } + } + + /// The check this answer failed, when it is a refusal. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn failed_check(&self) -> Option { + match self { + Self::Problem(_) => None, + Self::Refused { check, .. } => Some(*check), + Self::KeySourceUnavailable => Some(FailedCheck::KeySourceUnavailable), + } + } +} + +impl From for ServiceError { + /// A problem that is not a refusal. A refusal code reaching this + /// conversion has no check to record, which is a defect in the caller: + /// it is logged and answered `service.unavailable`, never as a refusal + /// the operator cannot account for. + fn from(problem: ProblemCode) -> Self { + match RefusalCode::of(problem) { + None => Self::Problem(problem), + Some(_) => { + tracing::error!( + code = problem.code(), + "a refusal was built without the check it failed" + ); + Self::Problem(ProblemCode::ServiceUnavailable) + } + } + } +} + +/// The answer to a custody placement the policy refused. Every refusal of +/// [`place_custody`] is one of the caller's profile or request naming custody +/// it may not place, so the check is the operation. +fn custody_refusal(problem: ProblemCode) -> ServiceError { + match RefusalCode::of(problem) { + Some(RefusalCode::CustodyNotPermitted) => ServiceError::custody(FailedCheck::Operation), + Some(_) | None => problem.into(), + } +} + /// Log a failure the caller is answered `service.unavailable` for. -fn unavailable(stage: &'static str, error: &dyn std::fmt::Display) -> ProblemCode { +fn unavailable(stage: &'static str, error: &dyn std::fmt::Display) -> ServiceError { tracing::error!(stage, error = %error, "a document operation failed"); - ProblemCode::ServiceUnavailable + ServiceError::Problem(ProblemCode::ServiceUnavailable) } fn timestamp(value: DateTime) -> String { @@ -455,7 +622,7 @@ fn key_digest(caller: &Caller, operation: &str, key: &str) -> String { } /// The digest of a request body in canonical JSON. -fn request_digest(body: &impl serde::Serialize) -> Result { +fn request_digest(body: &impl serde::Serialize) -> Result { let value = serde_json::to_value(body).map_err(|error| unavailable("request digest", &error))?; let canonical = @@ -479,7 +646,7 @@ async fn replay( transaction: &tokio_postgres::Transaction<'_>, key: &str, request: &str, -) -> Result { +) -> Result { transaction .execute( "SELECT pg_advisory_xact_lock(hashtextextended($1, 1))", @@ -503,10 +670,10 @@ async fn replay( let resource: Uuid = row.try_get(1).map_err(read)?; let expired: bool = row.try_get(2).map_err(read)?; if expired { - return Err(ProblemCode::IdempotencyExpired); + return Err(ProblemCode::IdempotencyExpired.into()); } if recorded != request { - return Err(ProblemCode::IdempotencyKeyReused); + return Err(ProblemCode::IdempotencyKeyReused.into()); } Ok(Replay::Repeat(resource)) } @@ -520,7 +687,7 @@ async fn record_key( request: &str, resource: Uuid, days: i32, -) -> Result<(), ProblemCode> { +) -> Result<(), ServiceError> { transaction .execute( "INSERT INTO documents_idempotency @@ -600,7 +767,7 @@ impl DocumentService { &self.settings.budget } - fn actor_reference(&self, caller: &Caller) -> Result { + fn actor_reference(&self, caller: &Caller) -> Result { self.audit .actor_reference(&caller.issuer, &caller.subject, caller.kind) .map_err(|error| unavailable("audit actor reference", &error)) @@ -610,7 +777,7 @@ impl DocumentService { &self, event: &'static str, record: Value, - ) -> Result { + ) -> Result { self.audit .begin(event, record) .await @@ -620,15 +787,15 @@ impl DocumentService { async fn finish( audit: registry_platform_audit::AuditRequest, event: &'static str, - result: &Result, + result: &Result, success: Value, - ) -> Result<(), ProblemCode> { + ) -> Result<(), ServiceError> { let record = match result { Ok(_) => success, Err(problem) => json!({ "event": event, "outcome": "refused", - "code": problem.code(), + "code": problem.problem().code(), }), }; audit @@ -655,7 +822,7 @@ impl DocumentService { policy } - async fn client(&self) -> Result { + async fn client(&self) -> Result { self.store .client() .await @@ -664,7 +831,7 @@ impl DocumentService { /// A protected request is admitted only while this runtime's package /// remains active. Mutations additionally fence their own transaction. - pub(crate) async fn admit(&self) -> Result<(), ProblemCode> { + pub(crate) async fn admit(&self) -> Result<(), ServiceError> { self.store .admit() .await @@ -674,7 +841,7 @@ impl DocumentService { async fn record_in( client: &C, document_id: Uuid, - ) -> Result, ProblemCode> { + ) -> Result, ServiceError> { client .query_opt( &format!( @@ -690,14 +857,14 @@ impl DocumentService { .transpose() } - async fn record(&self, document_id: Uuid) -> Result, ProblemCode> { + async fn record(&self, document_id: Uuid) -> Result, ServiceError> { let client = self.client().await?; Self::record_in(&**client, document_id).await } /// Whether `caller`, by issuer, subject, and actor kind, holds an /// active grant on `version_id`. - async fn holds_grant(&self, caller: &Caller, version_id: Uuid) -> Result { + async fn holds_grant(&self, caller: &Caller, version_id: Uuid) -> Result { let client = self.client().await?; let row = client .query_one( @@ -719,7 +886,7 @@ impl DocumentService { } /// Decide what `caller` is to `record`. - async fn access(&self, caller: &Caller, record: &Record) -> Result { + async fn access(&self, caller: &Caller, record: &Record) -> Result { let Some(policy) = self.policy(&record.policy_id) else { return Ok(Access::default()); }; @@ -739,7 +906,7 @@ impl DocumentService { /// The view `access` shows of `record`. A version approved under /// another verifier binding, or whose approval names other content, is /// shown `suspended`: it is not releasable now. - fn present(&self, record: &Record, access: Access) -> Result { + fn present(&self, record: &Record, access: Access) -> Result { let mut status = record.status; if status.is_releasable() && record @@ -792,7 +959,7 @@ impl DocumentService { caller: &Caller, key: &str, request: &ReserveDocumentRequest, - ) -> Result { + ) -> Result { let reference = self.actor_reference(caller)?; let audit = self .begin( @@ -826,7 +993,7 @@ impl DocumentService { caller: &Caller, key: &str, request: &ReserveDocumentRequest, - ) -> Result { + ) -> Result { let admitted = admit_reservation( &self.project, ReservationAsk { @@ -842,7 +1009,8 @@ impl DocumentService { subject: request.custodian.subject.as_str(), issuing_institution: request.issuing_institution.as_ref().map(ExternalId::as_str), }, - )?; + ) + .map_err(custody_refusal)?; let binding = admitted .policy .binding(admitted.policy_id) @@ -991,7 +1159,7 @@ impl DocumentService { &self, caller: &Caller, record: &Record, - ) -> Result { + ) -> Result { let access = self.access(caller, record).await?; Ok(ReservationView { document: self.present(record, access)?, @@ -1014,7 +1182,7 @@ impl DocumentService { content_type: Option<&str>, content_length: Option, body: S, - ) -> Result + ) -> Result where S: Stream> + Unpin, { @@ -1062,7 +1230,7 @@ impl DocumentService { &self, caller: &Caller, upload_id: Uuid, - ) -> Result { + ) -> Result { let client = self.client().await?; let row = client .query_opt( @@ -1071,14 +1239,14 @@ impl DocumentService { ) .await .map_err(|error| unavailable("reservation read", &error))? - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let record = Record::from_row(&row).map_err(|error| unavailable("reservation decode", &error))?; if record.reserver_issuer != caller.issuer || record.reserver_subject != caller.subject || record.reserver_kind != caller.kind { - return Err(ProblemCode::ResourceNotFound); + return Err(ServiceError::concealed(FailedCheck::Visibility)); } Ok(Reservation { record }) } @@ -1090,7 +1258,7 @@ impl DocumentService { content_type: Option<&str>, content_length: Option, body: S, - ) -> Result + ) -> Result where S: Stream> + Unpin, { @@ -1103,31 +1271,33 @@ impl DocumentService { || record.upload_lapsed || record.status.is_erasing()) { - return Err(ProblemCode::UploadExpired); + return Err(ProblemCode::UploadExpired.into()); } if content_type != Some(record.media_type.as_str()) { return Err(if finalized { ProblemCode::UploadFinalized } else { ProblemCode::UploadContentTypeMismatch - }); + } + .into()); } match content_length { Some(length) if length > self.settings.ceiling => { - return Err(ProblemCode::RequestBodyTooLarge) + return Err(ProblemCode::RequestBodyTooLarge.into()) } Some(length) if length != record.length => { return Err(if finalized { ProblemCode::UploadFinalized } else { ProblemCode::UploadLengthMismatch - }) + } + .into()) } _ => {} } let Some(_permit) = self.settings.budget.try_reserve(record.length) else { tracing::warn!("the transfer budget is spent; the upload was refused"); - return Err(ProblemCode::ServiceUnavailable); + return Err(ProblemCode::ServiceUnavailable.into()); }; let deadline = self.settings.deadline.for_length(record.length); let body = match tokio::time::timeout(deadline, read_hashing(body, record.length)).await { @@ -1137,12 +1307,13 @@ impl DocumentService { ProblemCode::UploadFinalized } else { ProblemCode::UploadLengthMismatch - }) + } + .into()) } - Ok(Err(BodyRefusal::Unreadable)) => return Err(ProblemCode::RequestInvalid), + Ok(Err(BodyRefusal::Unreadable)) => return Err(ProblemCode::RequestInvalid.into()), Err(_) => { tracing::warn!("an upload body did not arrive within its transfer deadline"); - return Err(ProblemCode::ServiceUnavailable); + return Err(ProblemCode::ServiceUnavailable.into()); } }; let digest = body.digest(); @@ -1152,11 +1323,11 @@ impl DocumentService { self.current_view(caller, record.document_id).await?, )) } else { - Err(ProblemCode::UploadFinalized) + Err(ProblemCode::UploadFinalized.into()) }; } if digest != record.expected_digest { - return Err(ProblemCode::UploadDigestMismatch); + return Err(ProblemCode::UploadDigestMismatch.into()); } let sha256 = body.sha256_hex; let stored = match self.storage.as_ref() { @@ -1178,7 +1349,7 @@ impl DocumentService { &self, caller: &Caller, document_id: Uuid, - ) -> Result { + ) -> Result { let record = self .record(document_id) .await? @@ -1196,7 +1367,7 @@ impl DocumentService { record: &Record, sha256: &str, bytes: Vec, - ) -> Result { + ) -> Result { let object_id = Uuid::new_v4(); let store = self .storage @@ -1275,7 +1446,7 @@ impl DocumentService { record: &Record, digest: &str, stored: Stored, - ) -> Result { + ) -> Result { let version_id = record.version_id; let mut client = self.client().await?; let transaction = client @@ -1302,9 +1473,9 @@ impl DocumentService { let erasing: bool = row.try_get(3).map_err(read)?; match state.as_str() { "finalized" if computed.as_deref() == Some(digest) => return Ok(false), - "finalized" => return Err(ProblemCode::UploadFinalized), - "expired" => return Err(ProblemCode::UploadExpired), - _ if lapsed || erasing => return Err(ProblemCode::UploadExpired), + "finalized" => return Err(ProblemCode::UploadFinalized.into()), + "expired" => return Err(ProblemCode::UploadExpired.into()), + _ if lapsed || erasing => return Err(ProblemCode::UploadExpired.into()), _ => {} } if !pin_storage(&*transaction, &self.storage) @@ -1386,14 +1557,14 @@ impl DocumentService { &self, caller: &Caller, document_id: Uuid, - ) -> Result { + ) -> Result { let record = self .record(document_id) .await? - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let access = self.access(caller, &record).await?; if !access.sees() { - return Err(ProblemCode::ResourceNotFound); + return Err(ServiceError::concealed(FailedCheck::Visibility)); } self.present(&record, access) } @@ -1403,7 +1574,7 @@ impl DocumentService { &self, caller: &Caller, page: &PageRequest, - ) -> Result { + ) -> Result { let (after, after_id) = Cursor::bounds(page.cursor); let rows = { let client = self.client().await?; @@ -1464,7 +1635,7 @@ impl DocumentService { caller: &Caller, document_id: Uuid, version_id: Uuid, - ) -> Result { + ) -> Result { let started = Instant::now(); let reference = self.actor_reference(caller)?; let audit = self @@ -1502,7 +1673,7 @@ impl DocumentService { json!({ "event": CONTENT_DOWNLOAD_EVENT, "outcome": "refused", - "code": problem.code(), + "code": problem.problem().code(), }), Err(problem), ), @@ -1512,7 +1683,7 @@ impl DocumentService { "outcome": "storage-integrity", "byteCount": 0, }), - Err(ProblemCode::ServiceUnavailable), + Err(ProblemCode::ServiceUnavailable.into()), ), Err(Release::Unavailable) => ( json!({ @@ -1520,7 +1691,7 @@ impl DocumentService { "outcome": "storage-unavailable", "byteCount": 0, }), - Err(ProblemCode::ServiceUnavailable), + Err(ProblemCode::ServiceUnavailable.into()), ), }; audit @@ -1545,7 +1716,7 @@ impl DocumentService { .record(document_id) .await? .filter(|record| record.version_id == version_id) - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let access = self.access(caller, &record).await?; let digest = self.releasable(&record, access)?; let Some(permit) = self.settings.budget.try_reserve(record.length) else { @@ -1570,13 +1741,17 @@ impl DocumentService { /// The digest `access` may be released of `record`, or the answer to a /// caller that may not have its content. - fn releasable<'a>(&self, record: &'a Record, access: Access) -> Result<&'a str, ProblemCode> { + fn releasable<'a>(&self, record: &'a Record, access: Access) -> Result<&'a str, ServiceError> { match record.releasable_digest(&self.settings.verifier_binding) { Some(digest) if access.standing.custodian || access.released_by_grant => Ok(digest), - None if access.standing.custodian => Err(ProblemCode::DocumentVersionNotReleasable), + None if access.standing.custodian => { + Err(ProblemCode::DocumentVersionNotReleasable.into()) + } // The owning system sees the document but is never released it. - _ if access.standing.sees() => Err(ProblemCode::ProfileNotAuthorized), - _ => Err(ProblemCode::ResourceNotFound), + _ if access.standing.sees() => { + Err(ServiceError::not_authorized(FailedCheck::Ownership)) + } + _ => Err(ServiceError::concealed(FailedCheck::Visibility)), } } @@ -1633,16 +1808,22 @@ fn integrity(version: Uuid, error: &StorageError) -> Release { /// Why a release did not happen. enum Release { - Refused(ProblemCode), + Refused(ServiceError), /// The stored content failed its integrity check. Integrity, /// The content storage could not be read. Unavailable, } +impl From for Release { + fn from(error: ServiceError) -> Self { + Self::Refused(error) + } +} + impl From for Release { fn from(problem: ProblemCode) -> Self { - Self::Refused(problem) + Self::Refused(problem.into()) } } @@ -1650,6 +1831,92 @@ impl From for Release { mod tests { use super::*; + #[test] + fn every_problem_is_sorted_into_a_refusal_or_a_plain_answer() { + let refusals: Vec = ProblemCode::ALL + .iter() + .copied() + .filter(|problem| RefusalCode::of(*problem).is_some()) + .collect(); + assert_eq!( + refusals, + [ + ProblemCode::AuthenticationRefused, + ProblemCode::CustodyNotPermitted, + ProblemCode::ProfileNotAuthorized, + ProblemCode::ResourceNotFound, + ] + ); + for problem in ProblemCode::ALL { + if let Some(code) = RefusalCode::of(*problem) { + assert_eq!(code.problem(), *problem); + } + } + } + + #[test] + fn a_plain_problem_converts_and_a_bare_refusal_code_does_not_become_a_refusal() { + for problem in ProblemCode::ALL { + let error = ServiceError::from(*problem); + match RefusalCode::of(*problem) { + None => assert_eq!(error, ServiceError::Problem(*problem)), + Some(_) => assert_eq!( + error, + ServiceError::Problem(ProblemCode::ServiceUnavailable), + "{problem:?}" + ), + } + assert_eq!(error.failed_check(), None); + } + } + + #[test] + fn a_refusal_answers_its_code_and_names_its_check() { + let cases = [ + ( + ServiceError::unauthenticated(FailedCheck::TokenClaims), + ProblemCode::AuthenticationRefused, + FailedCheck::TokenClaims, + ), + ( + ServiceError::not_authorized(FailedCheck::Ownership), + ProblemCode::ProfileNotAuthorized, + FailedCheck::Ownership, + ), + ( + ServiceError::custody(FailedCheck::Operation), + ProblemCode::CustodyNotPermitted, + FailedCheck::Operation, + ), + ( + ServiceError::concealed(FailedCheck::Visibility), + ProblemCode::ResourceNotFound, + FailedCheck::Visibility, + ), + ( + ServiceError::KeySourceUnavailable, + ProblemCode::ServiceUnavailable, + FailedCheck::KeySourceUnavailable, + ), + ]; + for (error, problem, check) in cases { + assert_eq!(error.problem(), problem); + assert_eq!(error.failed_check(), Some(check)); + } + } + + #[test] + fn a_custody_refusal_names_the_operation() { + assert_eq!( + custody_refusal(ProblemCode::CustodyNotPermitted), + ServiceError::custody(FailedCheck::Operation) + ); + assert_eq!( + custody_refusal(ProblemCode::DocumentPolicyUnknown), + ServiceError::Problem(ProblemCode::DocumentPolicyUnknown) + ); + } + #[test] fn the_upload_path_names_the_upload() { let id = Uuid::nil(); diff --git a/crates/registry-documents/src/service/erasure.rs b/crates/registry-documents/src/service/erasure.rs index aff8421e6e..2daedf5935 100644 --- a/crates/registry-documents/src/service/erasure.rs +++ b/crates/registry-documents/src/service/erasure.rs @@ -12,11 +12,12 @@ //! the version is due. No grant expiry or revocation ever starts this clock. use registry_documents_core::{may_request_erasure, Caller, DocumentView, ProblemCode}; +use registry_platform_authcommon::FailedCheck; use serde_json::{json, Value}; use tokio_postgres::Transaction; use uuid::Uuid; -use super::{timestamp, unavailable, DocumentService}; +use super::{timestamp, unavailable, DocumentService, ServiceError}; use crate::audit::ERASURE_REQUEST_EVENT; use crate::hooks::GrantChange; @@ -38,7 +39,7 @@ impl DocumentService { &self, caller: &Caller, document_id: Uuid, - ) -> Result { + ) -> Result { let reference = self.actor_reference(caller)?; let audit = self .begin( @@ -71,22 +72,22 @@ impl DocumentService { &self, caller: &Caller, document_id: Uuid, - ) -> Result { + ) -> Result { let record = self .record(document_id) .await? - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let access = self.access(caller, &record).await?; if !access.sees() { - return Err(ProblemCode::ResourceNotFound); + return Err(ServiceError::concealed(FailedCheck::Visibility)); } if !may_request_erasure(access.standing) { - return Err(ProblemCode::ProfileNotAuthorized); + return Err(ServiceError::not_authorized(FailedCheck::Ownership)); } // A custodian sees the document only under a declared policy. let policy = self .policy(&record.policy_id) - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let grace = i32::try_from(policy.mandatory_restrictions.cleanup_grace_hours.get()) .map_err(|error| unavailable("erasure grace", &error))?; let version_id = record.version_id; @@ -193,7 +194,7 @@ impl DocumentService { pub(super) async fn refuse_erasing( transaction: &Transaction<'_>, version_id: Uuid, - ) -> Result<(), ProblemCode> { + ) -> Result<(), ServiceError> { let erasing: bool = transaction .query_one( "SELECT erasure_state <> 'none' FROM documents_versions @@ -204,7 +205,7 @@ impl DocumentService { .and_then(|row| row.try_get(0)) .map_err(|error| unavailable("grant erasure check", &error))?; if erasing { - return Err(ProblemCode::DocumentVersionNotReleasable); + return Err(ProblemCode::DocumentVersionNotReleasable.into()); } Ok(()) } diff --git a/crates/registry-documents/src/service/grants.rs b/crates/registry-documents/src/service/grants.rs index 5bd8d55609..44b4f2d221 100644 --- a/crates/registry-documents/src/service/grants.rs +++ b/crates/registry-documents/src/service/grants.rs @@ -17,6 +17,7 @@ use registry_documents_core::{ grant_expiry_hours, ActorKind, Caller, DocumentGrantPage, DocumentGrantView, GrantState, GranteeRef, IssueGrantRequest, ProblemCode, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_yaml::ExternalId; use serde_json::{json, Value}; use tokio_postgres::Row; @@ -24,7 +25,7 @@ use uuid::Uuid; use super::{ checked, key_digest, next_cursor, record_key, replay, request_digest, timestamp, unavailable, - Cursor, DocumentService, PageRequest, Record, Replay, + Cursor, DocumentService, PageRequest, Record, Replay, ServiceError, }; use crate::audit::{GRANT_ISSUE_EVENT, GRANT_REVOKE_EVENT}; use crate::hooks::{DocumentEvent, GrantChange}; @@ -101,14 +102,14 @@ impl Grant { } } -fn decode_grants(rows: &[Row]) -> Result, ProblemCode> { +fn decode_grants(rows: &[Row]) -> Result, ServiceError> { rows.iter() .map(Grant::from_row) .collect::, _>>() .map_err(|error| unavailable("grant decode", &error)) } -fn grant_views(grants: &[Grant], limit: u32) -> Result, ProblemCode> { +fn grant_views(grants: &[Grant], limit: u32) -> Result, ServiceError> { grants .iter() .take(limit as usize) @@ -132,14 +133,14 @@ impl DocumentService { caller: &Caller, document_id: Uuid, managing: bool, - ) -> Result { + ) -> Result { let record = self .record(document_id) .await? - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let access = self.access(caller, &record).await?; if !access.sees() { - return Err(ProblemCode::ResourceNotFound); + return Err(ServiceError::concealed(FailedCheck::Visibility)); } let allowed = if managing { access.standing.may_grant @@ -147,7 +148,7 @@ impl DocumentService { access.standing.may_list_grants() }; if !allowed { - return Err(ProblemCode::ProfileNotAuthorized); + return Err(ServiceError::not_authorized(FailedCheck::Operation)); } Ok(record) } @@ -162,7 +163,7 @@ impl DocumentService { key: &str, document_id: Uuid, request: &IssueGrantRequest, - ) -> Result { + ) -> Result { let reference = self.actor_reference(caller)?; let version_id = Uuid::parse_str(&request.version_id).ok(); let audit = self @@ -200,20 +201,20 @@ impl DocumentService { document_id: Uuid, version_id: Option, request: &IssueGrantRequest, - ) -> Result { + ) -> Result { let record = self.grantable(caller, document_id, true).await?; let version_id = version_id .filter(|id| *id == record.version_id) - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; if record .releasable_digest(&self.settings.verifier_binding) .is_none() { - return Err(ProblemCode::DocumentVersionNotReleasable); + return Err(ProblemCode::DocumentVersionNotReleasable.into()); } let policy = self .policy(&record.policy_id) - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let hours = i32::try_from(grant_expiry_hours(policy, request.expiry_hours)?) .map_err(|_| ProblemCode::RequestUnprocessable)?; let days = i32::try_from(self.settings.idempotency_days) @@ -289,7 +290,7 @@ impl DocumentService { &self, caller: &Caller, grant_id: Uuid, - ) -> Result { + ) -> Result { let reference = self.actor_reference(caller)?; let audit = self .begin( @@ -319,7 +320,7 @@ impl DocumentService { &self, caller: &Caller, grant_id: Uuid, - ) -> Result { + ) -> Result { let document_id: Uuid = { let client = self.client().await?; client @@ -329,7 +330,7 @@ impl DocumentService { ) .await .map_err(|error| unavailable("grant read", &error))? - .ok_or(ProblemCode::ResourceNotFound)? + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))? .try_get(0) .map_err(|error| unavailable("grant decode", &error))? }; @@ -390,7 +391,7 @@ impl DocumentService { caller: &Caller, grant_id: Uuid, change: GrantChange, - ) -> Result<(), ProblemCode> { + ) -> Result<(), ServiceError> { let event = DocumentEvent::grant(transaction, grant_id, change, caller.kind) .await .map_err(|error| unavailable("grant event read", &error))?; @@ -407,7 +408,7 @@ impl DocumentService { caller: &Caller, document_id: Uuid, page: &PageRequest, - ) -> Result { + ) -> Result { self.grantable(caller, document_id, false).await?; let (after, after_id) = Cursor::bounds(page.cursor); let client = self.client().await?; @@ -440,7 +441,7 @@ impl DocumentService { &self, caller: &Caller, page: &PageRequest, - ) -> Result { + ) -> Result { let (after, after_id) = Cursor::bounds(page.cursor); let policies: Vec<&str> = self .project diff --git a/crates/registry-documents/tests/golden/refusals.json b/crates/registry-documents/tests/golden/refusals.json new file mode 100644 index 0000000000..aac6cbc2de --- /dev/null +++ b/crates/registry-documents/tests/golden/refusals.json @@ -0,0 +1,475 @@ +{ + "agent-actor-kind": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "another-actor-kind": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "another-scheme": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "download-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "download-by-the-reserving-system": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "empty-bearer": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "erasure-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "erasure-by-the-reserving-system": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "exchanged-token": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "expired": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "foreign-audience": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "foreign-issuer": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "forged-signature": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "grant-issued-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "grant-issued-by-the-reserving-system": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "grant-on-another-version": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "grants-listed-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "grants-listed-by-the-reserving-system": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "malformed-actor-kind": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "missing-scope": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "no-authorization-header": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "not-a-compact-token": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "principal-outside-its-grammar": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "read-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "read-of-a-malformed-id": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "read-of-an-absent-document": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "reservation-by-a-recipient-profile": { + "body": { + "code": "custody.not-permitted", + "detail": "The caller's access profile may not place a document in this custody, or the request names an issuing institution other than the profile's.", + "status": 403, + "title": "Custody not permitted", + "type": "https://id.registrystack.org/problems/registry-documents/custody/not-permitted" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "reservation-for-another-custodian-by-a-person": { + "body": { + "code": "custody.not-permitted", + "detail": "The caller's access profile may not place a document in this custody, or the request names an issuing institution other than the profile's.", + "status": 403, + "title": "Custody not permitted", + "type": "https://id.registrystack.org/problems/registry-documents/custody/not-permitted" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "reservation-outside-the-custody-profiles": { + "body": { + "code": "custody.not-permitted", + "detail": "The caller's access profile may not place a document in this custody, or the request names an issuing institution other than the profile's.", + "status": 403, + "title": "Custody not permitted", + "type": "https://id.registrystack.org/problems/registry-documents/custody/not-permitted" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "revoke-of-an-absent-grant": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "unadmitted-client": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "upload-by-another-caller": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "upload-to-an-absent-reservation": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + } +} diff --git a/crates/registry-documents/tests/refusal_golden.rs b/crates/registry-documents/tests/refusal_golden.rs new file mode 100644 index 0000000000..8bf1980383 --- /dev/null +++ b/crates/registry-documents/tests/refusal_golden.rs @@ -0,0 +1,621 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The refusals of the Document Store, driven over the served router with +//! real tokens, in two checks. +//! +//! The first freezes what a caller is answered: the status, the headers that +//! matter to a client, and the body without its trace, for every refusal of +//! authentication or authority, against `tests/golden/refusals.json`. The +//! file records the answers the runtime gave before refusals were counted by +//! the check they failed. It must not change when the recording changes. +//! +//! The second proves the operator's side of the same refusals: each one adds +//! one to `documents_request_refusals_total` under the fixed check it failed, +//! writes one `request refused` line carrying that check and nothing a caller +//! sent, and answers the same bytes as the first. +//! +//! `DOCUMENTS_UPDATE_GOLDEN=1` rewrites the golden file from the current +//! answers. The database is named by `DOCUMENTS_TEST_DATABASE_URL`. + +mod support; + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use axum::body::Body; +use axum::http::{Method, Request}; +use registry_documents::runtime::{prepare_with_verifier, Prepared}; +use registry_platform_authcommon::FailedCheck; +use serde_json::{json, Value}; +use support::{ + pdf, request, reservation, token, token_with, Answer, Api, Deployment, FakeVerifier, Principal, + APP, APPROVE, CITIZEN, DATABASE_STORAGE, DISABLED_VERIFIER, OTHER_APP, READER, STRANGER, + TEST_AUDIENCE, TEST_ISSUER, +}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber as _; +use uuid::Uuid; + +/// The headers a client reads on a refusal. +const HEADERS: [&str; 4] = [ + "content-type", + "www-authenticate", + "retry-after", + "cache-control", +]; + +/// How a fixture presents its credential. +enum Credential { + Absent, + Header(&'static str), + Token(String), +} + +/// One refusal: its name in the golden file, the check it must be recorded +/// under, and the request that trips it. +struct Fixture { + name: &'static str, + check: FailedCheck, + method: Method, + path: String, + credential: Credential, + body: Option, +} + +impl Fixture { + fn new( + name: &'static str, + check: FailedCheck, + method: Method, + path: &str, + credential: Credential, + ) -> Self { + Self { + name, + check, + method, + path: path.to_owned(), + credential, + body: None, + } + } + + fn get(name: &'static str, check: FailedCheck, path: &str, credential: Credential) -> Self { + Self::new(name, check, Method::GET, path, credential) + } + + fn as_principal( + name: &'static str, + check: FailedCheck, + method: Method, + path: &str, + principal: Principal, + ) -> Self { + Self::new( + name, + check, + method, + path, + Credential::Token(token(principal)), + ) + } + + fn with_body(mut self, body: Value) -> Self { + self.body = Some(body); + self + } + + fn request(&self) -> Request { + let mut builder = Request::builder() + .method(self.method.clone()) + .uri(&self.path); + match &self.credential { + Credential::Absent => {} + Credential::Header(value) => builder = builder.header("authorization", *value), + Credential::Token(token) => { + builder = builder.header("authorization", format!("Bearer {token}")); + } + } + match &self.body { + Some(body) => builder + .header("content-type", "application/json") + .header("idempotency-key", Uuid::new_v4().to_string()) + .body(Body::from(body.to_string())) + .unwrap(), + None => builder.body(Body::empty()).unwrap(), + } + } +} + +/// The deployment, one document held for the citizen, and its ids. +struct World { + deployment: Deployment, + prepared: Prepared, + api: Api, + document: String, + version: String, + upload_path: String, +} + +async fn world() -> World { + let mut deployment = Deployment::new(DATABASE_STORAGE, DISABLED_VERIFIER).await; + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + deployment.configure(&format!("metricsListener:\n bind: 127.0.0.1:{port}\n")); + deployment.migrate().await; + let prepared = prepare_with_verifier( + &deployment.runtime, + FakeVerifier::new("refusal-golden", APPROVE), + ) + .await + .expect("the runtime prepares"); + let api = Api::new(&prepared); + let content = pdf(256, 7); + let reserved = api + .reserve( + APP, + "citizen-delivery", + CITIZEN.subject, + &content, + "application/pdf", + ) + .await; + let (document, version, upload_path) = reservation(&reserved); + World { + deployment, + prepared, + api, + document, + version, + upload_path, + } +} + +fn claims(name: &str, value: Value) -> Value { + json!({ name: value }) +} + +fn fixtures(world: &World) -> Vec { + let document = &world.document; + let version = &world.version; + let missing = Uuid::new_v4().to_string(); + let reserve = |policy: &str, custodian: &str| { + support::reservation_body( + policy, + custodian, + &support::sha256(&pdf(256, 7)), + 256, + "application/pdf", + ) + }; + let signed = |claims: Value| Credential::Token(token_with(CITIZEN, claims)); + let mut forged = token(CITIZEN); + let signature_at = forged.rfind('.').unwrap() + 1; + forged.replace_range(signature_at.., &"A".repeat(86)); + vec![ + // The credential. + Fixture::get( + "no-authorization-header", + FailedCheck::CredentialMissing, + "/v1/documents", + Credential::Absent, + ), + Fixture::get( + "another-scheme", + FailedCheck::CredentialMissing, + "/v1/documents", + Credential::Header("Basic dXNlcjpwYXNz"), + ), + Fixture::get( + "empty-bearer", + FailedCheck::CredentialMalformed, + "/v1/documents", + Credential::Header("Bearer"), + ), + Fixture::get( + "not-a-compact-token", + FailedCheck::CredentialMalformed, + "/v1/documents", + Credential::Token("not-a-token".to_owned()), + ), + // The token. + Fixture::get( + "forged-signature", + FailedCheck::TokenSignature, + "/v1/documents", + Credential::Token(forged), + ), + Fixture::get( + "foreign-issuer", + FailedCheck::TokenIssuer, + "/v1/documents", + signed(claims("iss", json!("https://other.example.test"))), + ), + Fixture::get( + "foreign-audience", + FailedCheck::TokenAudience, + "/v1/documents", + signed(claims("aud", json!("urn:example:elsewhere"))), + ), + Fixture::get( + "expired", + FailedCheck::TokenTime, + "/v1/documents", + signed(claims("exp", json!(1_600_000_000))), + ), + Fixture::get( + "unadmitted-client", + FailedCheck::TokenClient, + "/v1/documents", + signed(json!({"azp": "unlisted-client", "client_id": "unlisted-client"})), + ), + Fixture::get( + "exchanged-token", + FailedCheck::TokenAssertionIssuer, + "/v1/documents", + signed(claims( + registry_platform_oidc::ASSERTION_ISSUER_CLAIM, + json!("https://partner.example.test"), + )), + ), + // The profile the token resolves to. + Fixture::get( + "missing-scope", + FailedCheck::Scope, + "/v1/documents", + signed(claims("scope", json!("documents:read"))), + ), + Fixture::get( + "another-actor-kind", + FailedCheck::ActorKind, + "/v1/documents", + signed(claims("registry_actor_kind", json!("service"))), + ), + Fixture::get( + "agent-actor-kind", + FailedCheck::ActorKind, + "/v1/documents", + signed(claims("registry_actor_kind", json!("agent"))), + ), + Fixture::get( + "malformed-actor-kind", + FailedCheck::ActorKind, + "/v1/documents", + signed(claims("registry_actor_kind", json!(7))), + ), + Fixture::get( + "principal-outside-its-grammar", + FailedCheck::TokenClaims, + "/v1/documents", + signed(claims("sub", json!("a principal\u{7}with a control"))), + ), + // A document the caller may not see, or not act on. + Fixture::as_principal( + "read-by-a-stranger", + FailedCheck::Visibility, + Method::GET, + &format!("/v1/documents/{document}"), + STRANGER, + ), + Fixture::as_principal( + "read-of-an-absent-document", + FailedCheck::Visibility, + Method::GET, + &format!("/v1/documents/{missing}"), + CITIZEN, + ), + Fixture::as_principal( + "read-of-a-malformed-id", + FailedCheck::Visibility, + Method::GET, + "/v1/documents/not-a-uuid", + CITIZEN, + ), + Fixture::as_principal( + "download-by-a-stranger", + FailedCheck::Visibility, + Method::GET, + &format!("/v1/documents/{document}/versions/{version}/content"), + STRANGER, + ), + Fixture::as_principal( + "download-by-the-reserving-system", + FailedCheck::Ownership, + Method::GET, + &format!("/v1/documents/{document}/versions/{version}/content"), + APP, + ), + Fixture::as_principal( + "grants-listed-by-a-stranger", + FailedCheck::Visibility, + Method::GET, + &format!("/v1/documents/{document}/grants"), + STRANGER, + ), + Fixture::as_principal( + "grants-listed-by-the-reserving-system", + FailedCheck::Operation, + Method::GET, + &format!("/v1/documents/{document}/grants"), + APP, + ), + Fixture::as_principal( + "grant-issued-by-a-stranger", + FailedCheck::Visibility, + Method::POST, + &format!("/v1/documents/{document}/grants"), + STRANGER, + ) + .with_body( + json!({"versionId": version, "grantee": {"subject": "reader-1", "kind": "human"}}), + ), + Fixture::as_principal( + "grant-issued-by-the-reserving-system", + FailedCheck::Operation, + Method::POST, + &format!("/v1/documents/{document}/grants"), + APP, + ) + .with_body( + json!({"versionId": version, "grantee": {"subject": "reader-1", "kind": "human"}}), + ), + Fixture::as_principal( + "grant-on-another-version", + FailedCheck::Visibility, + Method::POST, + &format!("/v1/documents/{document}/grants"), + CITIZEN, + ) + .with_body( + json!({"versionId": missing, "grantee": {"subject": "reader-1", "kind": "human"}}), + ), + Fixture::as_principal( + "revoke-of-an-absent-grant", + FailedCheck::Visibility, + Method::DELETE, + &format!("/v1/document-grants/{missing}"), + CITIZEN, + ), + Fixture::as_principal( + "erasure-by-a-stranger", + FailedCheck::Visibility, + Method::POST, + &format!("/v1/documents/{document}/erasure"), + STRANGER, + ), + Fixture::as_principal( + "erasure-by-the-reserving-system", + FailedCheck::Ownership, + Method::POST, + &format!("/v1/documents/{document}/erasure"), + APP, + ), + // An upload the caller did not reserve. + Fixture::as_principal( + "upload-to-an-absent-reservation", + FailedCheck::Visibility, + Method::PUT, + &format!("/v1/uploads/{missing}/content"), + APP, + ), + Fixture::as_principal( + "upload-by-another-caller", + FailedCheck::Visibility, + Method::PUT, + &world.upload_path, + OTHER_APP, + ), + // Custody the caller's profile may not place. + Fixture::as_principal( + "reservation-by-a-recipient-profile", + FailedCheck::Operation, + Method::POST, + "/v1/documents", + READER, + ) + .with_body(reserve("citizen-delivery", "citizen-1")), + Fixture::as_principal( + "reservation-outside-the-custody-profiles", + FailedCheck::Operation, + Method::POST, + "/v1/documents", + CITIZEN, + ) + .with_body(reserve("citizen-delivery", "citizen-1")), + Fixture::as_principal( + "reservation-for-another-custodian-by-a-person", + FailedCheck::Operation, + Method::POST, + "/v1/documents", + CITIZEN, + ) + .with_body(reserve("named-share", "citizen-2")), + ] +} + +/// The answer to `fixture` and what a client can read of it: the status, the +/// headers in [`HEADERS`], and the problem body without its trace. +async fn observe(api: &Api, fixture: &Fixture) -> (Answer, Value) { + let answer = api.call(fixture.request()).await; + let mut body: Value = serde_json::from_slice(&answer.body).unwrap_or_else(|_| { + panic!( + "{}: a problem body, got {}", + fixture.name, + String::from_utf8_lossy(&answer.body) + ) + }); + assert!( + body.as_object_mut().unwrap().remove("traceId").is_some(), + "{}: the answer carries a trace", + fixture.name + ); + let headers: BTreeMap<&str, &str> = HEADERS + .iter() + .filter_map(|name| { + answer + .headers + .get(*name) + .map(|value| (*name, value.to_str().unwrap())) + }) + .collect(); + let observed = json!({ + "status": answer.status, + "headers": headers, + "body": body, + }); + (answer, observed) +} + +fn golden_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusals.json") +} + +#[tokio::test] +async fn every_refusal_answers_the_bytes_the_golden_file_holds() { + let world = world().await; + let mut observed = BTreeMap::new(); + for fixture in fixtures(&world) { + let (_, answer) = observe(&world.api, &fixture).await; + assert!( + matches!(answer["status"].as_u64(), Some(401 | 403 | 404)), + "{}: {answer}", + fixture.name + ); + observed.insert(fixture.name, answer); + } + let observed = serde_json::to_value(&observed).unwrap(); + if std::env::var_os("DOCUMENTS_UPDATE_GOLDEN").is_some() { + let text = serde_json::to_string_pretty(&observed).unwrap() + "\n"; + std::fs::create_dir_all(golden_path().parent().unwrap()).unwrap(); + std::fs::write(golden_path(), text).unwrap(); + return; + } + let golden: Value = serde_json::from_slice( + &std::fs::read(golden_path()).expect("tests/golden/refusals.json exists"), + ) + .unwrap(); + assert_eq!( + observed, + golden, + "a refusal answers differently than the golden file holds:\n{}", + serde_json::to_string_pretty(&observed).unwrap() + ); +} + +/// The count `documents_request_refusals_total` holds for `check`. +async fn counted(prepared: &Prepared, check: FailedCheck) -> u64 { + let response = prepared + .metrics_app() + .expect("a metrics listener is configured") + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), 200); + let text = String::from_utf8( + axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(), + ) + .unwrap(); + let prefix = format!( + "documents_request_refusals_total{{check=\"{}\"}} ", + check.as_str() + ); + text.lines() + .find_map(|line| line.strip_prefix(&prefix)) + .unwrap_or_else(|| panic!("no series for {}\n{text}", check.as_str())) + .parse() + .unwrap() +} + +#[tokio::test] +async fn every_refusal_is_counted_and_logged_under_the_check_it_failed() { + let world = world().await; + let logs = registry_platform_testing::CapturedDiagnosticLogs::default(); + let mut logged: BTreeMap<&str, usize> = BTreeMap::new(); + let mut seen: BTreeMap<&str, u64> = BTreeMap::new(); + for fixture in fixtures(&world) { + let before = counted(&world.prepared, fixture.check).await; + let lines_before = logs.text().lines().count(); + let (_, _) = observe(&world.api, &fixture) + .with_subscriber(logs.subscriber()) + .await; + let after = counted(&world.prepared, fixture.check).await; + assert_eq!(after, before + 1, "{}: counted once", fixture.name); + let occurrences = seen.entry(fixture.check.as_str()).or_default(); + *occurrences += 1; + let text = logs.text(); + let written: Vec<&str> = text + .lines() + .skip(lines_before) + .filter(|line| line.contains("request refused")) + .collect(); + // The limiter admits the first lines of each check in a window. + if *occurrences <= 5 { + assert_eq!(written.len(), 1, "{}: one line\n{text}", fixture.name); + let line: Value = serde_json::from_str(written[0]).unwrap(); + let fields = &line["fields"]; + assert_eq!(fields["decision"], "refused", "{}", fixture.name); + assert_eq!( + fields["failed_check"], + fixture.check.as_str(), + "{}", + fixture.name + ); + *logged.entry(fixture.check.as_str()).or_default() += 1; + } + } + let text = logs.text(); + // Nothing a caller sent reaches the log. + for canary in [ + "unlisted-client", + "a principal", + "other.example.test", + "urn:example:elsewhere", + "partner.example.test", + TEST_ISSUER, + TEST_AUDIENCE, + "citizen-portal", + "reader-1", + "someone-else", + "not-a-token", + ] { + assert!(!text.contains(canary), "{canary} reached the log\n{text}"); + } + assert!(!logged.is_empty()); +} + +#[tokio::test] +async fn a_request_that_is_not_refused_is_not_counted() { + let world = world().await; + let before = counted(&world.prepared, FailedCheck::Visibility).await; + let read = world.api.read(CITIZEN, &world.document).await; + assert_eq!(read.status, 200); + let listed = world.api.get(CITIZEN, "/v1/documents").await; + assert_eq!(listed.status, 200); + let missing_route = world.api.get(CITIZEN, "/v1/nothing-here").await; + assert_eq!(missing_route.status, 404); + let unsupported = world + .api + .call( + request(CITIZEN, Method::POST, "/v1/documents") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert!(unsupported.status >= 400); + assert_eq!( + counted(&world.prepared, FailedCheck::Visibility).await, + before + ); + drop(world.deployment); +} diff --git a/crates/registry-documents/tests/token_characterisation.rs b/crates/registry-documents/tests/token_characterisation.rs index 7dc1a1e006..44d7e6ded4 100644 --- a/crates/registry-documents/tests/token_characterisation.rs +++ b/crates/registry-documents/tests/token_characterisation.rs @@ -252,13 +252,13 @@ destinations: let token = case.token.expose(); match authenticator.authenticate(token).await { Ok(caller) => Outcome::Admitted(Some(caller.kind.as_str().to_owned())), - Err(AuthenticationError::Claims) => refusal("claims"), + Err(AuthenticationError::Claims(_)) => refusal("claims"), Err(AuthenticationError::Unavailable) => refusal("unavailable"), - Err(error @ (AuthenticationError::Refused | AuthenticationError::Profile)) => { + Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { let reference = TokenVerifier::new(config.verifier_profile(), keys); match reference.verify(token).await { Err(failure) => refusal(failure.authentication_stage().label()), - Ok(verified) if error == AuthenticationError::Profile => { + Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { if verified.scopes.iter().any(|held| held == &scope) { refusal("profile") } else { diff --git a/crates/registry-evidence-oid4vci/Cargo.toml b/crates/registry-evidence-oid4vci/Cargo.toml index 88573bbbfb..2b61abf0f1 100644 --- a/crates/registry-evidence-oid4vci/Cargo.toml +++ b/crates/registry-evidence-oid4vci/Cargo.toml @@ -49,6 +49,7 @@ jsonwebtoken.workspace = true registry-evidence-client.workspace = true registry-evidence-verifier.workspace = true registry-platform-audit.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto = { workspace = true, features = ["xchacha-seal"] } diff --git a/crates/registry-evidence-oid4vci/src/authorizer.rs b/crates/registry-evidence-oid4vci/src/authorizer.rs index ebe4be5532..b029c310e9 100644 --- a/crates/registry-evidence-oid4vci/src/authorizer.rs +++ b/crates/registry-evidence-oid4vci/src/authorizer.rs @@ -18,6 +18,7 @@ use std::{collections::HashSet, sync::Arc, time::Duration}; use async_trait::async_trait; +use registry_platform_authcommon::FailedCheck; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ grant_claims, ClaimNames, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcError, @@ -52,12 +53,25 @@ pub struct AuthorizedOffer { pub enum AuthorizationError { #[error("the request carried no bearer credential")] Missing, + /// The credential was refused, under the check that refused it. #[error("the presented credential was refused")] - Refused, + Refused(FailedCheck), #[error("the offer key set is unavailable")] KeySource, } +impl AuthorizationError { + /// The check the request failed. + #[must_use] + pub const fn failed_check(&self) -> FailedCheck { + match self { + Self::Missing => FailedCheck::CredentialMissing, + Self::Refused(check) => *check, + Self::KeySource => FailedCheck::KeySourceUnavailable, + } + } +} + /// The seam the offer endpoint authorizes through. #[async_trait] pub trait OfferAuthorizer: Send + Sync { @@ -185,7 +199,7 @@ impl OfferAuthorizer for MintResourceServer { Ok(verified) => { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) - .map_err(|_| AuthorizationError::Refused)? + .map_err(|_| AuthorizationError::Refused(FailedCheck::TokenTime))? .as_secs(); if !matches!(grant_claims(&verified.claims, &self.claims, now), Ok(None)) || !matches!( @@ -197,7 +211,7 @@ impl OfferAuthorizer for MintResourceServer { // later redemption cannot recheck the task authority. No // complete, partial, malformed, or expired task grant under // either configured or reserved claim names may cross it. - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TaskGrantClaims)); } // The scope gate runs only on the verified token's scope set: // a correctly signed token for this audience whose client @@ -210,7 +224,7 @@ impl OfferAuthorizer for MintResourceServer { .iter() .all(|scope| present.contains(scope.as_str())) { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::Scope)); } } let client = match verified.matched_client_id() { @@ -232,7 +246,7 @@ impl OfferAuthorizer for MintResourceServer { target: "registry_evidence_oid4vci::authorizer", "the token verifier returned a malformed matched client" ); - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenClient)); } }; let subject = verified @@ -241,18 +255,12 @@ impl OfferAuthorizer for MintResourceServer { .clone() .filter(|subject| !subject.is_empty()); if client.is_none() && subject.is_none() { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenClient)); } Ok(AuthorizedOffer { client, subject }) } - Err(error) if is_key_source_failure(&error) => { - tracing::warn!( - target: "registry_evidence_oid4vci::authorizer", - "the offer key set is unavailable" - ); - Err(AuthorizationError::KeySource) - } - Err(_) => Err(AuthorizationError::Refused), + Err(error) if is_key_source_failure(&error) => Err(AuthorizationError::KeySource), + Err(error) => Err(AuthorizationError::Refused(error.failed_check())), } } } diff --git a/crates/registry-evidence-oid4vci/src/observability.rs b/crates/registry-evidence-oid4vci/src/observability.rs index 409d15c372..fa56a46693 100644 --- a/crates/registry-evidence-oid4vci/src/observability.rs +++ b/crates/registry-evidence-oid4vci/src/observability.rs @@ -23,6 +23,7 @@ use axum::{ Router, }; +use registry_platform_authcommon::{RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ Exposition, HistogramSnapshot, MetricKind, SumCountOrder, CONTENT_TYPE as METRICS_MEDIA_TYPE, }; @@ -139,6 +140,7 @@ pub(crate) struct Metrics { store_entries: AtomicUsize, store_capacity: usize, cleanup_expired: AtomicU64, + refusals: RefusalRecorder, } impl Metrics { @@ -149,9 +151,22 @@ impl Metrics { store_entries: AtomicUsize::new(0), store_capacity, cleanup_expired: AtomicU64::new(0), + refusals: RefusalRecorder::new("evidence_oid4vci").expect(DECLARATION), } } + /// Count a refused request under its check and write the admitted log + /// line. + fn record_refusal(&self, note: RefusalNote) { + registry_platform_authcommon::record_refusal!(self.refusals, note); + } + + /// The recorder that counts each refused request under its check. + #[cfg(test)] + pub(crate) fn refusal_recorder(&self) -> &RefusalRecorder { + &self.refusals + } + pub(crate) fn record_outcome(&self, outcome: Outcome) { let mut outcomes = self .outcomes @@ -295,6 +310,7 @@ impl Metrics { self.cleanup_expired.load(Ordering::Relaxed), ) .expect(DECLARATION); + self.refusals.counter().write(&mut out).expect(DECLARATION); out.finish() } } @@ -324,6 +340,9 @@ pub(crate) async fn observe( .map_or(NO_ERROR, |problem| normalized_problem(problem.0)); metrics.record_request(route, method, status, error, started.elapsed()); log_request(route, method, status, error); + if let Some(note) = response.extensions().get::() { + metrics.record_refusal(*note); + } response } diff --git a/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt b/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt index e487bf305c..67cf00d65c 100644 --- a/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt +++ b/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt @@ -103,3 +103,50 @@ evidence_oid4vci_store_capacity 256 # HELP evidence_oid4vci_cleanup_expired_total Expired in-memory entries released by cleanup. # TYPE evidence_oid4vci_cleanup_expired_total counter evidence_oid4vci_cleanup_expired_total 3 +# HELP evidence_oid4vci_request_refusals_total Requests refused, by the check that failed. +# TYPE evidence_oid4vci_request_refusals_total counter +evidence_oid4vci_request_refusals_total{check="credential-missing"} 0 +evidence_oid4vci_request_refusals_total{check="credential-malformed"} 0 +evidence_oid4vci_request_refusals_total{check="token-algorithm"} 0 +evidence_oid4vci_request_refusals_total{check="token-type"} 0 +evidence_oid4vci_request_refusals_total{check="token-key"} 0 +evidence_oid4vci_request_refusals_total{check="token-signature"} 0 +evidence_oid4vci_request_refusals_total{check="token-issuer"} 0 +evidence_oid4vci_request_refusals_total{check="token-audience"} 0 +evidence_oid4vci_request_refusals_total{check="token-time"} 0 +evidence_oid4vci_request_refusals_total{check="token-client"} 0 +evidence_oid4vci_request_refusals_total{check="token-assertion-issuer"} 0 +evidence_oid4vci_request_refusals_total{check="token-claims"} 0 +evidence_oid4vci_request_refusals_total{check="actor-kind"} 0 +evidence_oid4vci_request_refusals_total{check="delegation"} 0 +evidence_oid4vci_request_refusals_total{check="sender-constraint"} 0 +evidence_oid4vci_request_refusals_total{check="key-source-unavailable"} 0 +evidence_oid4vci_request_refusals_total{check="shared-secret"} 0 +evidence_oid4vci_request_refusals_total{check="one-time-credential"} 0 +evidence_oid4vci_request_refusals_total{check="delivery-signature"} 0 +evidence_oid4vci_request_refusals_total{check="delivery-freshness"} 0 +evidence_oid4vci_request_refusals_total{check="delivery-binding"} 0 +evidence_oid4vci_request_refusals_total{check="host-origin"} 0 +evidence_oid4vci_request_refusals_total{check="scope"} 0 +evidence_oid4vci_request_refusals_total{check="access-profile"} 0 +evidence_oid4vci_request_refusals_total{check="requester-client"} 0 +evidence_oid4vci_request_refusals_total{check="purpose"} 0 +evidence_oid4vci_request_refusals_total{check="operation"} 0 +evidence_oid4vci_request_refusals_total{check="disclosure"} 0 +evidence_oid4vci_request_refusals_total{check="subject-selector"} 0 +evidence_oid4vci_request_refusals_total{check="revision-pin"} 0 +evidence_oid4vci_request_refusals_total{check="acquisition-channel"} 0 +evidence_oid4vci_request_refusals_total{check="source-authority"} 0 +evidence_oid4vci_request_refusals_total{check="separation-of-duties"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-missing"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-claims"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-expired"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-binding"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-scope"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-lifetime"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-status"} 0 +evidence_oid4vci_request_refusals_total{check="row-boundary"} 0 +evidence_oid4vci_request_refusals_total{check="ownership"} 0 +evidence_oid4vci_request_refusals_total{check="visibility"} 0 +evidence_oid4vci_request_refusals_total{check="action-guard"} 0 +evidence_oid4vci_request_refusals_total{check="rate-limit"} 0 diff --git a/crates/registry-evidence-oid4vci/src/service.rs b/crates/registry-evidence-oid4vci/src/service.rs index 6ab18f3caa..2f35ec22f1 100644 --- a/crates/registry-evidence-oid4vci/src/service.rs +++ b/crates/registry-evidence-oid4vci/src/service.rs @@ -54,6 +54,7 @@ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use chrono::Utc; use registry_evidence_client::{HolderPublicKey, MAXIMUM_HOLDER_KEYS}; use registry_evidence_verifier::sdjwt_vc::holder_thumbprint; +use registry_platform_authcommon::{FailedCheck, RefusalNote}; use registry_platform_config::describe_secret_failure; use registry_platform_crypto::PublicJwk; use registry_platform_httpsec::{ @@ -239,9 +240,11 @@ async fn admit(limiter: &TokenBucketLimiter, key: &str) -> Result<(), Response> /// own key or cost is a fault of this service, so it is logged without the key /// and answered as a server error that carries no Retry-After. fn limiter_refusal(error: &TokenBucketError) -> Response { - let wait = match error { - TokenBucketError::Exceeded { retry_after } => retry_after.as_secs() + 1, - TokenBucketError::Capacity => CAPACITY_RETRY_SECONDS, + let (wait, check) = match error { + TokenBucketError::Exceeded { retry_after } => { + (retry_after.as_secs() + 1, Some(FailedCheck::RateLimit)) + } + TokenBucketError::Capacity => (CAPACITY_RETRY_SECONDS, None), TokenBucketError::Configuration | TokenBucketError::CostExceedsBurst => { tracing::error!( fault = %error, @@ -262,7 +265,10 @@ fn limiter_refusal(error: &TokenBucketError) -> Response { response .headers_mut() .insert(RETRY_AFTER, HeaderValue::from(wait)); - response + match check { + Some(check) => refused(response, check), + None => response, + } } /// The limiter key of an authorized offer principal: a digest, so a client id @@ -1134,7 +1140,10 @@ async fn credential( body: Bytes, ) -> Response { let Some(access_token) = bearer_credential(&headers) else { - return unauthorized("a bearer access token is required"); + return unauthorized( + FailedCheck::CredentialMissing, + "a bearer access token is required", + ); }; let access_token = Zeroizing::new(access_token.to_owned()); stage.mark_claiming_token(); @@ -1146,7 +1155,10 @@ async fn credential( Ok(prepared) => prepared, Err(StoreError::Unknown) => { service.metrics.record_outcome(Outcome::TokenClaimRefused); - return unauthorized("the access token cannot be used"); + return unauthorized( + FailedCheck::OneTimeCredential, + "the access token cannot be used", + ); } Err(error) => return store_response(&service, &error, Outcome::TokenClaimRefused), }; @@ -1512,12 +1524,20 @@ async fn authorize_offer( .authorize(credential) .await .map_err(|error| match error { - AuthorizationError::Missing => unauthorized("a bearer access token is required"), - AuthorizationError::Refused => unauthorized("the presented credential was refused"), - AuthorizationError::KeySource => problem( - StatusCode::SERVICE_UNAVAILABLE, - "temporarily_unavailable", - "offers cannot be authorized at the moment", + AuthorizationError::Missing => unauthorized( + FailedCheck::CredentialMissing, + "a bearer access token is required", + ), + AuthorizationError::Refused(check) => { + unauthorized(check, "the presented credential was refused") + } + AuthorizationError::KeySource => refused( + problem( + StatusCode::SERVICE_UNAVAILABLE, + "temporarily_unavailable", + "offers cannot be authorized at the moment", + ), + FailedCheck::KeySourceUnavailable, ), }) } @@ -1546,19 +1566,21 @@ fn now() -> i64 { fn store_response( service: &Arc, error: &StoreError, - refused: Outcome, + claim_refused: Outcome, ) -> Response { service.metrics.record_outcome(match error { StoreError::Saturated => Outcome::StoreSaturated, StoreError::Poisoned | StoreError::Unavailable => Outcome::StoreFault, - _ => refused, + _ => claim_refused, }); refresh_store_entries_in_background(service); match error { StoreError::Unknown | StoreError::AlreadyRedeemed | StoreError::TransactionCodeRefused - | StoreError::LockedOut => unredeemable_code_response(), + | StoreError::LockedOut => { + refused(unredeemable_code_response(), FailedCheck::OneTimeCredential) + } StoreError::Saturated | StoreError::Poisoned | StoreError::Unavailable => { tracing::warn!( target: "registry_evidence_oid4vci::service", @@ -1618,10 +1640,13 @@ fn warn_on_unusable_issuance(error: &IssuanceError) { fn issuance_response(service: &DeliveryService, error: &IssuanceError) -> Response { record_issuance_outcome(service, error); match error { - IssuanceError::Refused => problem( - StatusCode::FORBIDDEN, - "invalid_credential_request", - "the credential source refused this request", + IssuanceError::Refused => refused( + problem( + StatusCode::FORBIDDEN, + "invalid_credential_request", + "the credential source refused this request", + ), + FailedCheck::SourceAuthority, ), IssuanceError::NotAvailable => problem( StatusCode::BAD_REQUEST, @@ -1648,7 +1673,12 @@ fn issuance_response(service: &DeliveryService, error: &IssuanceError) -> Respon fn credential_issuance_response(service: &DeliveryService, error: &IssuanceError) -> Response { record_issuance_outcome(service, error); warn_on_unusable_issuance(error); - terminal_credential_response() + match error { + IssuanceError::Refused => { + refused(terminal_credential_response(), FailedCheck::SourceAuthority) + } + _ => terminal_credential_response(), + } } fn terminal_credential_response() -> Response { @@ -1684,12 +1714,19 @@ async fn unknown_route() -> Response { problem(StatusCode::NOT_FOUND, "invalid_request", "no such route") } -fn unauthorized(description: &'static str) -> Response { +/// The answer carrying the check that refused the caller in its response +/// extensions, which are never serialized. The request observer reads it. +fn refused(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + +fn unauthorized(check: FailedCheck, description: &'static str) -> Response { let mut response = problem(StatusCode::UNAUTHORIZED, "invalid_token", description); response .headers_mut() .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); - response + refused(response, check) } /// One error shape for every refusal: the OAuth members a wallet already reads, @@ -1775,6 +1812,7 @@ mod tests { use axum_test::TestServer; use registry_evidence_client::HolderBoundRequestSpec; use registry_platform_audit::AuditWriter; + use registry_platform_authcommon::FailedCheck; use crate::{ authorizer::AuthorizedOffer, @@ -1886,7 +1924,7 @@ mod tests { return Err(AuthorizationError::Missing); } if credential != self.accepted { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: Some("adopter-front-end".to_owned()), @@ -2738,7 +2776,7 @@ mod tests { impl OfferAuthorizer for PrincipalAuthorizer { async fn authorize(&self, credential: &str) -> Result { if credential != self.token { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: self.client.clone(), @@ -2766,7 +2804,7 @@ mod tests { return Ok(authorized); } } - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TokenSignature)) } } @@ -5310,4 +5348,354 @@ mod tests { assert_eq!(error.kind(), io::ErrorKind::InvalidInput); } } + + /// An Evidence boundary that refuses: the catalog when `catalog_refused` + /// is set, and every issuance otherwise. + struct RefusingIssuer { + inner: RecordingIssuer, + catalog_refused: bool, + } + + #[async_trait] + impl CredentialIssuer for RefusingIssuer { + async fn catalog(&self) -> Result, IssuanceError> { + if self.catalog_refused { + return Err(IssuanceError::Refused); + } + self.inner.catalog().await + } + + async fn issue(&self, _: HolderBoundRequestSpec) -> Result, IssuanceError> { + Err(IssuanceError::Refused) + } + } + + fn refusing_server( + directory: &Path, + catalog_refused: bool, + ) -> (TestServer, Arc) { + let service = Arc::new(DeliveryService::with_halves( + load_deployment(directory), + Arc::new(StubAuthorizer { + accepted: OFFER_TOKEN.to_owned(), + }), + Arc::new(RefusingIssuer { + inner: RecordingIssuer::new(), + catalog_refused, + }), + test_audit(), + )); + (TestServer::new(build_app(Arc::clone(&service))), service) + } + + fn draft13_server(directory: &Path) -> (TestServer, Arc) { + let mut config = load_deployment(directory); + config.draft13_profile = true; + let (service, _) = wired_service_over(config); + (TestServer::new(build_app(Arc::clone(&service))), service) + } + + fn limited_server(directory: &Path) -> (TestServer, Arc) { + let mut config = load_deployment(directory); + config.rate_limits = tight_limits(); + let (service, _) = wired_service_over(config); + (TestServer::new(build_app(Arc::clone(&service))), service) + } + + /// One refusal as the golden freezes it: status, the headers a caller or + /// proxy acts on, and the body. A `retry-after` on a 429 is the bucket's + /// remaining wait, which moves with the clock, so only its presence is + /// frozen there. + fn frozen_answer(response: &axum_test::TestResponse) -> Value { + let status = response.status_code().as_u16(); + let mut headers = serde_json::Map::new(); + for name in [ + "content-type", + "www-authenticate", + "cache-control", + "pragma", + "retry-after", + ] { + if let Some(value) = response.maybe_header(name) { + let text = if name == "retry-after" && status == 429 { + "".to_owned() + } else { + value.to_str().expect("ASCII header").to_owned() + }; + headers.insert(name.to_owned(), text.into()); + } + } + let body: Value = serde_json::from_slice(response.as_bytes()).expect("a JSON body"); + json!({"status": status, "headers": headers, "body": body}) + } + + /// Every refusal a caller can provoke, with the name the golden files it + /// under and the check that refuses it, or `None` where the answer + /// carries no check. + /// + /// Each case also names which of the returned services answered it, so a + /// test can read that service's counter. + async fn refusal_cases() -> ( + Vec<(&'static str, Option, Value, usize)>, + Vec>, + ) { + let mut cases = Vec::new(); + let current = std::cell::Cell::new(0_usize); + let mut put = |name, check, response: axum_test::TestResponse| { + cases.push((name, check, frozen_answer(&response), current.get())); + }; + let directory = canonical_tempdir(); + let (service, _) = wired_service(directory.path()); + let mut services = vec![Arc::clone(&service)]; + let server = TestServer::new(build_app(service)); + let offer = |authorization: Option<&str>| { + let mut request = server.post(OFFERS_PATH); + if let Some(value) = authorization { + request = request.add_header("authorization", value.to_owned()); + } + request.json(&offer_body(false)) + }; + put( + "offer-no-header", + Some(FailedCheck::CredentialMissing), + offer(None).await, + ); + put( + "offer-non-bearer-scheme", + Some(FailedCheck::CredentialMissing), + offer(Some("Basic dXNlcjpwYXNz")).await, + ); + put( + "offer-wrong-token", + Some(FailedCheck::TokenSignature), + offer(Some("Bearer not-the-offer-token")).await, + ); + put( + "token-unknown-code", + Some(FailedCheck::OneTimeCredential), + server + .post(TOKEN_PATH) + .form(&token_form("unknown-code", None)) + .await, + ); + let created = offer(Some(&format!("Bearer {OFFER_TOKEN}"))).await; + let code = offered_code(&created.json()); + server + .post(TOKEN_PATH) + .form(&token_form(&code, None)) + .await + .assert_status_ok(); + put( + "token-redeemed-code", + Some(FailedCheck::OneTimeCredential), + server.post(TOKEN_PATH).form(&token_form(&code, None)).await, + ); + put( + "credential-no-header", + Some(FailedCheck::CredentialMissing), + server.post(CREDENTIAL_PATH).json(&json!({})).await, + ); + put( + "credential-unknown-token", + Some(FailedCheck::OneTimeCredential), + server + .post(CREDENTIAL_PATH) + .add_header("authorization", "Bearer unknown-token") + .json(&json!({})) + .await, + ); + + // The draft 13 profile's own handlers. + let (draft13, service) = draft13_server(directory.path()); + services.push(service); + current.set(1); + put( + "draft13-credential-no-header", + Some(FailedCheck::CredentialMissing), + draft13 + .post(crate::draft13::CREDENTIAL_PATH) + .json(&json!({})) + .await, + ); + put( + "draft13-credential-unknown-token", + Some(FailedCheck::OneTimeCredential), + draft13 + .post(crate::draft13::CREDENTIAL_PATH) + .add_header("authorization", "Bearer unknown-token") + .json(&json!({})) + .await, + ); + put( + "draft13-token-unknown-code", + Some(FailedCheck::OneTimeCredential), + draft13 + .post(crate::draft13::TOKEN_PATH) + .form(&token_form("unknown-code", None)) + .await, + ); + + // Spent budgets. + let (limited, service) = limited_server(directory.path()); + services.push(service); + current.set(2); + limited.post(NONCE_PATH).await.assert_status_ok(); + put( + "nonce-rate-limited", + Some(FailedCheck::RateLimit), + limited.post(NONCE_PATH).await, + ); + put( + "setup-token", + Some(FailedCheck::OneTimeCredential), + limited.post(TOKEN_PATH).form(&token_form("x", None)).await, + ); + put( + "token-rate-limited", + Some(FailedCheck::RateLimit), + limited.post(TOKEN_PATH).form(&token_form("x", None)).await, + ); + put( + "setup-credential", + Some(FailedCheck::CredentialMissing), + limited.post(CREDENTIAL_PATH).json(&json!({})).await, + ); + put( + "credential-rate-limited", + Some(FailedCheck::RateLimit), + limited.post(CREDENTIAL_PATH).json(&json!({})).await, + ); + let offers = || { + limited + .post(OFFERS_PATH) + .add_header("authorization", format!("Bearer {OFFER_TOKEN}")) + .json(&offer_body(false)) + }; + offers().await; + put( + "offer-rate-limited", + Some(FailedCheck::RateLimit), + offers().await, + ); + + // Evidence refusing. + let (refused_catalog, service) = refusing_server(directory.path(), true); + services.push(service); + current.set(3); + put( + "offer-evidence-refused", + Some(FailedCheck::SourceAuthority), + refused_catalog + .post(OFFERS_PATH) + .add_header("authorization", format!("Bearer {OFFER_TOKEN}")) + .json(&offer_body(false)) + .await, + ); + let (refused_issue, service) = refusing_server(directory.path(), false); + services.push(service); + current.set(4); + let token = access_token(&refused_issue).await; + let nonce = minted_nonce(&refused_issue).await; + let key = private_jwk("refusal-golden"); + put( + "credential-evidence-refused", + Some(FailedCheck::SourceAuthority), + refused_issue + .post(CREDENTIAL_PATH) + .add_header("authorization", format!("Bearer {token}")) + .json(&json!({ + "credential_configuration_id": CONFIGURATION_ID, + "proofs": {"jwt": [proof_jwt(&key, "https://wallet.example.org", &nonce, now())]}, + })) + .await, + ); + (cases, services) + } + + /// The refusals as the whole router answers them, frozen in a checked-in + /// file that was written from the tree before any recording existed. Run + /// with `REGISTRY_OID4VCI_WRITE_GOLDEN=1` to rewrite it. + #[tokio::test] + async fn refusal_answers_match_the_golden() { + let mut answers = serde_json::Map::new(); + for (name, _, answer, _) in refusal_cases().await.0 { + // Setup requests spend a budget and are counted, but are not part + // of the frozen set. + if !name.starts_with("setup-") { + answers.insert(name.to_owned(), answer); + } + } + let actual = Value::Object(answers); + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusals.json"); + if std::env::var_os("REGISTRY_OID4VCI_WRITE_GOLDEN").is_some() { + fs::create_dir_all(path.parent().expect("parent")).expect("golden directory"); + fs::write( + &path, + format!("{}\n", serde_json::to_string_pretty(&actual).expect("json")), + ) + .expect("write golden"); + } + let expected: Value = + serde_json::from_slice(&fs::read(&path).expect("golden file")).expect("golden json"); + assert_eq!(actual, expected); + } + + /// Every refusal is counted under its check in the service that answered + /// it, nothing else is counted, and the log carries fixed lines only. + #[tokio::test] + async fn each_refusal_is_counted_and_logged_under_its_check() { + let buffer = TestLogBuffer::default(); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_writer(buffer.clone()) + .finish(); + let _logging = tracing::subscriber::set_default(subscriber); + + let (cases, services) = refusal_cases().await; + for (index, service) in services.iter().enumerate() { + for check in FailedCheck::ALL { + let expected = cases + .iter() + .filter(|(_, case_check, _, case_index)| { + *case_index == index && *case_check == Some(check) + }) + .count() as u64; + assert_eq!( + service + .metrics + .refusal_recorder() + .counter() + .get(&[check.as_str()]) + .expect("every check is declared"), + expected, + "service {index}, check {}", + check.as_str() + ); + } + } + let rendered = String::from_utf8(buffer.0.lock().expect("log buffer lock").clone()) + .expect("logs are UTF-8"); + for (name, check, _, _) in &cases { + let check = check.expect("every case names its check"); + assert!( + rendered.contains(&format!("failed_check=\"{}\"", check.as_str())) + || rendered.contains(&format!("failed_check={}", check.as_str())), + "{name}: no log line for {}: {rendered}", + check.as_str() + ); + } + assert!(rendered.contains("request refused"), "{rendered}"); + for canary in [ + OFFER_TOKEN, + "not-the-offer-token", + "unknown-token", + "unknown-code", + SELECTOR_VALUE, + "adopter-front-end", + "Basic dXNlcjpwYXNz", + ] { + assert!(!rendered.contains(canary), "logs rendered {canary}"); + } + } } diff --git a/crates/registry-evidence-oid4vci/src/service/draft13.rs b/crates/registry-evidence-oid4vci/src/service/draft13.rs index 698059d4a9..c134a76345 100644 --- a/crates/registry-evidence-oid4vci/src/service/draft13.rs +++ b/crates/registry-evidence-oid4vci/src/service/draft13.rs @@ -109,7 +109,10 @@ async fn credential( body: Bytes, ) -> Response { let Some(access_token) = bearer_credential(&headers) else { - return unauthorized("a bearer access token is required"); + return unauthorized( + FailedCheck::CredentialMissing, + "a bearer access token is required", + ); }; let access_token = Zeroizing::new(access_token.to_owned()); stage.mark_claiming_token(); @@ -125,7 +128,10 @@ async fn credential( Ok(prepared) => prepared, Err(StoreError::Unknown) => { service.metrics.record_outcome(Outcome::TokenClaimRefused); - return unauthorized("the access token cannot be used"); + return unauthorized( + FailedCheck::OneTimeCredential, + "the access token cannot be used", + ); } Err(error) => return store_response(&service, &error, Outcome::TokenClaimRefused), }; diff --git a/crates/registry-evidence-oid4vci/tests/draft13_profile.rs b/crates/registry-evidence-oid4vci/tests/draft13_profile.rs index 2de7611290..77fff8744b 100644 --- a/crates/registry-evidence-oid4vci/tests/draft13_profile.rs +++ b/crates/registry-evidence-oid4vci/tests/draft13_profile.rs @@ -48,6 +48,7 @@ use registry_evidence_verifier::{ EVIDENCE_SCHEMA_V1, }; use registry_platform_audit::AuditWriter; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{hmac_sha256_base64url_no_pad, sign, PrivateJwk}; use registry_platform_sdjwt::SdJwtIssuer; use serde_json::{json, Value}; @@ -151,7 +152,7 @@ impl OfferAuthorizer for StubAuthorizer { return Err(AuthorizationError::Missing); } if credential != OFFER_TOKEN { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: Some("adopter-front-end".to_owned()), diff --git a/crates/registry-evidence-oid4vci/tests/golden/refusals.json b/crates/registry-evidence-oid4vci/tests/golden/refusals.json new file mode 100644 index 0000000000..db0fbd2f3b --- /dev/null +++ b/crates/registry-evidence-oid4vci/tests/golden/refusals.json @@ -0,0 +1,205 @@ +{ + "credential-evidence-refused": { + "body": { + "error": "credential_request_denied", + "error_description": "this credential request cannot be completed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 400 + }, + "credential-no-header": { + "body": { + "error": "invalid_token", + "error_description": "a bearer access token is required" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "credential-rate-limited": { + "body": { + "error": "temporarily_unavailable", + "error_description": "too many requests; retry after the interval in Retry-After" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "retry-after": "" + }, + "status": 429 + }, + "credential-unknown-token": { + "body": { + "error": "invalid_token", + "error_description": "the access token cannot be used" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "draft13-credential-no-header": { + "body": { + "error": "invalid_token", + "error_description": "a bearer access token is required" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "draft13-credential-unknown-token": { + "body": { + "error": "invalid_token", + "error_description": "the access token cannot be used" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "draft13-token-unknown-code": { + "body": { + "error": "invalid_grant", + "error_description": "the pre-authorized code cannot be redeemed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 400 + }, + "nonce-rate-limited": { + "body": { + "error": "temporarily_unavailable", + "error_description": "too many requests; retry after the interval in Retry-After" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "retry-after": "" + }, + "status": 429 + }, + "offer-evidence-refused": { + "body": { + "error": "invalid_credential_request", + "error_description": "the credential source refused this request" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 403 + }, + "offer-no-header": { + "body": { + "error": "invalid_token", + "error_description": "a bearer access token is required" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "offer-non-bearer-scheme": { + "body": { + "error": "invalid_token", + "error_description": "a bearer access token is required" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "offer-rate-limited": { + "body": { + "error": "temporarily_unavailable", + "error_description": "too many requests; retry after the interval in Retry-After" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "retry-after": "" + }, + "status": 429 + }, + "offer-wrong-token": { + "body": { + "error": "invalid_token", + "error_description": "the presented credential was refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "token-rate-limited": { + "body": { + "error": "temporarily_unavailable", + "error_description": "too many requests; retry after the interval in Retry-After" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "retry-after": "" + }, + "status": 429 + }, + "token-redeemed-code": { + "body": { + "error": "invalid_grant", + "error_description": "the pre-authorized code cannot be redeemed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 400 + }, + "token-unknown-code": { + "body": { + "error": "invalid_grant", + "error_description": "the pre-authorized code cannot be redeemed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 400 + } +} diff --git a/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs b/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs index f8c97e3799..8e27f9626e 100644 --- a/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs +++ b/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs @@ -62,6 +62,7 @@ use registry_evidence_verifier::{ EVIDENCE_SCHEMA_V1, }; use registry_platform_audit::AuditWriter; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{hmac_sha256_base64url_no_pad, sign, PrivateJwk, PublicJwk}; use registry_platform_sdjwt::{presentation_disclosure_hash, SdJwtIssuer}; use serde_json::{json, Value}; @@ -165,7 +166,7 @@ impl OfferAuthorizer for FixtureAuthorizer { return Err(AuthorizationError::Missing); } if credential != OFFER_TOKEN { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: Some("fixture-adopter".to_owned()), diff --git a/crates/registry-evidence-oid4vci/tests/offer_authorization.rs b/crates/registry-evidence-oid4vci/tests/offer_authorization.rs index fa8a1e9287..cd83147b5e 100644 --- a/crates/registry-evidence-oid4vci/tests/offer_authorization.rs +++ b/crates/registry-evidence-oid4vci/tests/offer_authorization.rs @@ -28,6 +28,7 @@ use registry_evidence_oid4vci::{ config::{AccessTokenAlgorithm, OfferAuthorizationConfig, Restriction}, }; use registry_platform_audit::AuditWriter; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{sign, PrivateJwk, PublicJwk}; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier}; use registry_thunderid_tooling::{ @@ -134,7 +135,7 @@ async fn a_token_without_the_required_offer_scope_is_refused() { config.required_scopes = Restriction::Listed(vec!["oid4vci:offer".to_owned()]); assert_eq!( resource_server(&config, &key_set).authorize(&issued).await, - Err(AuthorizationError::Refused), + Err(AuthorizationError::Refused(FailedCheck::Scope)), "a correctly signed audience-matching token with no offer scope authorized an offer" ); @@ -295,7 +296,7 @@ async fn an_offer_token_without_a_nonempty_client_or_subject_is_refused() { let (token, keys) = signed_offer_fixture(identities); assert_eq!( resource_server(&config, &keys).authorize(&token).await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TokenClient)) ); } } @@ -321,13 +322,13 @@ async fn task_bound_and_partial_grants_cannot_create_deferred_wallet_offers() { }; assert_eq!( resource_server(&config, &keys).authorize(&task_bound).await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TaskGrantClaims)) ); let (partial, keys) = signed_offer_fixture(json!({"registry_grant_id":"grant-a"})); assert_eq!( resource_server(&config, &keys).authorize(&partial).await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TaskGrantClaims)) ); } @@ -362,7 +363,7 @@ async fn a_token_issued_for_another_resource_server_is_refused() { ) .authorize(&token) .await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TokenAudience)) ); } @@ -378,11 +379,13 @@ async fn a_token_this_issuer_did_not_sign_is_refused() { let forged = format!("{}.{}", parts.join("."), URL_SAFE_NO_PAD.encode([0_u8; 64])); assert_eq!( server.authorize(&forged).await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TokenSignature)) ); assert_eq!( server.authorize("not-a-token").await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused( + FailedCheck::CredentialMalformed + )) ); assert_eq!(server.authorize("").await, Err(AuthorizationError::Missing)); } diff --git a/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs b/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs index 2a598910cf..da86bc440d 100644 --- a/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs +++ b/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs @@ -37,6 +37,7 @@ use registry_evidence_oid4vci::{ PRE_AUTHORIZED_CODE_GRANT_TYPE, }; use registry_platform_audit::AuditWriter; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{sign, PrivateJwk}; use serde_json::{json, Value}; use tokio::sync::Barrier; @@ -123,7 +124,7 @@ impl OfferAuthorizer for StubAuthorizer { return Err(AuthorizationError::Missing); } if credential != OFFER_TOKEN { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: Some("adopter-front-end".to_owned()), diff --git a/crates/registry-evidence-oid4vci/tests/token_characterisation.rs b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs index cef6d01bd8..070161a043 100644 --- a/crates/registry-evidence-oid4vci/tests/token_characterisation.rs +++ b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs @@ -160,7 +160,9 @@ async fn authorize(case: FixtureCase, key_set_uri: String) -> Outcome { Ok(_) => Outcome::Admitted(None), Err(AuthorizationError::Missing) => Outcome::Refused(Stage::Header), Err(AuthorizationError::KeySource) => Outcome::Refused(Stage::Unavailable), - Err(AuthorizationError::Refused) => Outcome::Refused(refusal_stage(&config, &case).await), + Err(AuthorizationError::Refused(_)) => { + Outcome::Refused(refusal_stage(&config, &case).await) + } } } diff --git a/crates/registry-evidence-oid4vp/Cargo.toml b/crates/registry-evidence-oid4vp/Cargo.toml index 7e58d24d42..d3906c2bb0 100644 --- a/crates/registry-evidence-oid4vp/Cargo.toml +++ b/crates/registry-evidence-oid4vp/Cargo.toml @@ -31,12 +31,12 @@ chrono.workspace = true clap.workspace = true der.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true registry-platform-crypto = { workspace = true, features = ["jwe"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["refusal-trace-id", "server"] } registry-platform-metrics.workspace = true registry-platform-oidc.workspace = true registry-platform-ratelimit.workspace = true diff --git a/crates/registry-evidence-oid4vp/src/auth.rs b/crates/registry-evidence-oid4vp/src/auth.rs index b1d382282e..4e568fc335 100644 --- a/crates/registry-evidence-oid4vp/src/auth.rs +++ b/crates/registry-evidence-oid4vp/src/auth.rs @@ -9,7 +9,7 @@ use std::{sync::Arc, time::Duration}; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{parse_bearer_token, BearerParseError, FailedCheck}; use registry_platform_config::{JwksSource, SecretResolver}; use registry_platform_oidc::{ parse_static_jwks, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, @@ -24,14 +24,24 @@ const ACCESS_TOKEN_TYPES: [&str; 2] = ["at+jwt", "application/at+jwt"]; /// Why a request was not authenticated. #[derive(Debug, Eq, PartialEq, thiserror::Error)] pub enum AuthError { - #[error("the request carried no bearer credential")] - Missing, + /// The caller's credential was refused, under the check that refused it. #[error("the presented credential was refused")] - Refused, + Refused(FailedCheck), #[error("the issuer key set is unavailable")] KeySource, } +impl AuthError { + /// The check the request failed. + #[must_use] + pub const fn failed_check(&self) -> FailedCheck { + match self { + Self::Refused(check) => *check, + Self::KeySource => FailedCheck::KeySourceUnavailable, + } + } +} + /// Why an authenticator could not be built at startup. #[derive(Debug, thiserror::Error)] pub enum AuthSetupError { @@ -133,18 +143,15 @@ impl TokenAuthenticator { /// Authenticate the value of an `Authorization` header. pub async fn authenticate(&self, authorization: Option<&str>) -> Result { - let header = authorization.ok_or(AuthError::Missing)?; - let token = parse_bearer_token(header).map_err(|_| AuthError::Missing)?; + let header = authorization.ok_or(AuthError::Refused(FailedCheck::CredentialMissing))?; + let token = parse_bearer_token(header).map_err(|error| match error { + BearerParseError::InvalidScheme => AuthError::Refused(FailedCheck::CredentialMissing), + _ => AuthError::Refused(FailedCheck::CredentialMalformed), + })?; let verified = match self.verifier.verify(token).await { Ok(verified) => verified, - Err(error) if is_key_source_failure(&error) => { - tracing::warn!( - target: "registry_evidence_oid4vp::auth", - "the issuer key set is unavailable" - ); - return Err(AuthError::KeySource); - } - Err(_) => return Err(AuthError::Refused), + Err(error) if is_key_source_failure(&error) => return Err(AuthError::KeySource), + Err(error) => return Err(AuthError::Refused(error.failed_check())), }; // The scope gate runs on the verified token's scope set: a correctly // signed token for this audience without the scope grants nothing. @@ -153,7 +160,7 @@ impl TokenAuthenticator { .iter() .any(|scope| scope == &self.required_scope) { - return Err(AuthError::Refused); + return Err(AuthError::Refused(FailedCheck::Scope)); } let client = match verified.matched_client_id() { Ok(Some(client)) => Some(client.to_owned()), @@ -162,12 +169,12 @@ impl TokenAuthenticator { .azp .clone() .or_else(|| verified.claims.client_id.clone()), - Err(_) => return Err(AuthError::Refused), + Err(_) => return Err(AuthError::Refused(FailedCheck::TokenClient)), } .filter(|client| !client.is_empty()); let subject = verified.claims.sub.clone().filter(|sub| !sub.is_empty()); if client.is_none() && subject.is_none() { - return Err(AuthError::Refused); + return Err(AuthError::Refused(FailedCheck::TokenClient)); } Ok(Principal { issuer: verified diff --git a/crates/registry-evidence-oid4vp/src/metrics.rs b/crates/registry-evidence-oid4vp/src/metrics.rs index 7d728733bf..d9533f1fe2 100644 --- a/crates/registry-evidence-oid4vp/src/metrics.rs +++ b/crates/registry-evidence-oid4vp/src/metrics.rs @@ -13,6 +13,7 @@ use axum::{ routing::get, Router, }; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, MetricKind, MetricsError, CONTENT_TYPE as METRICS_TYPE, }; @@ -115,6 +116,7 @@ impl Event { /// The service's counters. pub struct Metrics { events: CounterVec, + refusals: Arc, } impl Metrics { @@ -127,9 +129,17 @@ impl Metrics { "Presentation session, request, response, and read events by outcome.", LabelSpace::closed_zero_filled(&["event"], &declared)?, )?, + refusals: Arc::new(RefusalRecorder::new("evidence_oid4vp")?), }) } + /// The recorder that counts each refused request under its check and + /// admits a bounded number of log lines. + #[must_use] + pub const fn refusal_recorder(&self) -> &Arc { + &self.refusals + } + pub fn record(&self, event: Event) { if self.events.inc(&[event.label()]).is_err() { tracing::error!("a metric event was refused by its closed label space"); @@ -145,6 +155,7 @@ impl Metrics { pub fn render(&self, store: &SessionStore) -> Result { let mut out = Exposition::new(); self.events.write(&mut out)?; + self.refusals.counter().write(&mut out)?; out.header( "evidence_oid4vp_sessions", Some("Presentation sessions held in memory, expired ones not yet cleaned up included."), diff --git a/crates/registry-evidence-oid4vp/src/service.rs b/crates/registry-evidence-oid4vp/src/service.rs index 03c6411459..7a10912c20 100644 --- a/crates/registry-evidence-oid4vp/src/service.rs +++ b/crates/registry-evidence-oid4vp/src/service.rs @@ -23,6 +23,7 @@ use axum::{ Json, Router, }; use chrono::{DateTime, SecondsFormat, Utc}; +use registry_platform_authcommon::{FailedCheck, RefusalNote, RefusalRecorder}; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit, security_headers, CspBuilder, @@ -412,6 +413,7 @@ pub fn build_app(service: Arc) -> Router { .route(RESPONSE_PATH, post(receive_response)) .layer(DefaultBodyLimit::max(response::MAX_BODY_BYTES)) .layer(request_body_limit(response::MAX_BODY_BYTES)); + let refusals = Arc::clone(service.metrics.refusal_recorder()); general .merge(responses) .fallback(unknown_route) @@ -421,6 +423,7 @@ pub fn build_app(service: Arc) -> Router { .layer(from_fn(normalize_rejections)) .layer(security_headers(CspBuilder::deny_by_default())) .layer(from_fn(apply_trace_context)) + .layer(from_fn_with_state(refusals, record_refusals)) } /// The outermost layer: every response, whichever layer or handler produced @@ -500,6 +503,60 @@ fn retry_after(mut response: Response, seconds: u64) -> Response { response } +/// The answer carrying the check that refused the caller in its response +/// extensions, which are never serialized. The recording layer reads it. +fn refused(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + +/// The 401 a caller without an acceptable bearer credential receives. +fn unauthorized(check: FailedCheck) -> Response { + let mut response = problem( + ProblemCode::Unauthorized, + "a valid bearer token is required", + ); + response + .headers_mut() + .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); + refused(response, check) +} + +/// The 503 a caller receives when the issuer's key set cannot be used. +fn issuer_unavailable_answer() -> Response { + refused( + retry_after( + problem( + ProblemCode::IssuerUnavailable, + "the token issuer is unavailable", + ), + 5, + ), + FailedCheck::KeySourceUnavailable, + ) +} + +/// Count each refusal answer under its check and write the admitted log line. +/// The trace id is the one the answer carries. +async fn record_refusals( + State(refusals): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::() { + match registry_platform_httpsec::response_trace_id(response.headers()) { + Ok(trace) => { + registry_platform_authcommon::record_refusal!(refusals, *note, trace_id = trace); + } + Err(_) => { + registry_platform_authcommon::record_refusal!(refusals, *note); + } + } + } + response +} + async fn unknown_route() -> Response { problem(ProblemCode::NotFound, "no such route") } @@ -571,24 +628,11 @@ async fn applicant(service: &VerifierService, headers: &HeaderMap) -> Result Ok(principal), Err(AuthError::KeySource) => { service.metrics.record(Event::SessionRefusedUnavailable); - Err(retry_after( - problem( - ProblemCode::IssuerUnavailable, - "the token issuer is unavailable", - ), - 5, - )) + Err(issuer_unavailable_answer()) } - Err(AuthError::Missing | AuthError::Refused) => { + Err(AuthError::Refused(check)) => { service.metrics.record(Event::SessionRefusedAuthentication); - let mut response = problem( - ProblemCode::Unauthorized, - "a valid bearer token is required", - ); - response - .headers_mut() - .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); - Err(response) + Err(unauthorized(check)) } } } @@ -769,7 +813,10 @@ async fn session_status( } None => { service.metrics.record(Event::StatusNotFound); - problem(ProblemCode::SessionNotFound, "no such session") + refused( + problem(ProblemCode::SessionNotFound, "no such session"), + FailedCheck::Visibility, + ) } } } @@ -869,9 +916,12 @@ fn response_unavailable(wait_seconds: u64) -> Response { async fn admit_response(limiter: &TokenBucketLimiter, key: &str) -> Result<(), Response> { match limiter.check(key, 1).await { Ok(()) => Ok(()), - Err(TokenBucketError::Exceeded { retry_after: wait }) => Err(retry_after( - oauth_error(StatusCode::TOO_MANY_REQUESTS, "temporarily_unavailable"), - wait.as_secs() + 1, + Err(TokenBucketError::Exceeded { retry_after: wait }) => Err(refused( + retry_after( + oauth_error(StatusCode::TOO_MANY_REQUESTS, "temporarily_unavailable"), + wait.as_secs() + 1, + ), + FailedCheck::RateLimit, )), Err(_) => Err(response_unavailable(CAPACITY_RETRY_SECONDS)), } @@ -1154,24 +1204,11 @@ async fn read_presentation( Ok(reader) => reader, Err(AuthError::KeySource) => { service.metrics.record(Event::ReadUnavailable); - return retry_after( - problem( - ProblemCode::IssuerUnavailable, - "the token issuer is unavailable", - ), - 5, - ); + return issuer_unavailable_answer(); } - Err(AuthError::Missing | AuthError::Refused) => { + Err(AuthError::Refused(check)) => { service.metrics.record(Event::ReadRefusedAuthentication); - let mut response = problem( - ProblemCode::Unauthorized, - "a valid bearer token is required", - ); - response - .headers_mut() - .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); - return response; + return unauthorized(check); } }; if let Err(response) = admit( @@ -1251,10 +1288,17 @@ async fn read_presentation( match verdict { // A principal that is not the creator reads exactly as an unknown // reference. - ReadVerdict::NotFound | ReadVerdict::PrincipalMismatch => { + ReadVerdict::NotFound => { service.metrics.record(Event::ReadNotFound); problem(ProblemCode::SessionNotFound, "no such session") } + ReadVerdict::PrincipalMismatch => { + service.metrics.record(Event::ReadNotFound); + refused( + problem(ProblemCode::SessionNotFound, "no such session"), + FailedCheck::Ownership, + ) + } ReadVerdict::Pending => { service.metrics.record(Event::ReadPending); problem( @@ -1331,19 +1375,22 @@ async fn admit( limiter: &TokenBucketLimiter, key: &str, metrics: &Metrics, - refused: Event, + event: Event, ) -> Result<(), Response> { match limiter.check(key, 1).await { Ok(()) => Ok(()), Err(TokenBucketError::Exceeded { retry_after: wait }) => { - metrics.record(refused); - Err(retry_after( - problem(ProblemCode::RateLimited, "too many requests; retry later"), - wait.as_secs() + 1, + metrics.record(event); + Err(refused( + retry_after( + problem(ProblemCode::RateLimited, "too many requests; retry later"), + wait.as_secs() + 1, + ), + FailedCheck::RateLimit, )) } Err(_) => { - metrics.record(refused); + metrics.record(event); Err(retry_after( problem(ProblemCode::Capacity, "the service is at capacity"), CAPACITY_RETRY_SECONDS, diff --git a/crates/registry-evidence-oid4vp/tests/golden/refusals.json b/crates/registry-evidence-oid4vp/tests/golden/refusals.json new file mode 100644 index 0000000000..72d8ba3f91 --- /dev/null +++ b/crates/registry-evidence-oid4vp/tests/golden/refusals.json @@ -0,0 +1,250 @@ +{ + "create-garbage-token": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "create-no-header": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "create-non-bearer-scheme": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "create-rate-limited": { + "body": { + "detail": "too many requests; retry later", + "status": 429, + "title": "Too Many Requests", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/rate-limited" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "", + "x-content-type-options": "nosniff" + }, + "status": 429 + }, + "create-wrong-scope": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "read-another-principal": { + "body": { + "detail": "no such session", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/session-not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "status": 404 + }, + "read-client-not-allowed": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "read-garbage-token": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "read-no-header": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "read-rate-limited": { + "body": { + "detail": "too many requests; retry later", + "status": 429, + "title": "Too Many Requests", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/rate-limited" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "", + "x-content-type-options": "nosniff" + }, + "status": 429 + }, + "read-unknown-reference": { + "body": { + "detail": "no such session", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/session-not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "status": 404 + }, + "read-wrong-scope": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "request-rate-limited": { + "body": { + "detail": "too many requests; retry later", + "status": 429, + "title": "Too Many Requests", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/rate-limited" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "", + "x-content-type-options": "nosniff" + }, + "status": 429 + }, + "response-rate-limited": { + "body": { + "error": "temporarily_unavailable" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "retry-after": "", + "x-content-type-options": "nosniff" + }, + "status": 429 + }, + "status-another-principal": { + "body": { + "detail": "no such session", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/session-not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "status": 404 + }, + "status-no-header": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "status-unknown-reference": { + "body": { + "detail": "no such session", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/session-not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "status": 404 + } +} diff --git a/crates/registry-evidence-oid4vp/tests/refusal_golden.rs b/crates/registry-evidence-oid4vp/tests/refusal_golden.rs new file mode 100644 index 0000000000..9082c4c13b --- /dev/null +++ b/crates/registry-evidence-oid4vp/tests/refusal_golden.rs @@ -0,0 +1,270 @@ +//! The refusals a caller can provoke, answered through the whole router and +//! frozen in `tests/golden/refusals.json`. Each answer is its status, the +//! headers a caller or proxy acts on, and the body without its per-request +//! trace id. Run with `REGISTRY_OID4VP_WRITE_GOLDEN=1` to rewrite the file. + +mod common; + +use std::path::Path; + +use axum_test::{TestResponse, TestServer}; +use common::{bearer, Harness, Options}; +use serde_json::{json, Map, Value}; + +const HEADERS: [&str; 5] = [ + "content-type", + "www-authenticate", + "cache-control", + "retry-after", + "x-content-type-options", +]; + +/// The answer as the golden freezes it. A `retry-after` on a 429 is the +/// bucket's remaining wait, which moves with the clock, so only its presence +/// is frozen there. +fn frozen(response: &TestResponse) -> Value { + let status = response.status_code().as_u16(); + let mut headers = Map::new(); + for name in HEADERS { + if let Some(value) = response.maybe_header(name) { + let text = value.to_str().expect("ASCII header").to_owned(); + let text = if name == "retry-after" && status == 429 { + "".to_owned() + } else { + text + }; + headers.insert(name.to_owned(), text.into()); + } + } + let mut body: Value = serde_json::from_slice(response.as_bytes()).expect("a JSON body"); + if let Some(object) = body.as_object_mut() { + object.remove("traceId"); + } + json!({"status": status, "headers": headers, "body": body}) +} + +async fn create(server: &TestServer, authorization: Option<&str>) -> TestResponse { + let mut request = server.post("/v1/sessions"); + if let Some(value) = authorization { + request = request.add_header("authorization", value.to_owned()); + } + request.json(&json!({"policy": "national-id"})).await +} + +async fn status_of( + server: &TestServer, + reference: &str, + authorization: Option<&str>, +) -> TestResponse { + let mut request = server.get(&format!("/v1/sessions/{reference}")); + if let Some(value) = authorization { + request = request.add_header("authorization", value.to_owned()); + } + request.await +} + +async fn read( + server: &TestServer, + authorization: Option<&str>, + reference: &str, + issuer: &str, + subject: &str, +) -> TestResponse { + let mut request = server.post("/v1/presentations/read"); + if let Some(value) = authorization { + request = request.add_header("authorization", value.to_owned()); + } + request + .json(&json!({ + "reference": reference, + "principal": {"issuer": issuer, "subject": subject}, + })) + .await +} + +/// Every refusal case, in a fixed order, answered by a fresh deployment where +/// the case needs a spent budget. +async fn answers() -> Value { + let mut answers = Map::new(); + let mut put = |name: &str, response: &TestResponse| { + answers.insert(name.to_owned(), frozen(response)); + }; + + let harness = Harness::new(&Options::default()).await; + let (server, _) = harness.server().await; + let issuer = harness.idp.issuer().to_string(); + let creator = harness.applicant_token("portal", "user-1"); + let created: Value = server + .post("/v1/sessions") + .add_header("authorization", bearer(&creator)) + .json(&json!({"policy": "national-id"})) + .await + .json(); + let reference = created["reference"].as_str().expect("reference").to_owned(); + + put("create-no-header", &create(&server, None).await); + put( + "create-non-bearer-scheme", + &create(&server, Some("Basic dXNlcjpwYXNz")).await, + ); + put( + "create-garbage-token", + &create(&server, Some("Bearer not-a-token")).await, + ); + let unscoped = harness.token("portal", "user-1", "something:else"); + put( + "create-wrong-scope", + &create(&server, Some(&bearer(&unscoped))).await, + ); + + put( + "status-no-header", + &status_of(&server, &reference, None).await, + ); + put( + "status-unknown-reference", + &status_of(&server, &"A".repeat(43), Some(&bearer(&creator))).await, + ); + let other = harness.applicant_token("portal", "user-2"); + put( + "status-another-principal", + &status_of(&server, &reference, Some(&bearer(&other))).await, + ); + + put( + "read-no-header", + &read(&server, None, &reference, &issuer, "user-1").await, + ); + put( + "read-garbage-token", + &read( + &server, + Some("Bearer not-a-token"), + &reference, + &issuer, + "user-1", + ) + .await, + ); + let applicant_as_reader = harness.token("portal", "user-1", "oid4vp:read-result"); + put( + "read-client-not-allowed", + &read( + &server, + Some(&bearer(&applicant_as_reader)), + &reference, + &issuer, + "user-1", + ) + .await, + ); + let reader_wrong_scope = harness.token("evidence", "evidence-service", "something:else"); + put( + "read-wrong-scope", + &read( + &server, + Some(&bearer(&reader_wrong_scope)), + &reference, + &issuer, + "user-1", + ) + .await, + ); + let reader = harness.evidence_token(); + put( + "read-another-principal", + &read( + &server, + Some(&bearer(&reader)), + &reference, + &issuer, + "user-2", + ) + .await, + ); + put( + "read-unknown-reference", + &read( + &server, + Some(&bearer(&reader)), + &"B".repeat(43), + &issuer, + "user-1", + ) + .await, + ); + + // Spent budgets, each in a deployment whose burst is one. + let limited = Harness::new(&Options { + session_creation_burst: 1, + wallet_request_burst: 1, + wallet_response_burst: 1, + evidence_read_burst: 1, + ..Options::default() + }) + .await; + let (server, _) = limited.server().await; + let token = limited.applicant_token("portal", "user-1"); + let first = create(&server, Some(&bearer(&token))).await; + assert_eq!(first.status_code().as_u16(), 201); + put( + "create-rate-limited", + &create(&server, Some(&bearer(&token))).await, + ); + let first = server.get("/v1/requests/unknown").await; + assert_eq!(first.status_code().as_u16(), 404); + put( + "request-rate-limited", + &server.get("/v1/requests/unknown").await, + ); + let issuer = limited.idp.issuer().to_string(); + let reader = limited.evidence_token(); + let first = read( + &server, + Some(&bearer(&reader)), + &"C".repeat(43), + &issuer, + "user-1", + ) + .await; + assert_eq!(first.status_code().as_u16(), 404); + put( + "read-rate-limited", + &read( + &server, + Some(&bearer(&reader)), + &"C".repeat(43), + &issuer, + "user-1", + ) + .await, + ); + let form = |server: &TestServer| { + server + .post("/v1/responses/unknown") + .content_type("application/x-www-form-urlencoded") + .text("response=x") + }; + let first = form(&server).await; + assert_eq!(first.status_code().as_u16(), 400); + put("response-rate-limited", &form(&server).await); + + Value::Object(answers) +} + +#[tokio::test] +async fn refusal_answers_match_the_golden() { + let actual = answers().await; + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusals.json"); + if std::env::var_os("REGISTRY_OID4VP_WRITE_GOLDEN").is_some() { + std::fs::create_dir_all(path.parent().expect("parent")).expect("golden directory"); + std::fs::write( + &path, + format!("{}\n", serde_json::to_string_pretty(&actual).expect("json")), + ) + .expect("write golden"); + } + let expected: Value = + serde_json::from_slice(&std::fs::read(&path).expect("golden file")).expect("golden json"); + assert_eq!(actual, expected); +} diff --git a/crates/registry-evidence-oid4vp/tests/refusal_recording.rs b/crates/registry-evidence-oid4vp/tests/refusal_recording.rs new file mode 100644 index 0000000000..11bb320df9 --- /dev/null +++ b/crates/registry-evidence-oid4vp/tests/refusal_recording.rs @@ -0,0 +1,373 @@ +//! Every refusal the service answers is counted in +//! `evidence_oid4vp_request_refusals_total{check}` and written as one +//! `request refused` line that carries the check and no caller value. +//! +//! The log subscriber is process-wide (see `certificate_expiry_log.rs` for +//! why a thread-scoped one is not reliable), so this binary holds one test. + +mod common; + +use std::{ + future::IntoFuture, + sync::{Arc, Mutex}, +}; + +use axum_test::{TestResponse, TestServer}; +use common::{bearer, Harness, Options}; +use registry_evidence_oid4vp::service::VerifierService; +use registry_platform_authcommon::FailedCheck; +use serde_json::{json, Value}; + +#[derive(Clone, Default)] +struct LogBuffer(Arc>>); + +impl std::io::Write for LogBuffer { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogBuffer { + type Writer = Self; + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } +} + +impl LogBuffer { + fn text(&self) -> String { + String::from_utf8(self.0.lock().unwrap().clone()).unwrap() + } +} + +fn count(service: &VerifierService, check: FailedCheck) -> u64 { + service + .metrics() + .refusal_recorder() + .counter() + .get(&[check.as_str()]) + .expect("every check is declared") +} + +fn total(service: &VerifierService) -> u64 { + FailedCheck::ALL + .iter() + .map(|check| count(service, *check)) + .sum() +} + +/// What a caller sent that must never reach a log line. +struct Canaries(Vec); + +/// Run one request and require that exactly its member moved by one, that +/// one new log line names it, and that no canary reached the log. +async fn expect( + service: &VerifierService, + logs: &LogBuffer, + canaries: &Canaries, + check: FailedCheck, + status: u16, + request: impl std::future::Future, +) { + let (before, lines_before, total_before) = ( + count(service, check), + logs.text() + .matches(&format!("failed_check=\"{}\"", check.as_str())) + .count() + + logs + .text() + .matches(&format!("failed_check={}", check.as_str())) + .count(), + total(service), + ); + let response = request.await; + assert_eq!(response.status_code().as_u16(), status, "{check:?}"); + assert_eq!(count(service, check), before + 1, "{check:?}"); + assert_eq!( + total(service), + total_before + 1, + "{check:?} moved another member" + ); + let text = logs.text(); + let lines_after = text + .matches(&format!("failed_check=\"{}\"", check.as_str())) + .count() + + text + .matches(&format!("failed_check={}", check.as_str())) + .count(); + assert_eq!(lines_after, lines_before + 1, "{check:?}\n{text}"); + for canary in &canaries.0 { + assert!( + !text.contains(canary.as_str()), + "the log carries a caller value" + ); + } +} + +#[tokio::test] +async fn each_refusal_is_counted_and_logged_under_its_check() { + let logs = LogBuffer::default(); + tracing::subscriber::set_global_default( + tracing_subscriber::fmt() + .with_writer(logs.clone()) + .with_ansi(false) + .finish(), + ) + .expect("this binary installs one log subscriber"); + + let harness = Harness::new(&Options::default()).await; + let (server, service) = harness.server().await; + // Nothing is counted before a refusal, and every member is declared. + for check in FailedCheck::ALL { + assert_eq!(count(&service, check), 0); + } + let issuer = harness.idp.issuer().to_string(); + let creator = harness.applicant_token("portal", "user-1"); + let other = harness.applicant_token("portal", "user-2"); + let unscoped = harness.token("portal", "user-1", "something:else"); + let reader = harness.evidence_token(); + let applicant_as_reader = harness.token("portal", "user-1", "oid4vp:read-result"); + let reader_wrong_scope = harness.token("evidence", "evidence-service", "something:else"); + let canaries = Canaries(vec![ + creator.clone(), + other.clone(), + unscoped.clone(), + reader.clone(), + "user-1".to_owned(), + "user-2".to_owned(), + "portal".to_owned(), + "canary-token-7f3a".to_owned(), + ]); + let created: Value = server + .post("/v1/sessions") + .add_header("authorization", bearer(&creator)) + .json(&json!({"policy": "national-id"})) + .await + .json(); + let reference = created["reference"].as_str().unwrap().to_owned(); + + let create = |authorization: Option| { + let mut request = server.post("/v1/sessions"); + if let Some(value) = authorization { + request = request.add_header("authorization", value); + } + request.json(&json!({"policy": "national-id"})) + }; + let status = |reference: String, authorization: Option| { + let mut request = server.get(&format!("/v1/sessions/{reference}")); + if let Some(value) = authorization { + request = request.add_header("authorization", value); + } + request + }; + let read = |authorization: Option, reference: String, subject: &str| { + let mut request = server.post("/v1/presentations/read"); + if let Some(value) = authorization { + request = request.add_header("authorization", value); + } + request.json(&json!({ + "reference": reference, + "principal": {"issuer": issuer, "subject": subject}, + })) + }; + + let (s, l, c) = (&service, &logs, &canaries); + expect( + s, + l, + c, + FailedCheck::CredentialMissing, + 401, + create(None).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMissing, + 401, + create(Some("Basic dXNlcjpwYXNz".to_owned())).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMalformed, + 401, + create(Some("Bearer canary-token-7f3a".to_owned())).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Scope, + 401, + create(Some(bearer(&unscoped))).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMissing, + 401, + status(reference.clone(), None).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Visibility, + 404, + status("A".repeat(43), Some(bearer(&creator))).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Visibility, + 404, + status(reference.clone(), Some(bearer(&other))).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMissing, + 401, + read(None, reference.clone(), "user-1").into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMalformed, + 401, + read( + Some("Bearer canary-token-7f3a".to_owned()), + reference.clone(), + "user-1", + ) + .into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::TokenClient, + 401, + read( + Some(bearer(&applicant_as_reader)), + reference.clone(), + "user-1", + ) + .into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Scope, + 401, + read( + Some(bearer(&reader_wrong_scope)), + reference.clone(), + "user-1", + ) + .into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Ownership, + 404, + read(Some(bearer(&reader)), reference.clone(), "user-2").into_future(), + ) + .await; + + // A read of a reference nobody holds is not recorded: the consult maps + // only another principal's session. + let before = total(&service); + let absent = read(Some(bearer(&reader)), "B".repeat(43), "user-1").await; + assert_eq!(absent.status_code().as_u16(), 404); + assert_eq!(total(&service), before); + + // Spent budgets, each in a deployment whose burst is one. + let limited = Harness::new(&Options { + session_creation_burst: 1, + wallet_request_burst: 1, + wallet_response_burst: 1, + evidence_read_burst: 1, + ..Options::default() + }) + .await; + let (server, service) = limited.server().await; + let token = limited.applicant_token("portal", "user-1"); + let reader = limited.evidence_token(); + let issuer = limited.idp.issuer().to_string(); + let create = || { + server + .post("/v1/sessions") + .add_header("authorization", bearer(&token)) + .json(&json!({"policy": "national-id"})) + }; + let first = create().await; + assert_eq!(first.status_code().as_u16(), 201); + let (s, l) = (&service, &logs); + expect(s, l, c, FailedCheck::RateLimit, 429, create().into_future()).await; + server + .get("/v1/requests/unknown") + .await + .assert_status_not_found(); + expect( + s, + l, + c, + FailedCheck::RateLimit, + 429, + server.get("/v1/requests/unknown").into_future(), + ) + .await; + let read = || { + server + .post("/v1/presentations/read") + .add_header("authorization", bearer(&reader)) + .json(&json!({ + "reference": "C".repeat(43), + "principal": {"issuer": issuer, "subject": "user-1"}, + })) + }; + read().await.assert_status_not_found(); + expect(s, l, c, FailedCheck::RateLimit, 429, read().into_future()).await; + let form = |server: &TestServer| { + server + .post("/v1/responses/unknown") + .content_type("application/x-www-form-urlencoded") + .text("response=x") + }; + form(&server).await.assert_status_bad_request(); + expect( + s, + l, + c, + FailedCheck::RateLimit, + 429, + form(&server).into_future(), + ) + .await; +} diff --git a/crates/registry-evidence/Cargo.toml b/crates/registry-evidence/Cargo.toml index 09bbbe1829..31e3c74917 100644 --- a/crates/registry-evidence/Cargo.toml +++ b/crates/registry-evidence/Cargo.toml @@ -50,11 +50,11 @@ registry-evidence-client.workspace = true registry-discovery-profile.workspace = true p256.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-crypto = { workspace = true, features = ["transit"] } registry-platform-config.workspace = true -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-metrics.workspace = true registry-platform-httputil.workspace = true registry-platform-oidc.workspace = true diff --git a/crates/registry-evidence/src/auth.rs b/crates/registry-evidence/src/auth.rs index 6b0312db45..09a815441d 100644 --- a/crates/registry-evidence/src/auth.rs +++ b/crates/registry-evidence/src/auth.rs @@ -7,7 +7,7 @@ use std::{ #[cfg(test)] use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ actor_kind, grant_claims, ActorKind, Audience, ClaimError, ClaimNames, GrantClaims, @@ -234,18 +234,38 @@ impl std::fmt::Debug for AuthenticatedContext { } } +/// Why a bearer token was refused. Every variant names the check that failed, +/// so the operator-side count and log line can say which of the checks it was. +/// The caller sees one closed `401` whichever variant this is. #[derive(Debug, Error)] pub enum AuthenticationError { #[error("access token is malformed")] Malformed, #[error("access token verification failed")] - Verification, + Verification(FailedCheck), #[error("required authenticated context is missing or invalid")] - Context, + Context(FailedCheck), #[error("access token is bound to a sender proof this profile cannot validate")] SenderConstrained, } +impl AuthenticationError { + /// The check this refusal failed. Written to no response. + #[deny(clippy::wildcard_enum_match_arm)] + pub fn failed_check(&self) -> FailedCheck { + match self { + Self::Malformed => FailedCheck::CredentialMalformed, + Self::Verification(check) | Self::Context(check) => *check, + Self::SenderConstrained => FailedCheck::SenderConstraint, + } + } + + /// A required claim is absent or not in its configured shape. + fn claims() -> Self { + Self::Context(FailedCheck::TokenClaims) + } +} + /// RFC 7800 confirmation claim. Its presence means the authorization server /// issued a token that is only valid when presented with a matching proof of /// possession, such as DPoP or mutual TLS. @@ -353,7 +373,7 @@ impl Authenticator { if is_key_source_failure(&error) { self.report_key_source_failure(&error); } - return Err(AuthenticationError::Verification); + return Err(AuthenticationError::Verification(error.failed_check())); } }; // The scope gate reads only the verified token's scope set. It runs @@ -371,7 +391,7 @@ impl Authenticator { .iter() .all(|scope| present.contains(scope.as_str())) { - return Err(AuthenticationError::Verification); + return Err(AuthenticationError::Verification(FailedCheck::Scope)); } } self.extract_context(verified) @@ -521,17 +541,17 @@ impl Authenticator { verified: VerifiedToken, ) -> Result { let actor_kind = actor_kind(&verified.claims, &self.claims.contextual_claims) - .map_err(|_| AuthenticationError::Context)?; + .map_err(|_| AuthenticationError::Context(FailedCheck::ActorKind))?; let now_unix = SystemTime::now() .duration_since(UNIX_EPOCH) - .map_err(|_| AuthenticationError::Context)? + .map_err(|_| AuthenticationError::Context(FailedCheck::TokenTime))? .as_secs(); let mut task_grant = grant_claims(&verified.claims, &self.claims.contextual_claims, now_unix) .map_err(|_: ClaimError| TaskGrantError::Claims); let claims = - serde_json::to_value(&verified.claims).map_err(|_| AuthenticationError::Context)?; - let claims_object = claims.as_object().ok_or(AuthenticationError::Context)?; + serde_json::to_value(&verified.claims).map_err(|_| AuthenticationError::claims())?; + let claims_object = claims.as_object().ok_or_else(AuthenticationError::claims)?; // Retain a bounded identifier from the verified token for denial audit // even when expiry or another grant member fails validation. This is // never an authorization input and is emitted only as a keyed pseudonym. @@ -563,7 +583,7 @@ impl Authenticator { &self.claims.evidence_audience_claim, MAX_PRINCIPAL_BYTES, )?; - url::Url::parse(&evidence_audience).map_err(|_| AuthenticationError::Context)?; + url::Url::parse(&evidence_audience).map_err(|_| AuthenticationError::claims())?; let requester_tags = required_string_array(claims_object, &self.claims.requester_tags_claim, MAX_TAGS)?; let actor = self @@ -719,7 +739,7 @@ fn required_direct_string( name: &str, maximum_bytes: usize, ) -> Result { - optional_direct_string(claims, name, maximum_bytes)?.ok_or(AuthenticationError::Context) + optional_direct_string(claims, name, maximum_bytes)?.ok_or_else(AuthenticationError::claims) } fn optional_direct_string( @@ -730,9 +750,9 @@ fn optional_direct_string( let Some(value) = claims.get(name) else { return Ok(None); }; - let value = value.as_str().ok_or(AuthenticationError::Context)?; + let value = value.as_str().ok_or_else(AuthenticationError::claims)?; if value.is_empty() || value.len() > maximum_bytes { - return Err(AuthenticationError::Context); + return Err(AuthenticationError::claims()); } Ok(Some(value.to_owned())) } @@ -745,15 +765,15 @@ fn required_string_array( let values = claims .get(name) .and_then(Value::as_array) - .ok_or(AuthenticationError::Context)?; + .ok_or_else(AuthenticationError::claims)?; if values.is_empty() || values.len() > maximum_items { - return Err(AuthenticationError::Context); + return Err(AuthenticationError::claims()); } let mut output = Vec::with_capacity(values.len()); for value in values { - let value = value.as_str().ok_or(AuthenticationError::Context)?; + let value = value.as_str().ok_or_else(AuthenticationError::claims)?; if value.is_empty() || value.len() > MAX_PRINCIPAL_BYTES { - return Err(AuthenticationError::Context); + return Err(AuthenticationError::claims()); } output.push(value.to_owned()); } @@ -1217,7 +1237,10 @@ mod tests { }) .expect_err("a token without registry_actor_kind is refused"); - assert!(matches!(error, AuthenticationError::Context)); + assert!(matches!( + error, + AuthenticationError::Context(FailedCheck::ActorKind) + )); } #[test] diff --git a/crates/registry-evidence/src/observability.rs b/crates/registry-evidence/src/observability.rs index 38ccbb7576..e779b66fd1 100644 --- a/crates/registry-evidence/src/observability.rs +++ b/crates/registry-evidence/src/observability.rs @@ -44,6 +44,7 @@ use axum::{ routing::get, Router, }; +use registry_platform_authcommon::{record_refusal, RefusalNote, RefusalRecorder}; use registry_platform_httpsec::{TraceContext, TraceId}; use registry_platform_metrics::{ Exposition, HistogramSnapshot, MetricKind, SumCountOrder, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -153,6 +154,25 @@ pub(crate) fn operation_id(extensions: &axum::http::Extensions) -> OperationId { ) } +/// Whether a public problem code is a refusal the check counter covers: the +/// authentication, authorization and rate-limit answers. +#[deny(clippy::wildcard_enum_match_arm)] +pub(crate) fn is_refusal_code(code: ProblemCode) -> bool { + match code { + ProblemCode::AuthenticationFailed + | ProblemCode::NotAuthorized + | ProblemCode::RateLimited => true, + ProblemCode::MalformedRequest + | ProblemCode::InvalidRequestNonce + | ProblemCode::InvalidSelector + | ProblemCode::ResponseFormatNotAcceptable + | ProblemCode::EvidenceNotAvailable + | ProblemCode::DependencyUnavailable + | ProblemCode::ServiceUnavailable + | ProblemCode::ResourceNotFound => false, + } +} + /// Coarse outcome class. Operational records report the class, never the exact /// status, because the exact status of a denial is part of the closed public /// problem contract rather than an operational signal. @@ -212,6 +232,7 @@ pub(crate) async fn observe( .get::() .map_or(NO_CATEGORY, |category| category.0); operation.apply_trace(response.headers_mut()); + record_response_refusal(&metrics, &response, &operation); metrics.record(route, method, status, error, elapsed); tracing::info!( @@ -228,6 +249,34 @@ pub(crate) async fn observe( response } +/// Count and log the refusal a response carries, once, at the single point +/// every route passes. +/// +/// The note is in the response extensions, which are not serialized, so this +/// reads nothing a caller was given. A refusal code that arrives without a note +/// is a defect in the code that built it: it is reported, not counted under a +/// check it never named. +fn record_response_refusal(metrics: &Metrics, response: &Response, operation: &OperationId) { + match response.extensions().get::() { + Some(note) => { + record_refusal!(metrics.refusals, *note, trace_id = operation.trace_id()); + } + None => { + if response + .extensions() + .get::() + .is_some_and(|code| is_refusal_code(*code)) + { + tracing::error!( + target: "registry_evidence::refusal", + trace_id = operation.trace_id().as_str(), + "a refusal was answered without the check that failed" + ); + } + } + } +} + /// Choose the W3C trace for one request. /// /// Every route continues a valid inbound `traceparent` except the public @@ -280,7 +329,6 @@ fn duration_milliseconds(elapsed: Duration) -> u64 { /// /// Series are keyed only by the closed label set above, so the registry is /// bounded by the route table regardless of traffic and needs no eviction. -#[derive(Default)] pub(crate) struct Metrics { series: Mutex>, /// Current count of pseudonym keys tracked by the rate limiter, for the @@ -297,6 +345,21 @@ pub(crate) struct Metrics { /// The per-source counters the runtime's source executors increment. /// `None` for registries built without a runtime. source_diagnostics: Option>, + /// Counts refusals by the check that failed and bounds the log lines they + /// write. Keyed by no request value. + refusals: RefusalRecorder, +} + +impl Default for Metrics { + fn default() -> Self { + Self { + series: Mutex::default(), + rate_limiter_tracked_keys: AtomicUsize::default(), + rate_limiter: None, + source_diagnostics: None, + refusals: RefusalRecorder::new("evidence").expect(DECLARATION), + } + } } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] @@ -426,6 +489,7 @@ impl Metrics { self.rate_limiter_tracked_keys.load(Ordering::Relaxed), ) .expect(DECLARATION); + self.refusals.counter().write(&mut out).expect(DECLARATION); if let Some(source_diagnostics) = &self.source_diagnostics { source_diagnostics.render(&mut out); } diff --git a/crates/registry-evidence/src/observability/golden-scrape.txt b/crates/registry-evidence/src/observability/golden-scrape.txt index 298e7270f0..89d3c341d6 100644 --- a/crates/registry-evidence/src/observability/golden-scrape.txt +++ b/crates/registry-evidence/src/observability/golden-scrape.txt @@ -70,6 +70,53 @@ evidence_http_request_duration_seconds_count{route="unmatched",method="other",st # HELP evidence_rate_limiter_tracked_keys Pseudonym keys currently tracked by the rate limiter. # TYPE evidence_rate_limiter_tracked_keys gauge evidence_rate_limiter_tracked_keys 5 +# HELP evidence_request_refusals_total Requests refused, by the check that failed. +# TYPE evidence_request_refusals_total counter +evidence_request_refusals_total{check="credential-missing"} 0 +evidence_request_refusals_total{check="credential-malformed"} 0 +evidence_request_refusals_total{check="token-algorithm"} 0 +evidence_request_refusals_total{check="token-type"} 0 +evidence_request_refusals_total{check="token-key"} 0 +evidence_request_refusals_total{check="token-signature"} 0 +evidence_request_refusals_total{check="token-issuer"} 0 +evidence_request_refusals_total{check="token-audience"} 0 +evidence_request_refusals_total{check="token-time"} 0 +evidence_request_refusals_total{check="token-client"} 0 +evidence_request_refusals_total{check="token-assertion-issuer"} 0 +evidence_request_refusals_total{check="token-claims"} 0 +evidence_request_refusals_total{check="actor-kind"} 0 +evidence_request_refusals_total{check="delegation"} 0 +evidence_request_refusals_total{check="sender-constraint"} 0 +evidence_request_refusals_total{check="key-source-unavailable"} 0 +evidence_request_refusals_total{check="shared-secret"} 0 +evidence_request_refusals_total{check="one-time-credential"} 0 +evidence_request_refusals_total{check="delivery-signature"} 0 +evidence_request_refusals_total{check="delivery-freshness"} 0 +evidence_request_refusals_total{check="delivery-binding"} 0 +evidence_request_refusals_total{check="host-origin"} 0 +evidence_request_refusals_total{check="scope"} 0 +evidence_request_refusals_total{check="access-profile"} 0 +evidence_request_refusals_total{check="requester-client"} 0 +evidence_request_refusals_total{check="purpose"} 0 +evidence_request_refusals_total{check="operation"} 0 +evidence_request_refusals_total{check="disclosure"} 0 +evidence_request_refusals_total{check="subject-selector"} 0 +evidence_request_refusals_total{check="revision-pin"} 0 +evidence_request_refusals_total{check="acquisition-channel"} 0 +evidence_request_refusals_total{check="source-authority"} 0 +evidence_request_refusals_total{check="separation-of-duties"} 0 +evidence_request_refusals_total{check="task-grant-missing"} 0 +evidence_request_refusals_total{check="task-grant-claims"} 0 +evidence_request_refusals_total{check="task-grant-expired"} 0 +evidence_request_refusals_total{check="task-grant-binding"} 0 +evidence_request_refusals_total{check="task-grant-scope"} 0 +evidence_request_refusals_total{check="task-grant-lifetime"} 0 +evidence_request_refusals_total{check="task-grant-status"} 0 +evidence_request_refusals_total{check="row-boundary"} 0 +evidence_request_refusals_total{check="ownership"} 0 +evidence_request_refusals_total{check="visibility"} 0 +evidence_request_refusals_total{check="action-guard"} 0 +evidence_request_refusals_total{check="rate-limit"} 0 # HELP evidence_build_info Running version and captured governed identities. # TYPE evidence_build_info gauge evidence_build_info{version="{VERSION}",bundle="bundle\"x\\y\nz",authority="package"} 1 diff --git a/crates/registry-evidence/src/refusal_recording_tests.rs b/crates/registry-evidence/src/refusal_recording_tests.rs new file mode 100644 index 0000000000..92d02e9409 --- /dev/null +++ b/crates/registry-evidence/src/refusal_recording_tests.rs @@ -0,0 +1,520 @@ +//! Every refusal the Evidence boundary answers with 401, 403 or 429 is counted +//! under the check that failed, logged once with that check, and answered with +//! the bytes it has always had. +//! +//! The golden file holds each answer's status, headers and body (minus the +//! per-request trace id). It was written from the tree before the check was +//! threaded through, so a pass proves no refusal answer changed. +//! `REGISTRY_EVIDENCE_WRITE_GOLDEN=1` rewrites it. + +use super::*; +use registry_platform_authcommon::FailedCheck; + +const GOLDEN: &str = "tests/golden/refusal_answers.json"; +const TOKEN_CANARY: &str = "refusal-token-canary-value"; +const CLIENT_CANARY: &str = "refusal-client-canary-value"; + +/// What the request carries besides its route. +enum Credential { + Absent, + Header(&'static str), + Repeated, + Token(String), +} + +struct Scenario { + name: &'static str, + method: &'static str, + route: &'static str, + credential: Credential, + accept: Option<&'static str>, + body: Option, + status: StatusCode, + check: FailedCheck, +} + +fn evidence( + name: &'static str, + credential: Credential, + body: EvidenceRequest, + status: StatusCode, + check: FailedCheck, +) -> Scenario { + Scenario { + name, + method: "POST", + route: "/v1/evidence", + credential, + accept: None, + body: Some(body), + status, + check, + } +} + +fn claims_without(removed: &[&str], replaced: Value) -> Value { + let now = Utc::now().timestamp(); + let mut claims = json!({ + "iss": TOKEN_ISSUER, + "aud": TOKEN_AUDIENCE, + "sub": "requester-principal-canary", + "iat": now - 1, + "exp": now + 298, + "client_id": "evidence-task-agent", + "registry_actor_kind": "service", + "evidence_tags": ["fixture-agency"], + "evidence_audience": EVIDENCE_AUDIENCE + }); + let object = claims.as_object_mut().expect("claims are an object"); + for name in removed { + object.remove(*name); + } + object.extend( + replaced + .as_object() + .expect("replacements are an object") + .clone(), + ); + claims +} + +/// A well-formed token whose signature segment is not the signature of its +/// payload. +fn token_with_tampered_signature() -> String { + let token = access_token(None); + let (signing_input, _) = token.rsplit_once('.').expect("a compact token"); + format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode([0u8; 64])) +} + +/// A token whose header names a key the verifier does not hold. +fn token_with_unknown_key() -> String { + let token = access_token(None); + let mut segments = token.split('.'); + let _ = segments.next(); + let header = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&json!({"alg": "ES256", "kid": "unknown-key", "typ": "at+jwt"})) + .expect("header serializes"), + ); + format!( + "{header}.{}.{}", + segments.next().expect("payload"), + segments.next().expect("signature") + ) +} + +fn scenarios() -> Vec { + let now = Utc::now().timestamp(); + let adult = adult_request; + let mut wrong_purpose = adult_request(); + wrong_purpose.purpose = "no-such-purpose".to_owned(); + let mut unknown_profile = adult_request(); + unknown_profile.subjects[0].selector.profile = "no-such-profile".to_owned(); + let mut pinned = adult_request(); + pinned.expected_configuration_revision = Some(format!("sha256:{}", "0".repeat(64))); + let unauthorized = StatusCode::UNAUTHORIZED; + let forbidden = StatusCode::FORBIDDEN; + vec![ + evidence( + "no-authorization-header", + Credential::Absent, + adult(), + unauthorized, + FailedCheck::CredentialMissing, + ), + evidence( + "non-bearer-scheme", + Credential::Header("Basic abc"), + adult(), + unauthorized, + FailedCheck::CredentialMissing, + ), + evidence( + "repeated-authorization-header", + Credential::Repeated, + adult(), + unauthorized, + FailedCheck::CredentialMalformed, + ), + evidence( + "double-space-separator", + Credential::Header("Bearer abc"), + adult(), + unauthorized, + FailedCheck::CredentialMalformed, + ), + evidence( + "not-a-compact-token", + Credential::Header("Bearer refusal-token-canary-value"), + adult(), + unauthorized, + FailedCheck::CredentialMalformed, + ), + evidence( + "wrong-issuer", + Credential::Token(access_token_for_issuer( + "https://other.invalid", + "requester-principal-canary", + None, + )), + adult(), + unauthorized, + FailedCheck::TokenIssuer, + ), + evidence( + "expired-token", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"iat": now - 900, "exp": now - 600}), + ))), + adult(), + unauthorized, + FailedCheck::TokenTime, + ), + evidence( + "wrong-audience", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"aud": "https://other.invalid/audience"}), + ))), + adult(), + unauthorized, + FailedCheck::TokenAudience, + ), + evidence( + "unknown-key", + Credential::Token(token_with_unknown_key()), + adult(), + unauthorized, + FailedCheck::TokenKey, + ), + evidence( + "tampered-signature", + Credential::Token(token_with_tampered_signature()), + adult(), + unauthorized, + FailedCheck::TokenSignature, + ), + evidence( + "client-not-admitted", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"client_id": CLIENT_CANARY}), + ))), + adult(), + unauthorized, + FailedCheck::TokenClient, + ), + evidence( + "sender-constrained-token", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"cnf": {"jkt": "thumbprint"}}), + ))), + adult(), + unauthorized, + FailedCheck::SenderConstraint, + ), + evidence( + "unknown-actor-kind", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"registry_actor_kind": "not-a-kind"}), + ))), + adult(), + unauthorized, + FailedCheck::ActorKind, + ), + evidence( + "evidence-audience-claim-is-not-a-url", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"evidence_audience": "not a url"}), + ))), + adult(), + unauthorized, + FailedCheck::TokenClaims, + ), + evidence( + "requester-tags-claim-absent", + Credential::Token(signed_access_token(claims_without( + &["evidence_tags"], + json!({}), + ))), + adult(), + unauthorized, + FailedCheck::TokenClaims, + ), + Scenario { + name: "batch-without-credential", + method: "POST", + route: "/v1/evidence/batch", + credential: Credential::Absent, + accept: None, + body: None, + status: unauthorized, + check: FailedCheck::CredentialMissing, + }, + Scenario { + name: "discovery-without-credential", + method: "GET", + route: "/v1/evidence-definitions", + credential: Credential::Absent, + accept: None, + body: None, + status: unauthorized, + check: FailedCheck::CredentialMissing, + }, + Scenario { + name: "discovery-with-wrong-issuer", + method: "GET", + route: "/v1/evidence-definitions", + credential: Credential::Token(access_token_for_issuer( + "https://other.invalid", + "requester-principal-canary", + None, + )), + accept: None, + body: None, + status: unauthorized, + check: FailedCheck::TokenIssuer, + }, + evidence( + "no-entitlement-for-the-requester", + Credential::Token(access_token(Some( + json!({"evidence_tags": ["unmatched-agency"]}), + ))), + adult(), + forbidden, + FailedCheck::AccessProfile, + ), + evidence( + "purpose-not-permitted", + Credential::Token(access_token(None)), + wrong_purpose, + forbidden, + FailedCheck::Purpose, + ), + evidence( + "selector-profile-not-granted", + Credential::Token(access_token(None)), + unknown_profile, + forbidden, + FailedCheck::SubjectSelector, + ), + evidence( + "revision-pin-mismatch", + Credential::Token(access_token(None)), + pinned, + forbidden, + FailedCheck::RevisionPin, + ), + Scenario { + name: "response-format-not-permitted", + method: "POST", + route: "/v1/evidence", + credential: Credential::Token(access_token(None)), + accept: Some(EVIDENCE_SD_JWT_VC_MEDIA_TYPE), + body: Some(adult_request()), + status: forbidden, + check: FailedCheck::Disclosure, + }, + ] +} + +fn build_request(scenario: &Scenario) -> HttpRequest { + let mut builder = HttpRequest::builder() + .method(scenario.method) + .uri(scenario.route) + .header("content-type", "application/json"); + match &scenario.credential { + Credential::Absent => {} + Credential::Header(value) => builder = builder.header("authorization", *value), + Credential::Repeated => { + builder = builder + .header("authorization", "Bearer first.second.third") + .header("authorization", "Bearer first.second.third"); + } + Credential::Token(token) => { + builder = builder.header("authorization", format!("Bearer {token}")); + } + } + if let Some(accept) = scenario.accept { + builder = builder.header("accept", accept); + } + let body = scenario.body.as_ref().map_or_else(Body::empty, |body| { + Body::from(serde_json::to_vec(body).expect("the request serializes")) + }); + builder.body(body).expect("the request builds") +} + +/// The family line of `evidence_request_refusals_total` for one check, or zero +/// when the exposition carries no such series. +fn counted(exposition: &str, check: FailedCheck) -> u64 { + let prefix = format!( + "evidence_request_refusals_total{{check=\"{}\"}} ", + check.as_str() + ); + exposition + .lines() + .find_map(|line| line.strip_prefix(&prefix)) + .map_or(0, |value| value.parse().expect("a counter value")) +} + +struct Observed { + answer: Value, + exposition: String, +} + +/// Serve one scenario on a fresh runtime, so its counter and log budget are its +/// own, and return what the caller received and what the registry then held. +async fn serve(scenario: &Scenario) -> Observed { + let fixture = acceptance_runtime().await; + let (app, metrics) = build_app_with_metrics(Arc::clone(&fixture.runtime)); + let response = app + .oneshot(build_request(scenario)) + .await + .expect("the router answers"); + let status = response.status(); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("ASCII header").to_owned()) + }; + let headers = json!({ + "content-type": header("content-type"), + "www-authenticate": header("www-authenticate"), + "retry-after": header("retry-after"), + "cache-control": header("cache-control"), + "vary": header("vary"), + }); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .expect("the body reads"); + let mut body: Value = serde_json::from_slice(&bytes).expect("a problem body"); + body.as_object_mut() + .expect("a problem object") + .insert("traceId".to_owned(), json!("")); + Observed { + answer: json!({"status": status.as_u16(), "headers": headers, "body": body}), + exposition: metrics.render(), + } +} + +fn golden_path() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join(GOLDEN) +} + +#[test] +fn every_refusal_is_counted_logged_once_by_its_check_and_answered_as_before() { + let scenarios = scenarios(); + let mut answers = serde_json::Map::new(); + let mut failures = Vec::new(); + for scenario in &scenarios { + let slot: Arc>> = Arc::new(Mutex::new(None)); + let sink = Arc::clone(&slot); + let emitted = capture_evidence_logs(|| async { + *sink.lock().expect("observation slot") = Some(serve(scenario).await); + }); + let observed = slot + .lock() + .expect("observation slot") + .take() + .expect("the scenario ran"); + answers.insert(scenario.name.to_owned(), observed.answer.clone()); + + if observed.answer["status"] != json!(scenario.status.as_u16()) { + failures.push(format!( + "{}: status {} where {} was expected", + scenario.name, observed.answer["status"], scenario.status + )); + continue; + } + let count = counted(&observed.exposition, scenario.check); + if count != 1 { + failures.push(format!( + "{}: the {} series counted {count}, expected 1", + scenario.name, + scenario.check.as_str() + )); + } + for other in FailedCheck::ALL { + if other != scenario.check && counted(&observed.exposition, other) != 0 { + failures.push(format!( + "{}: {} was counted as well", + scenario.name, + other.as_str() + )); + } + } + let refused: Vec<&Value> = emitted + .iter() + .filter(|record| record["fields"]["decision"] == json!("refused")) + .collect(); + if refused.len() != 1 + || refused[0]["fields"]["failed_check"] != json!(scenario.check.as_str()) + { + failures.push(format!( + "{}: expected one refused line for {}, saw {refused:?}", + scenario.name, + scenario.check.as_str() + )); + } + let raw = serde_json::to_string(&emitted).expect("captured records serialize"); + for canary in [TOKEN_CANARY, CLIENT_CANARY, "requester-principal-canary"] { + if raw.contains(canary) { + failures.push(format!("{}: a log line carried {canary}", scenario.name)); + } + } + } + + let answers = Value::Object(answers); + if std::env::var_os("REGISTRY_EVIDENCE_WRITE_GOLDEN").is_some() { + let mut text = serde_json::to_string_pretty(&answers).expect("the golden serializes"); + text.push('\n'); + fs::write(golden_path(), text).expect("the golden is written"); + } else { + let golden: Value = serde_json::from_str( + &fs::read_to_string(golden_path()).expect("the golden file is readable"), + ) + .expect("the golden parses"); + assert_eq!(answers, golden, "a refusal answer changed"); + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +/// A request over the per-principal budget is a `429` counted under +/// `rate-limit`, with its `Retry-After` unchanged. +#[tokio::test] +async fn a_request_over_the_rate_budget_is_counted_under_rate_limit() { + let prepared = prepare_acceptance("subject-binding-secret-canary-32-bytes-minimum").await; + make_writable(&prepared.bundle_root); + let configuration_path = prepared.bundle_root.join("evidence.yaml"); + mutate_acceptance_configuration(&configuration_path, |configuration| { + configuration["rateLimits"]["requestsPerPrincipalPerMinute"] = json!(1); + configuration["rateLimits"]["burstPerPrincipal"] = json!(1); + }); + refresh_package_envelope(&prepared.bundle_root); + make_read_only(&prepared.bundle_root); + let runtime = Arc::new( + EvidenceRuntime::initialize_with_authenticator(&prepared.runtime_path, authenticator()) + .await + .expect("rate-limited runtime initializes"), + ); + let (app, metrics) = build_app_with_metrics(runtime); + let http = TestServer::new(app); + let token = access_token(None); + + http.get("/v1/evidence-definitions") + .add_header("authorization", format!("Bearer {token}")) + .await + .assert_status_ok(); + assert_eq!(counted(&metrics.render(), FailedCheck::RateLimit), 0); + let limited = http + .get("/v1/evidence-definitions") + .add_header("authorization", format!("Bearer {token}")) + .await; + assert_eq!(limited.status_code(), StatusCode::TOO_MANY_REQUESTS); + assert_eq!(limited.header("retry-after"), "1"); + assert_eq!(counted(&metrics.render(), FailedCheck::RateLimit), 1); +} diff --git a/crates/registry-evidence/src/runtime.rs b/crates/registry-evidence/src/runtime.rs index c902906297..e19284b41c 100644 --- a/crates/registry-evidence/src/runtime.rs +++ b/crates/registry-evidence/src/runtime.rs @@ -13,6 +13,7 @@ use async_trait::async_trait; use chrono::{SubsecRound as _, Utc}; use registry_adapter_engine::route::EvidenceHttpDiagnostic; use registry_platform_audit::{AuditDestination, AuditError, AuditProfile}; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{ LocalJwkSigner, PrivateJwk, SigningProvider, TransitInitializationError, TransitSigner, TransitSignerConfig, @@ -412,6 +413,9 @@ pub async fn validate_verification_material( pub struct RuntimeFailure { problem: ProblemCode, category: &'static str, + /// The check a refusal failed. Present exactly when the problem is one of + /// the refusal codes, which only [`refusal`] builds. + check: Option, } impl RuntimeFailure { @@ -422,6 +426,12 @@ impl RuntimeFailure { pub fn category(self) -> &'static str { self.category } + + /// The check a refusal failed, for the operator's count and log line. It is + /// written to no response. + pub fn check(self) -> Option { + self.check + } } impl std::fmt::Debug for RuntimeFailure { @@ -430,6 +440,7 @@ impl std::fmt::Debug for RuntimeFailure { .debug_struct("RuntimeFailure") .field("problem", &self.problem) .field("category", &self.category) + .field("check", &self.check.map(FailedCheck::as_str)) .finish() } } @@ -947,7 +958,7 @@ impl EvidenceRuntime { .authenticator .authenticate(access_token) .await - .map_err(|_| failure(ProblemCode::AuthenticationFailed, "authentication"))?; + .map_err(|error| authentication_refusal(&error))?; let rate_scope = rate_limit_scope(&self.bundle().config.service.trust_domain); let request_limit_key = self .audit @@ -1292,9 +1303,10 @@ impl EvidenceRuntime { )); } if self.bundle().configuration_revision(requirement) != Some(expected) { - return Err(failure( + return Err(refusal( ProblemCode::NotAuthorized, "configuration-revision", + FailedCheck::RevisionPin, )); } Ok(()) @@ -1337,7 +1349,7 @@ impl EvidenceRuntime { .authenticator .authenticate(access_token) .await - .map_err(|_| failure(ProblemCode::AuthenticationFailed, "authentication"))?; + .map_err(|error| authentication_refusal(&error))?; let grant_deadline = grant_release_deadline(&context); let rate_scope = rate_limit_scope(&self.bundle().config.service.trust_domain); let request_limit_key = self @@ -1435,7 +1447,10 @@ impl EvidenceRuntime { }; let matched = match match_entitlement(self.bundle(), &request, &context) { Ok(matched) => matched, - Err(AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority) => { + Err( + error @ (AuthorizationError::Unauthorized(_) + | AuthorizationError::AmbiguousAuthority), + ) => { self.append_authorization_refusal( operation, AuditCaller { @@ -1448,7 +1463,7 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "authorization")); + return Err(map_authority(error)); } Err(error) => return Err(map_authority(error)), }; @@ -1477,7 +1492,11 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "response-format")); + return Err(refusal( + ProblemCode::NotAuthorized, + "response-format", + FailedCheck::Disclosure, + )); } let selector_limit_input = canonical_pair( @@ -1495,7 +1514,10 @@ impl EvidenceRuntime { .map_err(map_selector_limit)?; let resolved = match resolve_selectors(self.bundle(), &request, &context, &matched) { Ok(resolved) => resolved, - Err(AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority) => { + Err( + error @ (AuthorizationError::Unauthorized(_) + | AuthorizationError::AmbiguousAuthority), + ) => { self.append_authorization_refusal( operation, AuditCaller { @@ -1508,7 +1530,7 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "authorization")); + return Err(map_authority(error)); } Err(error) => { if error == AuthorizationError::Selector { @@ -1810,7 +1832,7 @@ impl EvidenceRuntime { .authenticator .authenticate(access_token) .await - .map_err(|_| failure(ProblemCode::AuthenticationFailed, "authentication"))?; + .map_err(|error| authentication_refusal(&error))?; let grant_deadline = grant_release_deadline(&context); let rate_scope = rate_limit_scope(&self.bundle().config.service.trust_domain); let request_limit_key = self @@ -1881,7 +1903,10 @@ impl EvidenceRuntime { let matched = match match_entitlement(self.bundle(), request, &context) { Ok(matched) => matched, - Err(AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority) => { + Err( + error @ (AuthorizationError::Unauthorized(_) + | AuthorizationError::AmbiguousAuthority), + ) => { self.append_authorization_refusal( operation, AuditCaller { @@ -1894,7 +1919,7 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "authorization")); + return Err(map_authority(error)); } Err(error) => return Err(map_authority(error)), }; @@ -1921,7 +1946,11 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "response-format")); + return Err(refusal( + ProblemCode::NotAuthorized, + "response-format", + FailedCheck::Disclosure, + )); } // Only the batch container carries more than one credential, so every // other media type answers at most one presented key, in either binding @@ -1965,7 +1994,10 @@ impl EvidenceRuntime { .map_err(map_selector_limit)?; let resolved = match resolve_selectors(self.bundle(), request, &context, &matched) { Ok(resolved) => resolved, - Err(AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority) => { + Err( + error @ (AuthorizationError::Unauthorized(_) + | AuthorizationError::AmbiguousAuthority), + ) => { self.append_authorization_refusal( operation, AuditCaller { @@ -1978,7 +2010,7 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "authorization")); + return Err(map_authority(error)); } Err(error) => { if error == AuthorizationError::Selector { @@ -3777,13 +3809,21 @@ fn acquisition_source_for_subjects<'a>( for subject in subjects { let source = acquisition .source_for_profile(&subject.selector_profile) - .ok_or_else(|| failure(ProblemCode::NotAuthorized, "acquisition-channel"))?; + .ok_or_else(acquisition_channel_refusal)?; if selected.is_some_and(|previous| previous != source) { - return Err(failure(ProblemCode::NotAuthorized, "acquisition-channel")); + return Err(acquisition_channel_refusal()); } selected = Some(source); } - selected.ok_or_else(|| failure(ProblemCode::NotAuthorized, "acquisition-channel")) + selected.ok_or_else(acquisition_channel_refusal) +} + +fn acquisition_channel_refusal() -> RuntimeFailure { + refusal( + ProblemCode::NotAuthorized, + "acquisition-channel", + FailedCheck::AcquisitionChannel, + ) } /// The shared value-free source failure classification used by serving and offline tooling. @@ -3791,7 +3831,13 @@ pub fn pack_source_failure(error: PackSourceError) -> RuntimeFailure { let (problem, category) = match error { PackSourceError::Plan => (ProblemCode::ServiceUnavailable, "source-plan"), PackSourceError::Inputs => (ProblemCode::ServiceUnavailable, "source-inputs"), - PackSourceError::Authority => (ProblemCode::NotAuthorized, "source-authority"), + PackSourceError::Authority => { + return refusal( + ProblemCode::NotAuthorized, + "source-authority", + FailedCheck::SourceAuthority, + ) + } PackSourceError::Audit => (ProblemCode::ServiceUnavailable, "access-audit"), PackSourceError::Budget => (ProblemCode::DependencyUnavailable, "acquisition-budget"), PackSourceError::Protocol => (ProblemCode::DependencyUnavailable, "source-protocol"), @@ -4120,7 +4166,11 @@ pub(crate) fn release_admission( if grant_deadline .is_some_and(|deadline| deadline.is_expired_at(Utc::now().timestamp_millis(), now)) { - return Err(failure(ProblemCode::NotAuthorized, "grant-expired")); + return Err(refusal( + ProblemCode::NotAuthorized, + "grant-expired", + FailedCheck::TaskGrantExpired, + )); } if now >= acquisition_deadline { return Err(failure( @@ -4131,8 +4181,40 @@ pub(crate) fn release_admission( Ok(()) } +/// A failure that is not a refusal. The refusal codes carry the check that +/// failed, so they are built by [`refusal`] and by nothing else. fn failure(problem: ProblemCode, category: &'static str) -> RuntimeFailure { - RuntimeFailure { problem, category } + debug_assert!( + !crate::observability::is_refusal_code(problem), + "a refusal code is built with `refusal`, which names its check" + ); + RuntimeFailure { + problem, + category, + check: None, + } +} + +/// An authentication, authorization or rate-limit refusal, with the check that +/// failed. +fn refusal(problem: ProblemCode, category: &'static str, check: FailedCheck) -> RuntimeFailure { + debug_assert!( + crate::observability::is_refusal_code(problem), + "`refusal` builds only the refusal codes" + ); + RuntimeFailure { + problem, + category, + check: Some(check), + } +} + +fn authentication_refusal(error: &AuthenticationError) -> RuntimeFailure { + refusal( + ProblemCode::AuthenticationFailed, + "authentication", + error.failed_check(), + ) } fn evidence_unavailable_failure() -> RuntimeFailure { @@ -4148,16 +4230,25 @@ fn public_check_miss() -> RuntimeFailure { fn map_authority(error: AuthorizationError) -> RuntimeFailure { match error { AuthorizationError::Selector => failure(ProblemCode::InvalidSelector, "selector"), - AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority => { - failure(ProblemCode::NotAuthorized, "authorization") + AuthorizationError::Unauthorized(check) => { + refusal(ProblemCode::NotAuthorized, "authorization", check) } + AuthorizationError::AmbiguousAuthority => refusal( + ProblemCode::NotAuthorized, + "authorization", + FailedCheck::AccessProfile, + ), AuthorizationError::Binding => failure(ProblemCode::ServiceUnavailable, "subject-binding"), } } fn map_request_limit(error: RateLimitError) -> RuntimeFailure { match error { - RateLimitError::RequestExceeded => failure(ProblemCode::RateLimited, "request-rate"), + RateLimitError::RequestExceeded => refusal( + ProblemCode::RateLimited, + "request-rate", + FailedCheck::RateLimit, + ), // No wait admits a cost the burst cannot hold, so this is a request // the deployment will never accept, not a retryable rate limit: it // carries no Retry-After and charges nothing. @@ -4168,9 +4259,11 @@ fn map_request_limit(error: RateLimitError) -> RuntimeFailure { fn map_selector_limit(error: RateLimitError) -> RuntimeFailure { match error { - RateLimitError::FailedSelectorExceeded => { - failure(ProblemCode::RateLimited, "selector-rate") - } + RateLimitError::FailedSelectorExceeded => refusal( + ProblemCode::RateLimited, + "selector-rate", + FailedCheck::RateLimit, + ), _ => failure(ProblemCode::ServiceUnavailable, "selector-rate"), } } diff --git a/crates/registry-evidence/src/runtime_tests.rs b/crates/registry-evidence/src/runtime_tests.rs index bcfc0ceb1d..fd214898e8 100644 --- a/crates/registry-evidence/src/runtime_tests.rs +++ b/crates/registry-evidence/src/runtime_tests.rs @@ -82,6 +82,8 @@ use registry_evidence_verifier::model::{ mod discovery_channel_tests; #[path = "evidence_source_tests.rs"] mod evidence_source_tests; +#[path = "refusal_recording_tests.rs"] +mod refusal_recording_tests; #[path = "wallet_channel_tests.rs"] mod wallet_channel_tests; @@ -3562,7 +3564,7 @@ async fn admission_gates_refuse_unadmitted_clients_and_missing_scopes() { .await .expect_err(&format!("{label} was accepted")); assert!( - matches!(error, AuthenticationError::Verification), + matches!(error, AuthenticationError::Verification(_)), "{label}: {error:?}" ); } @@ -3584,7 +3586,7 @@ async fn admission_gates_refuse_unadmitted_clients_and_missing_scopes() { .await .expect_err(&format!("{label} was accepted")); assert!( - matches!(error, AuthenticationError::Verification), + matches!(error, AuthenticationError::Verification(_)), "{label}: {error:?}" ); } diff --git a/crates/registry-evidence/src/selector.rs b/crates/registry-evidence/src/selector.rs index 0049d99852..5da76fe4aa 100644 --- a/crates/registry-evidence/src/selector.rs +++ b/crates/registry-evidence/src/selector.rs @@ -3,12 +3,13 @@ use std::{collections::BTreeSet, fmt}; use chrono::NaiveDate; +use registry_platform_authcommon::FailedCheck; use registry_platform_oidc::ActorKind; use serde_json::Value; use thiserror::Error; use crate::{ - auth::AuthenticatedContext, + auth::{AuthenticatedContext, TaskGrantError}, binding::{ subject_binding, BindingError, SelectorField as BindingField, SelectorScalar as BindingScalar, SubjectBindingInput, SubjectBindingScope, @@ -53,8 +54,11 @@ pub(crate) fn validate_subject_binding_key( #[derive(Debug, Error, Clone, Copy, PartialEq, Eq)] pub enum AuthorizationError { + /// The request is refused. The check says which part of the decision did + /// it, for the operator's count and log line. The caller learns only that + /// the request is not permitted. #[error("the Evidence request is not authorized")] - Unauthorized, + Unauthorized(FailedCheck), #[error("the Evidence request selector is invalid")] Selector, #[error("the Evidence authorization decision is ambiguous")] @@ -459,6 +463,15 @@ pub fn authority_selected_by_principal( .all(|required| requester_tags.iter().any(|actual| actual == required)) } +/// The check a present but untrustworthy task grant failed. +#[deny(clippy::wildcard_enum_match_arm)] +fn task_grant_check(error: TaskGrantError) -> FailedCheck { + match error { + TaskGrantError::Claims | TaskGrantError::PrincipalMismatch => FailedCheck::TaskGrantClaims, + TaskGrantError::Client | TaskGrantError::Resource => FailedCheck::TaskGrantBinding, + } +} + /// Match exactly one complete entitlement without inspecting selector values. /// /// Keeping this decision separate lets the service charge invalid selector @@ -471,7 +484,12 @@ pub fn match_entitlement( ) -> Result { let has_task_grant = match context.grant() { Ok(Some(_)) if context.actor_kind() == ActorKind::Agent => true, - Ok(Some(_)) | Err(_) => return Err(AuthorizationError::Unauthorized), + Ok(Some(_)) => { + return Err(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantClaims, + )) + } + Err(error) => return Err(AuthorizationError::Unauthorized(task_grant_check(error))), Ok(None) => false, }; let requirement = bundle @@ -479,7 +497,7 @@ pub fn match_entitlement( .requirements .iter() .find(|candidate| candidate.id == request.requirement) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized(FailedCheck::AccessProfile))?; if requirement.grant_ceiling.as_ref().is_some_and(|ceiling| { !ceiling .audiences @@ -487,14 +505,16 @@ pub fn match_entitlement( .any(|audience| audience == context.evidence_audience()) || !ceiling.actor_kinds.contains(&context.actor_kind()) }) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantBinding, + )); } if !requirement .purposes .iter() .any(|purpose| purpose == &request.purpose) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized(FailedCheck::Purpose)); } validate_request_subject_shape(requirement, &request.subjects)?; @@ -545,7 +565,7 @@ pub fn match_entitlement( match matched.len() { 1 => Ok(matched.remove(0)), - 0 => Err(AuthorizationError::Unauthorized), + 0 => Err(AuthorizationError::Unauthorized(FailedCheck::AccessProfile)), _ => Err(AuthorizationError::AmbiguousAuthority), } } @@ -589,7 +609,7 @@ pub fn resolve_selectors( .requirements .iter() .find(|candidate| candidate.id == request.requirement) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized(FailedCheck::AccessProfile))?; let subjects = resolve_grant_subjects( bundle, requirement, @@ -667,7 +687,9 @@ pub(crate) fn validate_entitlement_context( .iter() .any(|subject| subject.value_origin == ValueOrigin::AuthenticatedGrant); if uses_authenticated_grant && context.grant_id().is_none() { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantClaims, + )); } for grant in &matched.subjects { @@ -678,11 +700,15 @@ pub(crate) fn validate_entitlement_context( .config .selector_profiles .get(&grant.selector_profile) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let claims = grant .value_claims .as_ref() - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let values = claims .iter() .map(|(field, path)| { @@ -733,7 +759,7 @@ pub(crate) fn resolve_request_origin_subjects( .iter() .any(|configured| configured == purpose) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized(FailedCheck::Purpose)); } // Value origin belongs to the configured request shape. At least one @@ -757,7 +783,9 @@ pub(crate) fn resolve_request_origin_subjects( .all(|subject| subject.value_origin == ValueOrigin::Request) }); if !configured_as_request_origin { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } // Emit the requirement's declaration order. Request array position has no @@ -770,12 +798,16 @@ pub(crate) fn resolve_request_origin_subjects( let subject = requested .iter() .find(|subject| subject.role == declared.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let profile = bundle .config .selector_profiles .get(&subject.selector.profile) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let values = subject .selector .values @@ -859,7 +891,7 @@ pub fn resolve_offline_fixture_authorization( }) .map(|grant| (authority, grant)) }) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized(FailedCheck::AccessProfile))?; let claims = case .get("verifiedTokenClaims") .or_else(|| common.and_then(|value| value.get("verifiedTokenClaims"))) @@ -869,67 +901,73 @@ pub fn resolve_offline_fixture_authorization( .subjects .iter() .any(|subject| subject.value_origin == ValueOrigin::AuthenticatedGrant); - let (actor_kind, client, task_grant) = if uses_task_grant { - let client = authority - .requester_clients - .first() - .ok_or(AuthorizationError::Unauthorized)?; - let source_issuer = authority - .grant_source_issuer - .as_deref() - .ok_or(AuthorizationError::Unauthorized)?; - let resource = bundle.config.authentication.oidc.audience(); - let names = &bundle.config.authentication.oidc.claims; - let now = chrono::Utc::now().timestamp(); - let mut grant_claims = serde_json::json!({ - "sub": "offline-fixture-principal", - "exp": now + 300, - }); - let object = grant_claims - .as_object_mut() - .ok_or(AuthorizationError::Unauthorized)?; - object.insert( - names.grant_id.clone(), - Value::String("offline-fixture-grant".to_owned()), - ); - object.insert( - names.grant_source_issuer.clone(), - Value::String(source_issuer.to_owned()), - ); - object.insert(names.grant_client.clone(), Value::String(client.to_owned())); - object.insert( - names.grant_resource.clone(), - Value::String(resource.to_owned()), - ); - object.insert( - names.purpose.clone(), - Value::String(request.purpose.clone()), - ); - object.insert(names.grant_exp.clone(), Value::from(now + 300)); - object.insert( - names.grant_bounds.clone(), - serde_json::json!({"type": "evidence", "requirement": request.requirement}), - ); - object.insert( - names.approver.clone(), - Value::String("h:offline-fixture-approver".to_owned()), - ); - let parsed: registry_platform_oidc::Claims = - serde_json::from_value(grant_claims).map_err(|_| AuthorizationError::Unauthorized)?; - let grant = registry_platform_oidc::grant_claims( - &parsed, - names, - u64::try_from(now).map_err(|_| AuthorizationError::Unauthorized)?, - ) - .map_err(|_| AuthorizationError::Unauthorized)?; - (ActorKind::Agent, Some(client.as_str()), Ok(grant)) - } else { - ( - authority.actor_kind.unwrap_or(ActorKind::Service), - None, - Ok(None), - ) - }; + let (actor_kind, client, task_grant) = + if uses_task_grant { + let client = + authority + .requester_clients + .first() + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantBinding, + ))?; + let source_issuer = authority.grant_source_issuer.as_deref().ok_or( + AuthorizationError::Unauthorized(FailedCheck::TaskGrantBinding), + )?; + let resource = bundle.config.authentication.oidc.audience(); + let names = &bundle.config.authentication.oidc.claims; + let now = chrono::Utc::now().timestamp(); + let mut grant_claims = serde_json::json!({ + "sub": "offline-fixture-principal", + "exp": now + 300, + }); + let object = grant_claims + .as_object_mut() + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantClaims, + ))?; + object.insert( + names.grant_id.clone(), + Value::String("offline-fixture-grant".to_owned()), + ); + object.insert( + names.grant_source_issuer.clone(), + Value::String(source_issuer.to_owned()), + ); + object.insert(names.grant_client.clone(), Value::String(client.to_owned())); + object.insert( + names.grant_resource.clone(), + Value::String(resource.to_owned()), + ); + object.insert( + names.purpose.clone(), + Value::String(request.purpose.clone()), + ); + object.insert(names.grant_exp.clone(), Value::from(now + 300)); + object.insert( + names.grant_bounds.clone(), + serde_json::json!({"type": "evidence", "requirement": request.requirement}), + ); + object.insert( + names.approver.clone(), + Value::String("h:offline-fixture-approver".to_owned()), + ); + let parsed: registry_platform_oidc::Claims = serde_json::from_value(grant_claims) + .map_err(|_| AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims))?; + let grant = registry_platform_oidc::grant_claims( + &parsed, + names, + u64::try_from(now) + .map_err(|_| AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims))?, + ) + .map_err(|_| AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims))?; + (ActorKind::Agent, Some(client.as_str()), Ok(grant)) + } else { + ( + authority.actor_kind.unwrap_or(ActorKind::Service), + None, + Ok(None), + ) + }; let context = AuthenticatedContext::offline_fixture_context( authority.requester_tags.clone().into_vec(), audience, @@ -965,7 +1003,7 @@ fn fixture_audience<'a>( }, }; if ceiling.is_some_and(|allowed| !allowed.iter().any(|entry| entry == audience)) { - return Err(AuthorizationError::Unauthorized.into()); + return Err(AuthorizationError::Unauthorized(FailedCheck::TaskGrantBinding).into()); } Ok(audience) } @@ -986,7 +1024,7 @@ fn fixture_purpose<'a>( .find(|purpose| purpose.as_str() == declared) .map(String::as_str) .ok_or(OfflineFixtureError::Authorization( - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::Purpose), )) } None => match purposes { @@ -1052,13 +1090,17 @@ fn fixture_subjects_from_selectors( && grant.purpose == purpose && same_subject_tuples(&grant.subjects, &requested) }) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; for subject in &mut requested { let granted = grant .subjects .iter() .find(|granted| granted.role == subject.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; if granted.value_origin != ValueOrigin::Request { subject.selector.values = None; } @@ -1136,24 +1178,32 @@ fn validate_request_subject_shape( requested: &[RequestedSubject], ) -> Result<(), AuthorizationError> { if requested.len() != requirement.subject_roles.len() { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } let mut roles = BTreeSet::new(); for subject in requested { if !roles.insert(subject.role.as_str()) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } let configured = requirement .subject_roles .iter() .find(|configured| configured.role == subject.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; if !configured .selector_profiles .iter() .any(|profile| profile == &subject.selector.profile) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } } Ok(()) @@ -1181,10 +1231,14 @@ fn resolve_grant_subjects( .iter() .any(|subject| subject.value_origin == ValueOrigin::AuthenticatedGrant); if uses_authenticated_grant && context.grant_id().is_none() { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantClaims, + )); } if granted.len() != requirement.subject_roles.len() { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } requirement @@ -1194,16 +1248,22 @@ fn resolve_grant_subjects( let grant = granted .iter() .find(|grant| grant.role == declared.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let subject = requested .iter() .find(|subject| subject.role == grant.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let profile = bundle .config .selector_profiles .get(&grant.selector_profile) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let input = match grant.value_origin { ValueOrigin::Request => subject .selector @@ -1215,10 +1275,13 @@ fn resolve_grant_subjects( if subject.selector.values.is_some() { return Err(AuthorizationError::Selector); } - let claims = grant - .value_claims - .as_ref() - .ok_or(AuthorizationError::Unauthorized)?; + let claims = + grant + .value_claims + .as_ref() + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; claims .iter() .map(|(field, path)| { @@ -1675,7 +1738,7 @@ mod tests { let outside = fixture_object(serde_json::json!({"audience":"urn:example:outside"})); assert_eq!( fixture_audience(Some(&ceiling), None, &outside, "urn:legacy:fixture"), - Err(AuthorizationError::Unauthorized.into()) + Err(AuthorizationError::Unauthorized(FailedCheck::TaskGrantBinding).into()) ); let multiple = vec![ "urn:example:first".to_owned(), @@ -1746,7 +1809,9 @@ mod tests { assert_eq!(error, OfflineFixtureError::Purpose); assert_ne!( error, - OfflineFixtureError::Authorization(AuthorizationError::Unauthorized), + OfflineFixtureError::Authorization(AuthorizationError::Unauthorized( + FailedCheck::Purpose + )), "an unselected fixture purpose must not be reported as an authorization denial" ); } @@ -1774,7 +1839,7 @@ mod tests { &fixture_object(serde_json::json!({"purpose": "other"})) ), Err(OfflineFixtureError::Authorization( - AuthorizationError::Unauthorized + AuthorizationError::Unauthorized(FailedCheck::Purpose) )) ); } diff --git a/crates/registry-evidence/src/server.rs b/crates/registry-evidence/src/server.rs index efd5de0773..119432442b 100644 --- a/crates/registry-evidence/src/server.rs +++ b/crates/registry-evidence/src/server.rs @@ -33,7 +33,9 @@ use axum::{ routing::{get, post}, Router, }; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, BearerParseError, FailedCheck, RefusalNote, +}; use registry_platform_crypto::parse_json_strict; use registry_platform_httpsec::CspBuilder; use serde::Serialize; @@ -466,7 +468,14 @@ async fn create_evidence_negotiated(state: Arc, request: Request token.to_owned(), - Err(code) => return problem_response(code, "authentication", &operation), + Err(check) => { + return refusal_response( + ProblemCode::AuthenticationFailed, + "authentication", + check, + &operation, + ) + } }; // Strict media negotiation resolves the requested response format before // the body is read and long before credential acquisition or source @@ -603,7 +612,14 @@ async fn create_evidence_batch_negotiated( let access_token = match bearer_token(request.headers()) { Ok(token) => token.to_owned(), - Err(code) => return problem_response(code, "authentication", &operation), + Err(check) => { + return refusal_response( + ProblemCode::AuthenticationFailed, + "authentication", + check, + &operation, + ) + } }; if !has_exact_accept(request.headers(), EVIDENCE_REQUEST_BATCH_MEDIA_TYPE) { return problem_response( @@ -863,7 +879,14 @@ async fn discover_evidence( let started = Instant::now(); let access_token = match bearer_token(request.headers()) { Ok(token) => token.to_owned(), - Err(code) => return problem_response(code, "authentication", &operation), + Err(check) => { + return refusal_response( + ProblemCode::AuthenticationFailed, + "authentication", + check, + &operation, + ) + } }; if request.uri().query().is_some() || content_length_exceeds(request.headers(), 0) { return problem_response(ProblemCode::MalformedRequest, "request-shape", &operation); @@ -1130,18 +1153,24 @@ fn parse_evidence_request_batch(bytes: &[u8]) -> Result Result<&str, ProblemCode> { +/// The bearer token the request carries, or the check its header failed: no +/// header, or one that is not a bearer credential, is a missing credential. A +/// repeated, unreadable or misshapen one is a malformed credential. +fn bearer_token(headers: &HeaderMap) -> Result<&str, FailedCheck> { let mut values = headers.get_all(AUTHORIZATION).iter(); - let value = values.next().ok_or(ProblemCode::AuthenticationFailed)?; + let value = values.next().ok_or(FailedCheck::CredentialMissing)?; if values.next().is_some() { - return Err(ProblemCode::AuthenticationFailed); + return Err(FailedCheck::CredentialMalformed); } parse_bearer_token( value .to_str() - .map_err(|_| ProblemCode::AuthenticationFailed)?, + .map_err(|_| FailedCheck::CredentialMalformed)?, ) - .map_err(|_| ProblemCode::AuthenticationFailed) + .map_err(|error| match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) } fn has_exact_content_type(headers: &HeaderMap, expected: &str) -> bool { @@ -1172,7 +1201,10 @@ fn remaining(limit: Duration, started: Instant) -> Option { } fn runtime_failure_response(failure: RuntimeFailure, operation: &OperationId) -> Response { - problem_response(failure.problem(), failure.category(), operation) + match failure.check() { + Some(check) => refusal_response(failure.problem(), failure.category(), check, operation), + None => problem_response(failure.problem(), failure.category(), operation), + } } /// Build one problem response, recording the internal category that caused it. @@ -1187,6 +1219,37 @@ fn problem_response( code: ProblemCode, category: &'static str, operation: &OperationId, +) -> Response { + debug_assert!( + !observability::is_refusal_code(code), + "a refusal is answered with `refusal_response`, which names its check" + ); + answer(code, category, None, operation) +} + +/// Build the answer to an authentication, authorization or rate-limit refusal. +/// +/// The check rides in the response extensions with the code and category. The +/// observation layer counts and logs it. It is not serialized, so the caller's +/// bytes are the ones `problem_response` would have produced. +fn refusal_response( + code: ProblemCode, + category: &'static str, + check: FailedCheck, + operation: &OperationId, +) -> Response { + debug_assert!( + observability::is_refusal_code(code), + "`refusal_response` answers only the refusal codes" + ); + answer(code, category, Some(check), operation) +} + +fn answer( + code: ProblemCode, + category: &'static str, + check: Option, + operation: &OperationId, ) -> Response { let body = code.body(operation.trace_id()); let mut response = serialize_response(code.status(), PROBLEM_MEDIA_TYPE, &body) @@ -1199,6 +1262,9 @@ fn problem_response( response .extensions_mut() .insert(observability::FailureCategory(category)); + if let Some(check) = check { + response.extensions_mut().insert(RefusalNote::new(check)); + } if code == ProblemCode::AuthenticationFailed { response.headers_mut().insert( axum::http::header::WWW_AUTHENTICATE, @@ -1324,29 +1390,37 @@ mod tests { ); } - for invalid in [ - "Basic three.parts.value", - "Bearer", - "Bearer three.parts.value", - "Bearer three.parts.value ", - "Bearer three.parts.value,other", + for (invalid, check) in [ + ("Basic three.parts.value", FailedCheck::CredentialMissing), + ("Bearer", FailedCheck::CredentialMalformed), + ( + "Bearer three.parts.value", + FailedCheck::CredentialMalformed, + ), + ( + "Bearer three.parts.value ", + FailedCheck::CredentialMalformed, + ), + ( + "Bearer three.parts.value,other", + FailedCheck::CredentialMalformed, + ), ] { headers.insert( AUTHORIZATION, HeaderValue::from_str(invalid).expect("test header is valid"), ); - assert_eq!( - bearer_token(&headers), - Err(ProblemCode::AuthenticationFailed) - ); + assert_eq!(bearer_token(&headers), Err(check), "{invalid}"); } + headers.clear(); + assert_eq!(bearer_token(&headers), Err(FailedCheck::CredentialMissing)); headers.clear(); headers.append(AUTHORIZATION, HeaderValue::from_static("Bearer first")); headers.append(AUTHORIZATION, HeaderValue::from_static("Bearer second")); assert_eq!( bearer_token(&headers), - Err(ProblemCode::AuthenticationFailed) + Err(FailedCheck::CredentialMalformed) ); } @@ -1489,9 +1563,10 @@ mod tests { #[tokio::test] async fn problem_responses_have_closed_media_and_challenge_headers() { let operation = operation_id(&axum::http::Extensions::new()); - let authentication = problem_response( + let authentication = refusal_response( ProblemCode::AuthenticationFailed, "authentication", + FailedCheck::CredentialMissing, &operation, ); assert_eq!(authentication.status(), StatusCode::UNAUTHORIZED); @@ -1508,7 +1583,12 @@ mod tests { )) ); - let rate = problem_response(ProblemCode::RateLimited, "rate-limit", &operation); + let rate = refusal_response( + ProblemCode::RateLimited, + "rate-limit", + FailedCheck::RateLimit, + &operation, + ); assert_eq!(rate.status(), StatusCode::TOO_MANY_REQUESTS); assert_eq!( rate.headers().get(RETRY_AFTER), diff --git a/crates/registry-evidence/tests/golden/refusal_answers.json b/crates/registry-evidence/tests/golden/refusal_answers.json new file mode 100644 index 0000000000..9d69b2a05f --- /dev/null +++ b/crates/registry-evidence/tests/golden/refusal_answers.json @@ -0,0 +1,416 @@ +{ + "batch-without-credential": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "client-not-admitted": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "discovery-with-wrong-issuer": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": null, + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "discovery-without-credential": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": null, + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "double-space-separator": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "evidence-audience-claim-is-not-a-url": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "expired-token": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "no-authorization-header": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "no-entitlement-for-the-requester": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "non-bearer-scheme": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "not-a-compact-token": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "purpose-not-permitted": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "repeated-authorization-header": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "requester-tags-claim-absent": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "response-format-not-permitted": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "revision-pin-mismatch": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "selector-profile-not-granted": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "sender-constrained-token": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "tampered-signature": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "unknown-actor-kind": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "unknown-key": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "wrong-audience": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "wrong-issuer": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + } +} diff --git a/crates/registry-evidence/tests/selector_conformance.rs b/crates/registry-evidence/tests/selector_conformance.rs index 59f48f15b4..d244c878eb 100644 --- a/crates/registry-evidence/tests/selector_conformance.rs +++ b/crates/registry-evidence/tests/selector_conformance.rs @@ -38,6 +38,7 @@ use registry_evidence::selector::{ }; use registry_evidence::signing::{jwks_document, EvidenceSigner}; use registry_evidence::verifier::{verify_flattened_jws, EvidenceVerificationPolicy}; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{sign, LocalJwkSigner, PrivateJwk, SigningProvider}; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier, TokenVerifierConfig}; use serde_json::{json, Value}; @@ -527,7 +528,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { "record_reference", SelectorValue::String("synthetic-record-001".to_owned()), )])), - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; executed.insert("identifier-possession-without-entitlement"); @@ -629,14 +630,13 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { "event_reference": "synthetic-event-001" }} })); - assert!(matches!( - service - .authorize(&grant_source_without_id, &grant_request(None)) - .await, - Err(AuthorizationStageError::Authorization( - AuthorizationError::Unauthorized - )) - )); + assert_authorization_error( + &service, + &grant_source_without_id, + &grant_request(None), + AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims), + ) + .await; executed.insert("authenticated-grant-id-not-bound"); let mut wrong_grant_source_issuer = task_grant_claims(json!({ @@ -651,7 +651,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &access_token(wrong_grant_source_issuer), &grant_request(None), - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; executed.insert("authenticated-grant-source-issuer-not-bound"); @@ -663,7 +663,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { PROPERTY_WITH_EVENT, vec![subject("subject", "demographics-v1", None)], ), - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("alternative-field-set-not-inferred"); @@ -684,7 +684,13 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { subject("subject-b", "opaque-record-v1", role_a.clone()), ], ); - assert_authorization_error(&service, &base, &swapped, AuthorizationError::Unauthorized).await; + assert_authorization_error( + &service, + &base, + &swapped, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), + ) + .await; executed.insert("swapped-role-selectors"); let substituted = request( @@ -698,7 +704,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &substituted, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("unauthorized-subject-b-substitution"); @@ -711,7 +717,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &missing_role, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("missing-one-role"); @@ -727,7 +733,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &duplicate_role, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("duplicate-subject-role"); @@ -743,7 +749,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &unknown_role, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("unknown-subject-role"); @@ -766,7 +772,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &union_attempt, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; executed.insert("entitlement-union-across-roles"); @@ -887,7 +893,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { ]), )], ), - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("unauthorized-profile"); @@ -901,7 +907,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &wrong_purpose, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::Purpose), ) .await; executed.insert("unauthorized-purpose"); @@ -969,7 +975,7 @@ async fn standing_agent_requires_an_explicit_agent_profile() { &service, &access_token(json!({"registry_actor_kind": "agent"})), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; assert!(service.server.received_requests().await.unwrap().is_empty()); @@ -986,7 +992,7 @@ async fn standing_agent_requires_an_explicit_agent_profile() { &bound, &access_token(json!({"registry_actor_kind": "service"})), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; assert!(bound.server.received_requests().await.unwrap().is_empty()); @@ -1000,7 +1006,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(json!({})), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; let subject = json!({ @@ -1010,23 +1016,36 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { "event_reference": "synthetic-event-001" }); - for (name, member, value) in [ + for (name, member, value, check) in [ ( "source issuer", "registry_grant_source_issuer", json!("https://other.invalid"), + FailedCheck::AccessProfile, + ), + ( + "client", + "registry_grant_client", + json!("other-client"), + FailedCheck::TaskGrantBinding, ), - ("client", "registry_grant_client", json!("other-client")), ( "resource", "registry_grant_resource", json!("other-resource"), + FailedCheck::TaskGrantBinding, + ), + ( + "purpose", + "registry_purpose", + json!("other-purpose"), + FailedCheck::AccessProfile, ), - ("purpose", "registry_purpose", json!("other-purpose")), ( "requirement", "registry_grant_bounds", json!({"type":"evidence", "requirement":"urn:example:other"}), + FailedCheck::AccessProfile, ), ] { let mut claims = task_grant_claims(subject.clone()); @@ -1035,7 +1054,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(claims), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(check), ) .await; assert!(!name.is_empty()); @@ -1047,7 +1066,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(wrong_actor), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims), ) .await; @@ -1057,7 +1076,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(expired), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims), ) .await; @@ -1379,9 +1398,9 @@ async fn assert_authorization_error( let stage = match first { Ok(_) => "authorized", Err(AuthorizationStageError::Authentication) => "authentication", - Err(AuthorizationStageError::Authorization(AuthorizationError::Unauthorized)) => { - "unauthorized" - } + Err(AuthorizationStageError::Authorization(AuthorizationError::Unauthorized( + check, + ))) => check.as_str(), Err(AuthorizationStageError::Authorization(AuthorizationError::Selector)) => "selector", Err(AuthorizationStageError::Authorization(AuthorizationError::AmbiguousAuthority)) => { "ambiguous-authority" diff --git a/crates/registry-evidence/tests/token_characterisation.rs b/crates/registry-evidence/tests/token_characterisation.rs index 43bb3748ed..818981305c 100644 --- a/crates/registry-evidence/tests/token_characterisation.rs +++ b/crates/registry-evidence/tests/token_characterisation.rs @@ -22,6 +22,7 @@ use registry_evidence::{ OidcAuthenticationConfig, }, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::JwksSource; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier, TokenVerifierConfig}; use registry_platform_testing::{ @@ -181,19 +182,26 @@ async fn authenticate(case: FixtureCase, key_set_uri: String) -> Outcome { match authenticator.authenticate(case.token.expose()).await { Ok(context) => Outcome::Admitted(Some(context.actor_kind().as_str().to_owned())), Err(AuthenticationError::Malformed) => Outcome::Refused(Stage::Header), - Err(AuthenticationError::Context | AuthenticationError::SenderConstrained) => { + Err(AuthenticationError::Context(_) | AuthenticationError::SenderConstrained) => { Outcome::Refused(Stage::Claims) } - Err(AuthenticationError::Verification) => match verifier_refusal(&config, &case).await { - Some(stage) => Outcome::Refused(stage), - None => { - assert!( + Err(AuthenticationError::Verification(check)) => { + match verifier_refusal(&config, &case).await { + Some(stage) => Outcome::Refused(stage), + None => { + assert!( !config.required_scopes.admitted().is_empty(), "the authenticator refused a token the verifier admits and no scope gate is set" ); - Outcome::Refused(Stage::Scope) + assert_eq!( + check, + FailedCheck::Scope, + "a token the verifier admits is refused by the scope gate" + ); + Outcome::Refused(Stage::Scope) + } } - }, + } } } diff --git a/crates/registry-mcp-edge/Cargo.toml b/crates/registry-mcp-edge/Cargo.toml index 6f7a65873b..5ba528192d 100644 --- a/crates/registry-mcp-edge/Cargo.toml +++ b/crates/registry-mcp-edge/Cargo.toml @@ -26,7 +26,7 @@ async-trait.workspace = true axum.workspace = true http.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true diff --git a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs index 8d21fc9124..8092ac3f02 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs @@ -14,6 +14,7 @@ use axum::{ Router, }; use registry_platform_audit::AuditProfile; +use registry_platform_authcommon::FailedCheck; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ access_token_typ_set, is_access_token_typ_pair, Claims, JwksFetcher, JwksFetcherConfig, @@ -27,8 +28,8 @@ use zeroize::Zeroizing; use crate::{ inbound::{metadata_url, require_caller, retry_after_seconds, Refusal}, - token_verifier, AccessTokenAlgorithm, RateLimitOptions, ResourceServer, ResourceServerOptions, - TokenBucketOptions, VerifiedCaller, + token_verifier, AccessTokenAlgorithm, RateLimitOptions, ResourceServer, ResourceServerError, + ResourceServerOptions, TokenBucketOptions, VerifiedCaller, }; const RESOURCE: &str = "https://gateway.example.test/mcp"; @@ -433,9 +434,15 @@ async fn every_refusal_is_a_problem_document() { let auth = authorization_server().await; let server = resource_server_for(&auth, 10, 10); let cases = [ - (Refusal::Missing, 401, "Unauthorized", "unauthorized", true), ( - Refusal::InvalidToken, + Refusal::Missing(FailedCheck::CredentialMissing), + 401, + "Unauthorized", + "unauthorized", + true, + ), + ( + Refusal::InvalidToken(FailedCheck::TokenAudience), 401, "Unauthorized", "invalid-token", @@ -592,6 +599,37 @@ fn retry_after_rounds_up_to_whole_seconds() { assert_eq!(retry_after_seconds(Duration::from_secs(7)), 7); } +#[tokio::test] +async fn only_the_loopback_forms_are_a_development_resource_and_issuer() { + let auth = authorization_server().await; + for host in [ + "127.0.0.1", + "127.0.0.2", + "[::1]", + "LOCALHOST", + "[::ffff:127.0.0.1]", + ] { + let mut options = options(&auth); + options.resource = format!("http://{host}:8095/mcp"); + options.issuer = format!("http://{host}:8096"); + assert_eq!(options.validate(), Ok(()), "{host}"); + } + for host in [ + "localhost.", + "app.localhost", + "10.0.0.1", + "[::ffff:10.0.0.1]", + ] { + let mut options = options(&auth); + options.resource = format!("http://{host}:8095/mcp"); + assert_eq!( + options.validate(), + Err(ResourceServerError::Resource), + "{host}" + ); + } +} + #[tokio::test] async fn localhost_is_a_development_loopback_resource_and_issuer() { let auth = authorization_server().await; @@ -636,15 +674,53 @@ async fn a_token_that_already_names_an_actor_is_refused() { matched_client: Some(format!("client_id:{CHAT_HOST}")), scopes: vec![SCOPE.to_owned()], }; - assert!(server.caller_for_test(&delegated, "token").is_err()); + assert_eq!( + server.caller_for_test(&delegated, "token").err(), + Some(Refusal::InvalidToken(FailedCheck::Delegation)) + ); + claims + .extra + .insert("may_act".to_owned(), json!({"sub": "x"})); claims.extra.remove("act"); - claims.sub = None; - let anonymous = VerifiedToken { - claims, + let may_act = VerifiedToken { + claims: claims.clone(), matched_client: Some(format!("client_id:{CHAT_HOST}")), scopes: vec![SCOPE.to_owned()], }; - assert!(server.caller_for_test(&anonymous, "token").is_err()); + assert_eq!( + server.caller_for_test(&may_act, "token").err(), + Some(Refusal::InvalidToken(FailedCheck::Delegation)) + ); + claims.extra.remove("may_act"); + let verified = |claims: Claims, matched_client: Option| VerifiedToken { + claims, + matched_client, + scopes: vec![SCOPE.to_owned()], + }; + let matched = || Some(format!("client_id:{CHAT_HOST}")); + + let mut anonymous = claims.clone(); + anonymous.sub = None; + assert_eq!( + server + .caller_for_test(&verified(anonymous, matched()), "token") + .err(), + Some(Refusal::InvalidToken(FailedCheck::TokenClaims)) + ); + assert_eq!( + server + .caller_for_test(&verified(claims.clone(), None), "token") + .err(), + Some(Refusal::InvalidToken(FailedCheck::TokenClient)) + ); + let mut unbounded = claims; + unbounded.exp = None; + assert_eq!( + server + .caller_for_test(&verified(unbounded, matched()), "token") + .err(), + Some(Refusal::InvalidToken(FailedCheck::TokenClaims)) + ); } #[test] diff --git a/crates/registry-mcp-edge/src/config.rs b/crates/registry-mcp-edge/src/config.rs index 0506bb1a07..a32e32650a 100644 --- a/crates/registry-mcp-edge/src/config.rs +++ b/crates/registry-mcp-edge/src/config.rs @@ -11,10 +11,9 @@ use registry_platform_audit::{ use registry_platform_config::{ AuditKeyConfig, ConfigBlockError, JwksSource, SecretProvidersConfig, SecretReference, }; -use registry_platform_httputil::{valid_resource_uri, valid_scope_token}; +use registry_platform_httputil::{loopback::loopback_host, valid_resource_uri, valid_scope_token}; use registry_platform_yaml::{BoundedU32, BoundedU64, ExternalId, Invalid, UniqueList, Url}; use serde::{de, Deserialize, Deserializer}; -use url::Host; pub use crate::AccessTokenAlgorithm; use crate::{ResourceServerOptions, MCP_PATH}; @@ -206,23 +205,19 @@ pub enum ResourceServerConfigError { fn protected_endpoint(url: &url::Url, development_loopback: bool) -> bool { url.host().is_some() && (url.scheme() == "https" - || development_loopback && url.scheme() == "http" && loopback_host(url)) + || development_loopback && url.scheme() == "http" && is_loopback(url)) } fn issuer_endpoint(url: &url::Url, development_loopback: bool, allow_insecure_http: bool) -> bool { url.host().is_some() && (url.scheme() == "https" || url.scheme() == "http" - && (allow_insecure_http || development_loopback && loopback_host(url))) + && (allow_insecure_http || development_loopback && is_loopback(url))) } -fn loopback_host(url: &url::Url) -> bool { - match url.host() { - Some(Host::Ipv4(address)) => address.is_loopback(), - Some(Host::Ipv6(address)) => address.is_loopback(), - Some(Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), - None => false, - } +fn is_loopback(url: &url::Url) -> bool { + url.host_str() + .is_some_and(|host| loopback_host(host).is_some()) } fn default_scope_claim() -> ExternalId { @@ -541,6 +536,37 @@ mod tests { assert!(config.validate(true, &secret_providers()).is_empty()); } + #[test] + fn development_loopback_admits_only_the_loopback_forms() { + for host in ["127.0.0.2", "[::1]", "LOCALHOST", "[::ffff:127.0.0.1]"] { + let mut config = resource_server(); + config.resource = Url::new(format!("http://{host}:8110/mcp")).expect("resource"); + config.issuer = Url::new(format!("http://{host}:8111")).expect("issuer"); + assert!( + config.validate(true, &secret_providers()).is_empty(), + "{host}" + ); + } + for host in ["localhost.", "app.localhost", "10.0.0.1"] { + let mut config = resource_server(); + config.resource = Url::new(format!("http://{host}:8110/mcp")).expect("resource"); + config.issuer = Url::new(format!("http://{host}:8111")).expect("issuer"); + let errors = config.validate(true, &secret_providers()); + assert!( + errors + .iter() + .any(|error| matches!(error, ResourceServerConfigError::InsecureResource)), + "{host}" + ); + assert!( + errors + .iter() + .any(|error| matches!(error, ResourceServerConfigError::InsecureIssuer)), + "{host}" + ); + } + } + #[test] fn authored_resource_validation_reports_the_mcp_path_and_static_secret() { let mut config = resource_server(); diff --git a/crates/registry-mcp-edge/src/inbound.rs b/crates/registry-mcp-edge/src/inbound.rs index 99eaaeb6c1..776f086098 100644 --- a/crates/registry-mcp-edge/src/inbound.rs +++ b/crates/registry-mcp-edge/src/inbound.rs @@ -10,7 +10,10 @@ use axum::{ response::Response, }; use registry_platform_audit::AuditKeyHasher; -use registry_platform_authcommon::{parse_bearer_token, BearerParseError}; +use registry_platform_authcommon::{ + parse_bearer_token, record_refusal, BearerParseError, FailedCheck, RefusalNote, RefusalRecorder, +}; +use registry_platform_httputil::loopback::loopback_host; pub use registry_platform_oidc::AccessTokenAlgorithm; use registry_platform_oidc::{ access_token_typ_set, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, VerifiedToken, @@ -19,7 +22,7 @@ use registry_platform_ratelimit::token_bucket::{ TokenBucketConfig, TokenBucketError, TokenBucketLimiter, }; use serde_json::{json, Value}; -use url::{Host, Url}; +use url::Url; use zeroize::Zeroizing; use crate::server::{problem, METADATA_PREFIX}; @@ -223,10 +226,12 @@ impl CallerContext<'_> { } } +/// What the edge answers, and for the answers that carry a check, the check +/// that failed. The check is operator-side only and never reaches a response. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum Refusal { - Missing, - InvalidToken, + Missing(FailedCheck), + InvalidToken(FailedCheck), InsufficientScope, KeySource, RateLimited { retry_after_seconds: u64 }, @@ -245,6 +250,7 @@ pub struct ResourceServer { challenge: String, scope_challenge: String, metadata: Value, + refusals: Arc, } #[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] @@ -257,6 +263,8 @@ pub enum ResourceServerError { Options, #[error("the {0} rate limit is not usable")] RateLimit(&'static str), + #[error("the refusal recorder is not usable")] + Recorder, } impl ResourceServer { @@ -278,6 +286,8 @@ impl ResourceServer { .map_err(|_| ResourceServerError::RateLimit("perPrincipal"))?; let per_client = limiter(limits.per_client).map_err(|_| ResourceServerError::RateLimit("perClient"))?; + let refusals = + Arc::new(RefusalRecorder::new("mcp_edge").map_err(|_| ResourceServerError::Recorder)?); let metadata = json!({ "resource": options.resource.as_str(), "authorization_servers": [options.issuer.as_str()], @@ -297,9 +307,17 @@ impl ResourceServer { challenge, scope_challenge, metadata, + refusals, }) } + /// Counts every refusal by the check that failed. The edge has no metrics + /// listener, so the counter is read in tests and the log line is the + /// operator's signal. + pub(crate) const fn refusal_recorder(&self) -> &Arc { + &self.refusals + } + #[must_use] pub const fn metadata(&self) -> &Value { &self.metadata @@ -310,8 +328,8 @@ impl ResourceServer { &self, verified: &VerifiedToken, token: &str, - ) -> Result { - self.caller(verified, token).map_err(|_| ()) + ) -> Result { + self.caller(verified, token) } async fn authenticate(&self, headers: &HeaderMap) -> Result { @@ -322,7 +340,7 @@ impl ResourceServer { tracing::warn!("the access-token key set is unavailable"); return Err(Refusal::KeySource); } - Err(_) => return Err(Refusal::InvalidToken), + Err(error) => return Err(Refusal::InvalidToken(error.failed_check())), }; let caller = self.caller(&verified, token)?; admit(&self.per_principal, caller.principal_pseudonym()).await?; @@ -333,19 +351,21 @@ impl ResourceServer { fn caller(&self, verified: &VerifiedToken, token: &str) -> Result { let claims = &verified.claims; if claims.extra.contains_key("act") || claims.extra.contains_key("may_act") { - return Err(Refusal::InvalidToken); + return Err(Refusal::InvalidToken(FailedCheck::Delegation)); } let subject = claims .sub .as_deref() .filter(|subject| !subject.is_empty()) - .ok_or(Refusal::InvalidToken)?; + .ok_or(Refusal::InvalidToken(FailedCheck::TokenClaims))?; let client = verified .matched_client_id() .ok() .flatten() - .ok_or(Refusal::InvalidToken)?; - let expires_at = claims.exp.ok_or(Refusal::InvalidToken)?; + .ok_or(Refusal::InvalidToken(FailedCheck::TokenClient))?; + let expires_at = claims + .exp + .ok_or(Refusal::InvalidToken(FailedCheck::TokenClaims))?; let present: HashSet<&str> = verified.scopes.iter().map(String::as_str).collect(); if !self .required_scopes @@ -370,10 +390,21 @@ impl ResourceServer { .map_err(|_| Refusal::Unavailable) } + /// Counts and logs the refusal, then builds its answer. + fn refuse(&self, refusal: Refusal) -> Response { + match refusal.failed_check() { + Some(check) => record_refusal!(self.refusals, RefusalNote::new(check)), + // The gateway could not derive a pseudonym or run its limiter. + // That is a fault of this service, not a check a caller failed. + None => tracing::error!("the gateway could not admit a request"), + } + self.refusal_response(refusal) + } + pub(crate) fn refusal_response(&self, refusal: Refusal) -> Response { let (status, challenge) = match refusal { - Refusal::Missing => (StatusCode::UNAUTHORIZED, Some(self.challenge.clone())), - Refusal::InvalidToken => ( + Refusal::Missing(_) => (StatusCode::UNAUTHORIZED, Some(self.challenge.clone())), + Refusal::InvalidToken(_) => ( StatusCode::UNAUTHORIZED, Some( self.challenge @@ -445,9 +476,8 @@ fn valid_issuer_url(url: &Url, allow_insecure_http: bool) -> bool { } fn loopback(url: &Url) -> bool { - matches!(url.host(), Some(Host::Ipv4(ip)) if ip.is_loopback()) - || matches!(url.host(), Some(Host::Ipv6(ip)) if ip.is_loopback()) - || matches!(url.host(), Some(Host::Domain(domain)) if domain.eq_ignore_ascii_case("localhost")) + url.host_str() + .is_some_and(|host| loopback_host(host).is_some()) } fn limiter(options: TokenBucketOptions) -> Result { @@ -458,10 +488,21 @@ fn limiter(options: TokenBucketOptions) -> Result Option { + match self { + Self::Missing(check) | Self::InvalidToken(check) => Some(check), + Self::InsufficientScope => Some(FailedCheck::Scope), + Self::KeySource => Some(FailedCheck::KeySourceUnavailable), + Self::RateLimited { .. } => Some(FailedCheck::RateLimit), + Self::Unavailable => None, + } + } + const fn code(self) -> &'static str { match self { - Self::Missing => "unauthorized", - Self::InvalidToken => "invalid-token", + Self::Missing(_) => "unauthorized", + Self::InvalidToken(_) => "invalid-token", Self::InsufficientScope => "insufficient-scope", Self::KeySource | Self::Unavailable => "temporarily-unavailable", Self::RateLimited { .. } => "rate-limited", @@ -470,8 +511,8 @@ impl Refusal { const fn detail(self) -> &'static str { match self { - Self::Missing => "A bearer access token is required.", - Self::InvalidToken => "The access token is not valid for this resource.", + Self::Missing(_) => "A bearer access token is required.", + Self::InvalidToken(_) => "The access token is not valid for this resource.", Self::InsufficientScope => "The access token lacks a required scope.", Self::KeySource | Self::Unavailable => { "The gateway cannot verify the request right now." @@ -492,7 +533,7 @@ pub(crate) async fn require_caller( request.extensions_mut().insert(Arc::new(caller)); next.run(request).await } - Err(refusal) => server.refusal_response(refusal), + Err(refusal) => server.refuse(refusal), } } @@ -516,14 +557,19 @@ pub(crate) fn retry_after_seconds(retry_after: Duration) -> u64 { fn bearer_token(headers: &HeaderMap) -> Result<&str, Refusal> { let mut values = headers.get_all(header::AUTHORIZATION).iter(); - let value = values.next().ok_or(Refusal::Missing)?; + let value = values + .next() + .ok_or(Refusal::Missing(FailedCheck::CredentialMissing))?; if values.next().is_some() { - return Err(Refusal::InvalidToken); + return Err(Refusal::InvalidToken(FailedCheck::CredentialMalformed)); } - let value = value.to_str().map_err(|_| Refusal::InvalidToken)?; + let value = value + .to_str() + .map_err(|_| Refusal::InvalidToken(FailedCheck::CredentialMalformed))?; parse_bearer_token(value).map_err(|error| match error { - BearerParseError::Malformed | BearerParseError::InvalidScheme => Refusal::Missing, - _ => Refusal::InvalidToken, + BearerParseError::InvalidScheme => Refusal::Missing(FailedCheck::CredentialMissing), + BearerParseError::Malformed => Refusal::Missing(FailedCheck::CredentialMalformed), + _ => Refusal::InvalidToken(FailedCheck::CredentialMalformed), }) } @@ -572,3 +618,6 @@ fn is_key_source_failure(error: &OidcError) -> bool { | OidcError::MissingIssuer ) } + +#[cfg(test)] +mod refusal_tests; diff --git a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs new file mode 100644 index 0000000000..abced72916 --- /dev/null +++ b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs @@ -0,0 +1,446 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Every refusal the edge answers, driven through the real router. The golden +//! file freezes the status, the headers a client can read and the body of each +//! answer. + +use std::{collections::BTreeMap, io, sync::Arc, time::Duration}; + +use async_trait::async_trait; +use axum::{ + body::Body, + http::{header, HeaderName, HeaderValue, Request, StatusCode}, + Router, +}; +use registry_platform_audit::{AuditProfile, AuditWriter}; +use registry_platform_authcommon::FailedCheck; +use registry_platform_httputil::{client::StaticToken, FetchUrlPolicy}; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{TestAuthorizationServer, TestClient}; +use rmcp::model::Tool; +use serde_json::{json, Value}; +use tower::ServiceExt; +use url::Url; +use zeroize::Zeroizing; + +use crate::{ + router, token_verifier, AccessTokenAlgorithm, AuditOptions, EffectCertainty, + FixedAuthorizationFactory, GatewayCore, GatewayInfo, Invocation, Provider, + ProviderAuthorization, ProviderBinding, ProviderFailure, ProviderOutcome, RateLimitOptions, + ResolvedTool, ResourceServer, ResourceServerOptions, ServerOptions, TokenBucketOptions, + ToolAuditLog, VerifiedCaller, +}; + +const RESOURCE: &str = "https://gateway.example.test/mcp"; +const HOST: &str = "gateway.example.test"; +const CLIENT: &str = "chat-host"; +const SCOPE: &str = "test:read"; +const GOLDEN: &str = include_str!("../../tests/golden/refusals.json"); +const GOLDEN_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/golden/refusals.json"); + +struct UnusedProvider; + +#[async_trait] +impl Provider for UnusedProvider { + fn resolve_tool(&self, name: &str) -> Option { + (name == "unused") + .then(|| ResolvedTool::new("unused", "test", "unused", "v1").expect("identity")) + } + + async fn list_tools( + &self, + _: &VerifiedCaller, + _: ProviderAuthorization, + ) -> Result, ProviderFailure> { + Ok(Vec::new()) + } + + async fn invoke( + &self, + _: &VerifiedCaller, + _: ProviderAuthorization, + _: Invocation<'_>, + ) -> ProviderOutcome { + ProviderOutcome::failure(ProviderFailure::new( + "unused", + "Unused.", + EffectCertainty::NoEffect, + )) + } +} + +fn gateway_core() -> Arc { + let token = StaticToken::new("test-only-static-token").expect("token"); + let binding = ProviderBinding::new( + Arc::new(UnusedProvider), + Arc::new(FixedAuthorizationFactory::new(Arc::new(token))), + ["unused".to_owned()], + ) + .expect("binding"); + let audit = ToolAuditLog::new(AuditWriter::from_line_sink(Box::new(io::sink()))); + Arc::new( + GatewayCore::new( + [binding], + audit, + AuditOptions::new("registry-test-mcp.tool-call/v1", "test_mcp.tool_call") + .expect("audit"), + GatewayInfo::new("test-mcp", "Test", "Test").expect("info"), + ) + .expect("core"), + ) +} + +fn now() -> i64 { + i64::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_secs(), + ) + .expect("time fits") +} + +async fn authorization() -> TestAuthorizationServer { + TestAuthorizationServer::builder() + .client(TestClient::new(CLIENT)) + .client(TestClient::new("another-host")) + .start() + .await +} + +/// The real edge router over a verifier that reads `jwks_uri`. +pub(super) fn application( + authorization: &TestAuthorizationServer, + jwks_uri: String, + burst: u32, +) -> (Router, Arc) { + let options = ResourceServerOptions { + resource: RESOURCE.to_owned(), + issuer: authorization.issuer(), + allow_insecure_http: false, + algorithms: vec![AccessTokenAlgorithm::EdDSA], + allowed_clients: vec![CLIENT.to_owned()], + required_scopes: vec![SCOPE.to_owned()], + scope_claim: "scope".to_owned(), + maximum_token_lifetime: Duration::from_secs(300), + resource_name: "Test".to_owned(), + principal_audit_namespace: "test-principal-v1".to_owned(), + client_audit_namespace: "test-client-v1".to_owned(), + }; + let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( + jwks_uri, + JwksFetcherConfig::defaults(), + FetchUrlPolicy::dev(), + )); + let profile = + AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![8; 32])).expect("profile"); + let bucket = TokenBucketOptions { + requests_per_minute: 1, + burst, + }; + let resource_server = Arc::new( + ResourceServer::new( + &options, + token_verifier(&options, fetcher), + profile.key_hasher(), + RateLimitOptions { + per_principal: bucket, + per_client: bucket, + }, + ) + .expect("resource server"), + ); + let app = router( + gateway_core(), + Arc::clone(&resource_server), + &ServerOptions { + resource: Url::parse(RESOURCE).expect("resource URL"), + maximum_request_bytes: 4096, + hsts: false, + }, + ); + (app, resource_server) +} + +pub(super) type Headers = Vec<(HeaderName, HeaderValue)>; + +pub(super) fn request(headers: Headers) -> Request { + let mut request = Request::post("/mcp") + .header(header::HOST, HOST) + .header(header::ACCEPT, "application/json, text/event-stream"); + for (name, value) in headers { + request = request.header(name, value); + } + request.body(Body::empty()).expect("request") +} + +pub(super) fn authorization_header(value: &str) -> (HeaderName, HeaderValue) { + ( + header::AUTHORIZATION, + HeaderValue::from_str(value).expect("header value"), + ) +} + +pub(super) fn bearer(token: &str) -> Headers { + vec![authorization_header(&format!("Bearer {token}"))] +} + +/// The answers and, per case, the checks its refusal counted. +#[derive(Default)] +struct Run { + answers: BTreeMap<&'static str, Value>, + counted: BTreeMap<&'static str, BTreeMap<&'static str, u64>>, +} + +impl Run { + /// Sends one request to a server that has served nothing else, so the + /// counter holds this request's refusal alone. + async fn observe( + &mut self, + name: &'static str, + (app, server): &(Router, Arc), + headers: Headers, + ) { + let answer = summarise( + app.clone() + .oneshot(request(headers)) + .await + .expect("response"), + ) + .await; + self.record(name, server, answer); + } + + fn record(&mut self, name: &'static str, server: &ResourceServer, answer: Value) { + let counted = FailedCheck::ALL + .iter() + .filter_map(|check| { + let count = server + .refusal_recorder() + .counter() + .get(&[check.as_str()]) + .expect("every check is a declared series"); + (count > 0).then_some((check.as_str(), count)) + }) + .collect(); + self.answers.insert(name, answer); + self.counted.insert(name, counted); + } +} + +/// One name per refusal the edge can answer, with the answer it gives. +async fn drive() -> Run { + let auth = authorization().await; + let fresh = || application(&auth, auth.jwks_uri(), 100); + let issue = |client: &str, audience: &str, scope: &str, exp: i64| { + auth.issue_access_token(client, "citizen-a", audience, scope, exp) + }; + let mut run = Run::default(); + + run.observe("no-authorization-header", &fresh(), vec![]) + .await; + run.observe( + "non-bearer-scheme", + &fresh(), + vec![authorization_header("Basic abc")], + ) + .await; + run.observe( + "bearer-without-token", + &fresh(), + vec![authorization_header("Bearer")], + ) + .await; + run.observe( + "bearer-with-two-spaces", + &fresh(), + vec![authorization_header("Bearer a")], + ) + .await; + run.observe( + "repeated-authorization-header", + &fresh(), + vec![ + authorization_header("Bearer a"), + authorization_header("Bearer b"), + ], + ) + .await; + run.observe( + "unreadable-authorization-header", + &fresh(), + vec![( + header::AUTHORIZATION, + HeaderValue::from_bytes(b"Bearer \xff").expect("opaque header"), + )], + ) + .await; + run.observe("not-a-jwt", &fresh(), bearer("not-a-compact-token")) + .await; + run.observe( + "wrong-audience", + &fresh(), + bearer(&issue(CLIENT, "urn:elsewhere", SCOPE, now() + 300)), + ) + .await; + run.observe( + "client-not-allowed", + &fresh(), + bearer(&issue("another-host", RESOURCE, SCOPE, now() + 300)), + ) + .await; + run.observe( + "expired", + &fresh(), + bearer(&issue(CLIENT, RESOURCE, SCOPE, now() - 120)), + ) + .await; + run.observe( + "scope-missing", + &fresh(), + bearer(&issue(CLIENT, RESOURCE, "openid", now() + 300)), + ) + .await; + + let (app, server) = fresh(); + let response = app + .clone() + .oneshot( + Request::post("/mcp") + .header(header::HOST, "attacker.example.test") + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + run.record("host-not-admitted", &server, summarise(response).await); + run.observe( + "origin-present", + &fresh(), + vec![( + header::ORIGIN, + HeaderValue::from_static("https://elsewhere.example.test"), + )], + ) + .await; + + let token = issue(CLIENT, RESOURCE, SCOPE, now() + 300); + let limited = application(&auth, auth.jwks_uri(), 1); + let first = limited + .0 + .clone() + .oneshot(request(bearer(&token))) + .await + .expect("response"); + assert_ne!(first.status(), StatusCode::TOO_MANY_REQUESTS); + run.observe("rate-limited", &limited, bearer(&token)).await; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let closed = format!( + "http://{}/jwks.json", + listener.local_addr().expect("address") + ); + drop(listener); + run.observe( + "key-set-unreachable", + &application(&auth, closed, 100), + bearer(&token), + ) + .await; + run +} + +async fn summarise(response: axum::response::Response) -> Value { + let status = response.status(); + let mut readable = BTreeMap::new(); + for name in [ + header::CONTENT_TYPE, + header::CACHE_CONTROL, + header::WWW_AUTHENTICATE, + header::RETRY_AFTER, + ] { + if let Some(value) = response.headers().get(&name) { + // The delay depends on the clock, so only its presence is frozen. + let text = if name == header::RETRY_AFTER { + "present".to_owned() + } else { + value.to_str().expect("ASCII header").to_owned() + }; + readable.insert(name.as_str().to_owned(), text); + } + } + let bytes = axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .expect("body"); + let body: Value = serde_json::from_slice(&bytes).expect("a problem document"); + json!({"status": status.as_u16(), "headers": readable, "body": body}) +} + +#[tokio::test(flavor = "current_thread")] +async fn every_refusal_answers_exactly_as_the_golden_file_records() { + let answers = serde_json::to_value(drive().await.answers).expect("answers serialize"); + if std::env::var_os("REGISTRY_MCP_EDGE_WRITE_GOLDEN").is_some() { + let mut text = serde_json::to_string_pretty(&answers).expect("golden text"); + text.push('\n'); + std::fs::write(GOLDEN_PATH, text).expect("the golden file is written"); + } + let golden: Value = serde_json::from_str(GOLDEN).expect("the golden file is JSON"); + assert_eq!(answers, golden); +} + +/// The check each refusal counts, one request each. +const COUNTED: [(&str, &str); 15] = [ + ("no-authorization-header", "credential-missing"), + ("non-bearer-scheme", "credential-missing"), + ("bearer-without-token", "credential-malformed"), + ("bearer-with-two-spaces", "credential-malformed"), + ("repeated-authorization-header", "credential-malformed"), + ("unreadable-authorization-header", "credential-malformed"), + ("not-a-jwt", "credential-malformed"), + ("wrong-audience", "token-audience"), + ("client-not-allowed", "token-client"), + ("expired", "token-time"), + ("scope-missing", "scope"), + ("host-not-admitted", "host-origin"), + ("origin-present", "host-origin"), + ("rate-limited", "rate-limit"), + ("key-set-unreachable", "key-source-unavailable"), +]; + +#[tokio::test(flavor = "current_thread")] +async fn each_refusal_counts_once_under_its_check() { + let run = drive().await; + assert_eq!(run.counted.len(), COUNTED.len()); + for (name, check) in COUNTED { + assert_eq!(run.counted[name], BTreeMap::from([(check, 1)]), "{name}"); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn a_refusal_writes_one_line_with_its_check_and_no_caller_value() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + + let logs = CapturedDiagnosticLogs::default(); + let auth = authorization().await; + let token = auth.issue_access_token(CLIENT, "citizen-canary", RESOURCE, "openid", now() + 300); + let (app, _) = application(&auth, auth.jwks_uri(), 100); + let response = app + .oneshot(request(bearer(&token))) + .with_subscriber(logs.subscriber()) + .await + .expect("response"); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let text = logs.text(); + let lines: Vec<&str> = text + .lines() + .filter(|line| line.contains("request refused")) + .collect(); + assert_eq!(lines.len(), 1, "{text}"); + assert!(lines[0].contains("\"failed_check\":\"scope\""), "{text}"); + for canary in [token.as_str(), "citizen-canary", CLIENT, "openid"] { + assert!(!text.contains(canary), "{canary} reached the log: {text}"); + } +} diff --git a/crates/registry-mcp-edge/src/server.rs b/crates/registry-mcp-edge/src/server.rs index fc9c83e50e..83fdc4574f 100644 --- a/crates/registry-mcp-edge/src/server.rs +++ b/crates/registry-mcp-edge/src/server.rs @@ -11,6 +11,7 @@ use axum::{ routing::get, Json, Router, }; +use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote, RefusalRecorder}; use registry_platform_httpsec::{request_body_limit, security_headers, CspBuilder, Problem}; use rmcp::transport::streamable_http_server::{ session::never::NeverSessionManager, StreamableHttpServerConfig, StreamableHttpService, @@ -79,16 +80,23 @@ impl ResourceAuthority { } } +/// The host and origin check, with the recorder that counts its refusals. +struct HostGate { + authority: Option, + refusals: Arc, +} + async fn require_resource_host( - State(authority): State>>, + State(gate): State>, request: Request, next: Next, ) -> Response { - let admitted = authority - .as_ref() + let admitted = gate + .authority .as_ref() .is_some_and(|authority| authority.admits(request.uri(), request.headers())); if !admitted || request.headers().contains_key(header::ORIGIN) { + record_refusal!(gate.refusals, RefusalNote::new(FailedCheck::HostOrigin)); return forbidden(); } next.run(request).await @@ -118,7 +126,10 @@ pub fn router( require_caller, )) .layer(from_fn_with_state( - Arc::new(ResourceAuthority::of(&options.resource)), + Arc::new(HostGate { + authority: ResourceAuthority::of(&options.resource), + refusals: Arc::clone(resource_server.refusal_recorder()), + }), require_resource_host, )); let metadata_path = format!("{METADATA_PREFIX}{MCP_PATH}"); diff --git a/crates/registry-mcp-edge/tests/golden/refusals.json b/crates/registry-mcp-edge/tests/golden/refusals.json new file mode 100644 index 0000000000..6b9a6a6e00 --- /dev/null +++ b/crates/registry-mcp-edge/tests/golden/refusals.json @@ -0,0 +1,224 @@ +{ + "bearer-with-two-spaces": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "bearer-without-token": { + "body": { + "code": "unauthorized", + "detail": "A bearer access token is required.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "client-not-allowed": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "expired": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "host-not-admitted": { + "body": { + "code": "forbidden", + "detail": "The request's host or origin is not accepted.", + "status": 403, + "title": "Forbidden", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "key-set-unreachable": { + "body": { + "code": "temporarily-unavailable", + "detail": "The gateway cannot verify the request right now.", + "status": 503, + "title": "Service Unavailable", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 503 + }, + "no-authorization-header": { + "body": { + "code": "unauthorized", + "detail": "A bearer access token is required.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "non-bearer-scheme": { + "body": { + "code": "unauthorized", + "detail": "A bearer access token is required.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "not-a-jwt": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "origin-present": { + "body": { + "code": "forbidden", + "detail": "The request's host or origin is not accepted.", + "status": 403, + "title": "Forbidden", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "rate-limited": { + "body": { + "code": "rate-limited", + "detail": "Too many requests; retry after the indicated delay.", + "status": 429, + "title": "Too Many Requests", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "present" + }, + "status": 429 + }, + "repeated-authorization-header": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "scope-missing": { + "body": { + "code": "insufficient-scope", + "detail": "The access token lacks a required scope.", + "status": 403, + "title": "Forbidden", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"insufficient_scope\", scope=\"test:read\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 403 + }, + "unreadable-authorization-header": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "wrong-audience": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + } +} diff --git a/crates/registry-mcp/src/config.rs b/crates/registry-mcp/src/config.rs index dd621672ef..eaaf39b7ee 100644 --- a/crates/registry-mcp/src/config.rs +++ b/crates/registry-mcp/src/config.rs @@ -10,13 +10,13 @@ use registry_platform_config::{ PrivateListenerConfig, RemovedKey, RuntimeConfigLoader, RuntimeEnvelope, SecretProvidersConfig, SecretReference, TlsTermination, MAX_OIDC_AUDIENCE_CHARACTERS, }; +use registry_platform_httputil::loopback::loopback_host; use registry_platform_yaml::{Diagnostic, Digest, LocalId, Report, UniqueList, Url}; use serde::Deserialize; use std::{ collections::BTreeSet, path::{Path, PathBuf}, }; -use url::Host; pub const API_VERSION: &str = "id.registrystack.org/formats/platform/mcp-runtime/v1alpha1"; pub const KIND: &str = "PlatformMcpRuntimeConfig"; @@ -273,9 +273,7 @@ impl RuntimeConfig { let protected_endpoint = |url: url::Url| { registry_platform_httputil::client::ServiceBaseUrl::new(url.clone()).is_ok() && (url.scheme() == "https" - || (url.scheme() == "http" - && self.development_loopback() - && loopback_host(&url))) + || (url.scheme() == "http" && self.development_loopback() && is_loopback(&url))) }; if self .bindings @@ -602,13 +600,9 @@ impl RuntimeConfig { } } -fn loopback_host(url: &url::Url) -> bool { - match url.host() { - Some(Host::Ipv4(address)) => address.is_loopback(), - Some(Host::Ipv6(address)) => address.is_loopback(), - Some(Host::Domain(name)) => name.eq_ignore_ascii_case("localhost"), - None => false, - } +fn is_loopback(url: &url::Url) -> bool { + url.host_str() + .is_some_and(|host| loopback_host(host).is_some()) } fn valid_digest(value: &str) -> bool { diff --git a/crates/registry-mcp/src/runtime.rs b/crates/registry-mcp/src/runtime.rs index 246a180084..68cbb7d6d7 100644 --- a/crates/registry-mcp/src/runtime.rs +++ b/crates/registry-mcp/src/runtime.rs @@ -17,7 +17,7 @@ use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::client::StaticToken; use registry_platform_oidc::{ fetch_discovery_for_issuer, parse_static_jwks, IssuerNetworkPolicy, JwksFetcher, - JwksFetcherConfig, OidcDiscoveryConfig, + JwksFetcherConfig, OidcDiscoveryConfig, OidcError, }; use std::{fmt, future::Future, io, sync::Arc, time::Duration}; use zeroize::Zeroizing; @@ -85,10 +85,33 @@ fn secret_failure(field: String, reference: &str, error: &SecretError) -> Startu ) } -fn invalid_secret_value(field: String, cause: &'static str, remedy: &'static str) -> StartupError { +fn invalid_secret_value( + field: String, + cause: impl Into, + remedy: &'static str, +) -> StartupError { startup_failure(field, cause, remedy) } +/// Reads the static key document. A refusal of the document's own contents +/// names what it refused, in words that carry no key material. +fn static_key_fetcher(bytes: &[u8], field: String) -> Result { + let keys = parse_static_jwks(bytes).map_err(|error| { + let cause = match &error { + OidcError::StaticKeySet(refused) => { + format!("the resolved secret is not a usable JWKS document: {refused}") + } + _ => "the resolved secret is not a usable JWKS document".to_owned(), + }; + invalid_secret_value( + field, + cause, + "Replace it with a bounded JSON Web Key Set containing the issuer's active verification keys.", + ) + })?; + Ok(JwksFetcher::new_static(keys, JwksFetcherConfig::defaults())) +} + fn audit_failure(error: AuditError) -> StartupError { startup_failure( "audit", @@ -178,14 +201,7 @@ pub async fn build(config: &RuntimeConfig) -> Result { document_ref, "resourceServer.jwksSource.documentRef".to_owned(), )?; - let keys = parse_static_jwks(&bytes).map_err(|_| { - invalid_secret_value( - "resourceServer.jwksSource.documentRef".to_owned(), - "the resolved secret is not a usable JWKS document", - "Replace it with a bounded JSON Web Key Set containing the issuer's active verification keys.", - ) - })?; - JwksFetcher::new_static(keys, JwksFetcherConfig::defaults()) + static_key_fetcher(&bytes, "resourceServer.jwksSource.documentRef".to_owned())? } JwksSource::Discovery {} => { let (discovery, network) = fetch_discovery_for_issuer( @@ -499,6 +515,35 @@ mod tests { use super::*; + /// A public EC key as a provider publishes it, with members the verifier + /// does not read. + fn provider_key_set(extra: &str) -> Vec { + format!( + r#"{{"keys":[{{"kty":"EC","crv":"P-256","kid":"key-1","use":"sig","alg":"ES256","ext":true,"x5c":["MIIB"],"x5t":"abc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"{extra}}}]}}"# + ) + .into_bytes() + } + + #[test] + fn a_static_key_set_with_unknown_public_members_loads() { + static_key_fetcher(&provider_key_set(""), "field".to_owned()) + .expect("a provider key set with ext and x5c members loads"); + } + + #[test] + fn a_static_key_set_with_a_private_member_is_refused_with_the_validator_text() { + let Err(error) = static_key_fetcher( + &provider_key_set(r#","d":"CANARY-PRIVATE""#), + "field".to_owned(), + ) else { + panic!("a private member is refused"); + }; + let error = error.to_string(); + assert!(error.contains("not a usable JWKS document"), "{error}"); + assert!(error.contains("private-key member \"d\""), "{error}"); + assert!(!error.contains("CANARY-PRIVATE"), "{error}"); + } + #[test] fn missing_secret_and_malformed_key_have_distinct_value_free_guidance() { const CANARY_REFERENCE: &str = "secret:env/DO_NOT_PRINT_THIS_NAME"; diff --git a/crates/registry-messaging/Cargo.toml b/crates/registry-messaging/Cargo.toml index 59cc34143d..8b40642fbe 100644 --- a/crates/registry-messaging/Cargo.toml +++ b/crates/registry-messaging/Cargo.toml @@ -79,12 +79,12 @@ lettre.workspace = true registry-messaging-core.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true registry-platform-dispatch = { workspace = true, features = ["postgres"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-httputil.workspace = true registry-platform-metrics.workspace = true registry-platform-oidc.workspace = true diff --git a/crates/registry-messaging/src/auth.rs b/crates/registry-messaging/src/auth.rs index e1d61d0d7e..120d26d232 100644 --- a/crates/registry-messaging/src/auth.rs +++ b/crates/registry-messaging/src/auth.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use registry_messaging_core::{ AccessProfiles, AccessRefusal, ActorKind, ActorKindClaim, Caller, VerifiedTokenFacts, }; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; use registry_platform_oidc::{ actor_kind, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, @@ -34,14 +34,6 @@ pub struct MessagingAuthenticator { } impl MessagingAuthenticator { - pub(crate) fn record_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Header, - "Messaging authentication refused" - ); - } - #[must_use] pub fn new( verifier: TokenVerifierConfig, @@ -63,18 +55,13 @@ impl MessagingAuthenticator { /// Verify one credential and resolve it to exactly one access profile. pub async fn authenticate(&self, token: &str) -> Result { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Messaging authentication refused" - ); - verifier_failure(&error) - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| verifier_failure(&error))?; // An exchanged token names the authority whose assertion produced it. // The platform applies no rule while the deployment's map is empty, so // an empty map would trust every authority the issuer federates. @@ -83,14 +70,13 @@ impl MessagingAuthenticator { if !self.binds_assertion_issuers && verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - tracing::debug!( - "an exchanged credential arrived at a deployment that declared no assertion authority" - ); - return Err(AuthenticationError::Profile); + return Err(AuthenticationError::Profile( + FailedCheck::TokenAssertionIssuer, + )); } let client_id = verified .matched_client_id() - .map_err(|_| AuthenticationError::Claims)?; + .map_err(|_| AuthenticationError::Claims(FailedCheck::TokenClient))?; let facts = VerifiedTokenFacts { issuer: verified.claims.iss.as_deref(), subject: verified.claims.sub.as_deref(), @@ -101,23 +87,42 @@ impl MessagingAuthenticator { }; self.profiles .resolve(&facts) - .map_err(|refusal| match refusal { - AccessRefusal::Profile => { - let (stage, remedy) = if self.profiles.missing_scope(&facts).is_some() { - (registry_platform_oidc::AuthenticationStage::Scope, "check authentication.oidc.scopeClaim and accessProfiles requiredScopes") - } else { - (registry_platform_oidc::AuthenticationStage::Profile, "check accessProfiles actorKind and requesterClients") - }; - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - stage, - "Messaging authentication profile refused", - remedy = remedy - ); - AuthenticationError::Profile - } - AccessRefusal::Claims => AuthenticationError::Claims, - }) + .map_err(|refusal| self.access_refusal(refusal, &facts)) + } + + /// The error a refused profile resolution answers with, and the check it + /// names. + fn access_refusal( + &self, + refusal: AccessRefusal, + facts: &VerifiedTokenFacts<'_>, + ) -> AuthenticationError { + match refusal { + AccessRefusal::Profile => { + let check = if self.profiles.missing_scope(facts).is_some() { + FailedCheck::Scope + } else if self.profiles.iter().any(|profile| { + facts.client_id.is_some_and(|client| { + profile + .requester_clients + .iter() + .any(|named| named == client) + }) + }) { + FailedCheck::ActorKind + } else { + FailedCheck::AccessProfile + }; + AuthenticationError::Profile(check) + } + AccessRefusal::Claims => AuthenticationError::Claims( + if matches!(facts.actor_kind, ActorKindClaim::Malformed) { + FailedCheck::ActorKind + } else { + FailedCheck::TokenClaims + }, + ), + } } } @@ -134,11 +139,11 @@ impl std::fmt::Debug for MessagingAuthenticator { #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] - Refused, + Refused(FailedCheck), #[error("the verified identity claims are invalid")] - Claims, + Claims(FailedCheck), #[error("the caller's access profile is not authorized for this request")] - Profile, + Profile(FailedCheck), /// The verifier could not reach a verdict at all. #[error("the credential could not be verified because this verifier cannot answer")] Unavailable, @@ -168,7 +173,7 @@ fn verifier_failure(error: &OidcError) -> AuthenticationError { // signal, and answering 503 there would let a caller probe the key // set. A variant the platform adds later reads as a refusal until it // is classified here, so a new outcome can never widen the door. - _ => AuthenticationError::Refused, + _ => AuthenticationError::Refused(error.failed_check()), } } @@ -198,8 +203,6 @@ pub(crate) mod tests { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; - use crate::smtp::tests::Captured; - pub(crate) const ISSUER: &str = "https://task-token.test"; pub(crate) const AUDIENCE: &str = "urn:registry-messaging:test"; pub(crate) const SENDER_CLIENT: &str = "case-system"; @@ -366,26 +369,38 @@ pub(crate) mod tests { #[tokio::test] async fn a_credential_that_is_not_a_compact_token_is_refused() { for credential in ["", "not-a-jwt", "a.b", "a b.c.d"] { - assert_eq!(refusal(credential).await, AuthenticationError::Refused); + assert_eq!( + refusal(credential).await, + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); } } #[tokio::test] async fn a_forged_signature_is_refused() { let forged = token_signed_with(sender_claims(), b"another-secret-another-secret-another!"); - assert_eq!(refusal(&forged).await, AuthenticationError::Refused); + assert_eq!( + refusal(&forged).await, + AuthenticationError::Refused(FailedCheck::TokenSignature) + ); } #[tokio::test] async fn a_token_for_another_audience_or_issuer_is_refused() { let other_audience = token(with(sender_claims(), "aud", json!("urn:elsewhere"))); - assert_eq!(refusal(&other_audience).await, AuthenticationError::Refused); + assert_eq!( + refusal(&other_audience).await, + AuthenticationError::Refused(FailedCheck::TokenAudience) + ); let other_issuer = token(with( sender_claims(), "iss", json!("https://elsewhere.test"), )); - assert_eq!(refusal(&other_issuer).await, AuthenticationError::Refused); + assert_eq!( + refusal(&other_issuer).await, + AuthenticationError::Refused(FailedCheck::TokenIssuer) + ); } #[tokio::test] @@ -396,7 +411,10 @@ pub(crate) mod tests { "iat", json!(now - 900), )); - assert_eq!(refusal(&expired).await, AuthenticationError::Refused); + assert_eq!( + refusal(&expired).await, + AuthenticationError::Refused(FailedCheck::TokenTime) + ); } #[tokio::test] @@ -412,19 +430,28 @@ pub(crate) mod tests { header.typ = Some("JWT".to_owned()); let id_token = jsonwebtoken::encode(&header, &claims, &EncodingKey::from_secret(SECRET)).unwrap(); - assert_eq!(refusal(&id_token).await, AuthenticationError::Refused); + assert_eq!( + refusal(&id_token).await, + AuthenticationError::Refused(FailedCheck::TokenType) + ); } #[tokio::test] async fn a_client_the_deployment_does_not_admit_is_refused() { let stranger = token(with(sender_claims(), "azp", json!("unrelated-app"))); - assert_eq!(refusal(&stranger).await, AuthenticationError::Refused); + assert_eq!( + refusal(&stranger).await, + AuthenticationError::Refused(FailedCheck::TokenClient) + ); } #[tokio::test] async fn an_admitted_client_without_a_profile_is_not_authorized() { let unprofiled = token(with(sender_claims(), "azp", json!(UNPROFILED_CLIENT))); - assert_eq!(refusal(&unprofiled).await, AuthenticationError::Profile); + assert_eq!( + refusal(&unprofiled).await, + AuthenticationError::Profile(FailedCheck::AccessProfile) + ); } #[tokio::test] @@ -434,70 +461,58 @@ pub(crate) mod tests { "registry_scopes", json!("messaging:read"), )); - assert_eq!(refusal(&no_scope).await, AuthenticationError::Profile); + assert_eq!( + refusal(&no_scope).await, + AuthenticationError::Profile(FailedCheck::Scope) + ); let mut absent = sender_claims(); absent.as_object_mut().unwrap().remove("registry_scopes"); - assert_eq!(refusal(&token(absent)).await, AuthenticationError::Profile); - } - - #[tokio::test] - async fn a_scope_refusal_logs_only_a_fixed_stage_and_no_values() { - let captured = Captured::install(); - let credential = token(with( - sender_claims(), - "registry_scopes", - json!("messaging:read"), - )); - assert_eq!(refusal(&credential).await, AuthenticationError::Profile); - let logs = captured.finish(); - assert!(logs.contains("scope"), "{logs}"); - for needle in [ - credential.as_str(), - "messaging:read", - "case-system", - "registry_actor_kind", - "registry_scopes", - "messaging:send", - "case-notices", - ] { - assert!(!logs.contains(needle), "logs carry {needle:?}:\n{logs}"); - } - } - - #[tokio::test] - async fn an_actor_kind_refusal_logs_no_scope_advice() { - let captured = Captured::install(); - let human = token(with(sender_claims(), "registry_actor_kind", json!("human"))); - assert_eq!(refusal(&human).await, AuthenticationError::Profile); - let logs = captured.finish(); - assert!(!logs.contains("scopeClaim"), "{logs}"); + assert_eq!( + refusal(&token(absent)).await, + AuthenticationError::Profile(FailedCheck::Scope) + ); } #[tokio::test] async fn an_actor_kind_the_profile_does_not_admit_is_not_authorized() { let human = token(with(sender_claims(), "registry_actor_kind", json!("human"))); - assert_eq!(refusal(&human).await, AuthenticationError::Profile); + assert_eq!( + refusal(&human).await, + AuthenticationError::Profile(FailedCheck::ActorKind) + ); let mut absent = sender_claims(); absent .as_object_mut() .unwrap() .remove("registry_actor_kind"); - assert_eq!(refusal(&token(absent)).await, AuthenticationError::Profile); + assert_eq!( + refusal(&token(absent)).await, + AuthenticationError::Profile(FailedCheck::ActorKind) + ); } #[tokio::test] async fn a_malformed_actor_kind_is_a_claims_refusal() { let malformed = token(with(sender_claims(), "registry_actor_kind", json!("robot"))); - assert_eq!(refusal(&malformed).await, AuthenticationError::Claims); + assert_eq!( + refusal(&malformed).await, + AuthenticationError::Claims(FailedCheck::ActorKind) + ); let operator = token(with(operator_claims(), "registry_actor_kind", json!(7))); - assert_eq!(refusal(&operator).await, AuthenticationError::Claims); + assert_eq!( + refusal(&operator).await, + AuthenticationError::Claims(FailedCheck::ActorKind) + ); } #[tokio::test] async fn a_token_without_a_principal_is_a_claims_refusal() { let mut claims = sender_claims(); claims.as_object_mut().unwrap().remove("sub"); - assert_eq!(refusal(&token(claims)).await, AuthenticationError::Claims); + assert_eq!( + refusal(&token(claims)).await, + AuthenticationError::Claims(FailedCheck::TokenClaims) + ); } #[tokio::test] @@ -507,7 +522,10 @@ pub(crate) mod tests { registry_platform_oidc::ASSERTION_ISSUER_CLAIM, json!("https://assertions.example.test"), )); - assert_eq!(refusal(&exchanged).await, AuthenticationError::Profile); + assert_eq!( + refusal(&exchanged).await, + AuthenticationError::Profile(FailedCheck::TokenAssertionIssuer) + ); let declaring = MessagingAuthenticator::new( verifier(&[(SENDER_CLIENT, "https://assertions.example.test")]), @@ -583,32 +601,11 @@ pub(crate) mod tests { ] { assert_eq!( verifier_failure(&refusal), - AuthenticationError::Refused, + AuthenticationError::Refused(refusal.failed_check()), "{refusal} was excused as an outage" ); } } - #[tokio::test] - async fn compact_token_admission_logs_one_value_free_header_diagnostic() { - use registry_platform_testing::{malformed_access_token_fixtures, CapturedDiagnosticLogs}; - use tracing::instrument::WithSubscriber; - let captured = CapturedDiagnosticLogs::default(); - let subscriber = captured.subscriber(); - let tokens = malformed_access_token_fixtures(); - let auth = authenticator(); - for _ in 0..3 { - for token in &tokens { - assert!(matches!( - auth.authenticate(token) - .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - } - } - captured.assert_one_value_free_header_diagnostic(&tokens); - } - #[tokio::test] async fn separate_resource_rs256_and_es256_profiles_refuse_cross_resource_reuse() { for algorithm in [AccessTokenAlgorithm::RS256, AccessTokenAlgorithm::ES256] @@ -650,28 +647,28 @@ pub(crate) mod tests { let auth = &auth; async move { auth.authenticate(&token).await } }, - |error| matches!(error, AuthenticationError::Refused), + |error| matches!(error, AuthenticationError::Refused(_)), ) .await; // A valid symmetric JWT is outside the asymmetric production baseline. let token = self::token(sender_claims()); assert!(matches!( auth.authenticate(&token).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(_)) )); let mut wrong_actor = claims.clone(); wrong_actor["registry_actor_kind"] = json!("canary-invalid-actor"); let token = sign(wrong_actor, "at+jwt"); assert!(matches!( auth.authenticate(&token).await, - Err(AuthenticationError::Claims) + Err(AuthenticationError::Claims(_)) )); let mut missing = claims.clone(); missing["registry_scopes"] = json!(""); let token = sign(missing, "at+jwt"); assert!(matches!( auth.authenticate(&token).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(_)) )); } } diff --git a/crates/registry-messaging/src/callbacks.rs b/crates/registry-messaging/src/callbacks.rs index 1af963790c..8f9f18d739 100644 --- a/crates/registry-messaging/src/callbacks.rs +++ b/crates/registry-messaging/src/callbacks.rs @@ -12,7 +12,9 @@ //! that does not verify, and a token segment on a provider whose verifier is //! not `path-token` (or none on one whose verifier is) all answer //! `callback.unverified` alike, so the route reveals neither which providers -//! receive callbacks nor why a request was refused. +//! receive callbacks nor why a request was refused. The operator learns why +//! from the refusal's failed check, counted on the metrics listener and named +//! in one bounded log line that carries nothing the caller sent. //! //! A verified callback answers 204 when its receipt was applied, changed //! nothing, reported nothing this runtime records, or named no message: @@ -34,8 +36,10 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{HeaderMap, StatusCode, Uri}; use axum::response::{IntoResponse, Response}; use registry_messaging_core::{ - verify_callback, CallbackRequest, ProblemCode, Receipt, PROVIDER_CALLBACK_PATH, + verify_callback, CallbackRequest, CallbackVerificationRefusal, ProblemCode, Receipt, + PROVIDER_CALLBACK_PATH, }; +use registry_platform_authcommon::FailedCheck; use crate::http::{rate_limited_response, read_request_body, HttpError, HttpState}; use crate::http_provider::ReceiptScriptError; @@ -85,7 +89,7 @@ async fn answer( Err(LimitRefusal::Unavailable) => { tracing::error!("the Messaging callback-rate limiter could not decide"); state.metrics.record_callback(CallbackOutcome::Unavailable); - return Err(HttpError(ProblemCode::ServiceUnavailable).into_response()); + return Err(HttpError::problem(ProblemCode::ServiceUnavailable).into_response()); } } let uri = request.uri().clone(); @@ -96,22 +100,39 @@ async fn answer( let (outcome, answer) = match receive_callback(state, provider_id, token, &uri, &headers, body).await { Ok(outcome) => (outcome, Ok(StatusCode::NO_CONTENT)), - Err((outcome, problem)) => (outcome, Err(HttpError(problem).into_response())), + Err((outcome, error)) => (outcome, Err(error.into_response())), }; state.metrics.record_callback(outcome); answer } -type Refusal = (CallbackOutcome, ProblemCode); +type Refusal = (CallbackOutcome, HttpError); -const fn unverified() -> Refusal { - (CallbackOutcome::Unverified, ProblemCode::CallbackUnverified) +/// A callback that did not verify, and the check that failed. +fn unverified(check: FailedCheck) -> Refusal { + ( + CallbackOutcome::Unverified, + HttpError::refused(ProblemCode::CallbackUnverified, check), + ) +} + +/// The check a verifier's refusal names: a missing or wrong path token is a +/// shared secret that did not match, every other refusal a signature that did +/// not. +const fn verification_check(refusal: CallbackVerificationRefusal) -> FailedCheck { + match refusal { + CallbackVerificationRefusal::MissingHeader + | CallbackVerificationRefusal::MalformedSignature + | CallbackVerificationRefusal::SignatureMismatch => FailedCheck::DeliverySignature, + CallbackVerificationRefusal::MissingPathToken + | CallbackVerificationRefusal::TokenMismatch => FailedCheck::SharedSecret, + } } -const fn unavailable() -> Refusal { +fn unavailable() -> Refusal { ( CallbackOutcome::Unavailable, - ProblemCode::ServiceUnavailable, + HttpError::problem(ProblemCode::ServiceUnavailable), ) } @@ -124,15 +145,10 @@ async fn receive_callback( body: Bytes, ) -> Result { let Some(receiver) = state.callbacks.get(provider_id).map(Arc::clone) else { - tracing::warn!("a provider callback named no provider that receives callbacks"); - return Err(unverified()); + return Err(unverified(FailedCheck::DeliveryBinding)); }; if receiver.uses_path_token() != token.is_some() { - tracing::warn!( - provider = provider_id, - "a provider callback arrived on the route its verifier does not use" - ); - return Err(unverified()); + return Err(unverified(FailedCheck::DeliveryBinding)); } let path = PROVIDER_CALLBACK_PATH.replace("{provider_id}", provider_id); let callback = OwnedCallback { @@ -157,12 +173,7 @@ async fn receive_callback( if let Err(refusal) = callback.with_request(|request| verify_callback(&receiver.verifier(), request)) { - tracing::warn!( - provider = provider_id, - reason = %refusal, - "a provider callback did not verify" - ); - return Err(unverified()); + return Err(unverified(verification_check(refusal))); } let Some(service) = state.messages.as_deref() else { return Err(unavailable()); @@ -192,7 +203,10 @@ async fn receive_callback( reason = %error, "a verified provider callback could not be read" ); - return Err((CallbackOutcome::Unreadable, ProblemCode::CallbackUnreadable)); + return Err(( + CallbackOutcome::Unreadable, + HttpError::problem(ProblemCode::CallbackUnreadable), + )); } }; let recorded = service diff --git a/crates/registry-messaging/src/config.rs b/crates/registry-messaging/src/config.rs index 4347591b96..69947141f2 100644 --- a/crates/registry-messaging/src/config.rs +++ b/crates/registry-messaging/src/config.rs @@ -33,7 +33,8 @@ use registry_platform_config::{ }; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifierConfig, }; use registry_platform_yaml::{escape_pointer_segment, Diagnostic, Report, RetiredApiVersion}; use serde::{Deserialize, Deserializer}; @@ -939,8 +940,19 @@ impl RuntimeConfig { &error, )) })?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| RuntimeConfigError::Oidc)?; + let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { + match error { + // The document is the operator's own file, so its text names the + // rule it breaks and never a key value. + OidcError::StaticKeySet(refused) => { + RuntimeConfigError::OidcJwksSecret(format!( + "the document authentication.oidc.jwksSource.documentRef names \ + is not a usable static key set: {refused}" + )) + } + _ => RuntimeConfigError::Oidc, + } + })?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -1907,6 +1919,92 @@ pub(crate) mod tests { ); } + /// Load a runtime whose static key source names `document`, and build the + /// key source from it. + #[cfg(unix)] + async fn static_key_source(document: &str) -> Result<(), RuntimeConfigError> { + use std::os::unix::fs::PermissionsExt as _; + + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = root.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let file = secrets.join("issuer-jwks"); + std::fs::write(&file, document).unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut runtime = runtime_value(root.path()); + runtime["authentication"]["oidc"]["jwksSource"] = + json!({"type": "static", "documentRef": "secret:file/issuer-jwks"}); + let path = write_project(root.path(), &runtime, &package_value()); + let config = RuntimeConfig::load_with_environment(path, &no_environment)?; + let resolver = config.secret_resolver()?; + config.jwks_fetcher(&resolver).await.map(|_| ()) + } + + fn static_key(extra: Value) -> Value { + let mut key = json!({ + "kty": "RSA", + "kid": "issuer-key-1", + "use": "sig", + "alg": "RS256", + "n": "sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw", + "e": "AQAB", + }); + for (name, value) in extra.as_object().unwrap() { + key[name] = value.clone(); + } + key + } + + #[cfg(unix)] + #[tokio::test] + async fn a_static_key_set_with_members_it_does_not_know_loads() { + let key = static_key( + json!({"ext": true, "x5t": "abc", "x5u": "https://identity.example.test/cert"}), + ); + let document = json!({"keys": [key], "issuer": "https://identity.example.test"}); + static_key_source(&document.to_string()) + .await + .expect("a public key set with unknown members loads"); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_static_key_set_that_holds_a_private_member_is_refused_with_the_rule() { + for member in ["d", "p", "q", "dp", "dq", "qi", "oth", "k"] { + let key = static_key(json!({ member: "canary-private-value" })); + let document = json!({"keys": [key]}); + let error = static_key_source(&document.to_string()) + .await + .expect_err(member); + assert!( + matches!(error, RuntimeConfigError::OidcJwksSecret(_)), + "{member}: {error}" + ); + assert_eq!(error.code(), "messaging.runtime.unreadable-jwks-secret"); + let text = error.to_string(); + assert!( + text.contains(&format!("private-key member \"{member}\"")), + "{member}: {text}" + ); + assert!(!text.contains("canary-private-value"), "{text}"); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn a_static_key_set_that_repeats_a_member_name_is_refused() { + let document = r#"{"keys":[{"kty":"RSA","kid":"a","kid":"b","n":"AQAB","e":"AQAB"}]}"#; + let error = static_key_source(document) + .await + .expect_err("a repeated member"); + assert_eq!(error.code(), "messaging.runtime.unreadable-jwks-secret"); + assert!( + error.to_string().contains("repeats a member name"), + "{error}" + ); + } + fn no_environment(_: &str) -> Option { None } diff --git a/crates/registry-messaging/src/http.rs b/crates/registry-messaging/src/http.rs index b3b5657b36..916a8a87e5 100644 --- a/crates/registry-messaging/src/http.rs +++ b/crates/registry-messaging/src/http.rs @@ -50,7 +50,9 @@ use registry_messaging_core::{ MESSAGE_CANCEL_PATH, MESSAGE_PATH, MESSAGE_RECEIPT_PATH, METRICS_PATH, PROVIDER_CALLBACK_PATH, PROVIDER_CALLBACK_TOKEN_PATH, READY_PATH, TEMPLATE_PREVIEW_PATH, }; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, record_refusal, BearerParseError, FailedCheck, RefusalNote, +}; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, @@ -382,6 +384,7 @@ const CALLBACK_PROBLEMS: [ProblemCode; 7] = [ pub fn router(state: HttpState) -> Router { let metrics = Arc::clone(&state.metrics); + let refusals = Arc::clone(&state.metrics); http_edge( Router::new() .route(HEALTH_PATH, get(health)) @@ -397,6 +400,7 @@ pub fn router(state: HttpState) -> Router { post(callbacks::receive_with_token), ) .with_state(state) + .layer(middleware::from_fn_with_state(refusals, record_refusals)) .layer(middleware::from_fn_with_state(metrics, count_requests)), ) } @@ -465,7 +469,7 @@ async fn ready(State(state): State) -> Result if state.readiness.is_ready().await { Ok(StatusCode::OK) } else { - Err(HttpError(ProblemCode::ServiceUnavailable)) + Err(HttpError::problem(ProblemCode::ServiceUnavailable)) } } @@ -478,17 +482,17 @@ async fn submit_message( let mut audit = state .audit .begin(serde_json::to_value(requested).map_err(|_| { - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?) .await .map_err(|error| { tracing::error!(error = %error, "the Messaging audit destination refused a submission request"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; let result = match admit_submission(&state, &caller, request.headers()).await { Ok(key) => match read_request_body(request).await { Ok(body) => accept_submission(&state, &caller, &key, &body).await, - Err(HttpError(problem)) => Err(problem.into()), + Err(error) => Err(error.code().into()), }, Err(refusal) => Err(refusal), }; @@ -496,9 +500,9 @@ async fn submit_message( Ok(answer) if !answer.replayed => answer .audit_record .clone() - .ok_or(HttpError(ProblemCode::ServiceUnavailable))?, + .ok_or(HttpError::problem(ProblemCode::ServiceUnavailable))?, Ok(answer) => serde_json::to_value(SubmissionRecord::replayed(&state, &caller, answer)?) - .map_err(|_| HttpError(ProblemCode::ServiceUnavailable))?, + .map_err(|_| HttpError::problem(ProblemCode::ServiceUnavailable))?, Err(refusal) if refusal.problem == ProblemCode::ServiceUnavailable => { count_limit_refusal(&state.metrics, refusal.problem); return Ok(refusal_response(*refusal)); @@ -506,12 +510,12 @@ async fn submit_message( Err(refusal) => { count_limit_refusal(&state.metrics, refusal.problem); serde_json::to_value(SubmissionRecord::refused(&state, &caller, refusal.problem)?) - .map_err(|_| HttpError(ProblemCode::ServiceUnavailable))? + .map_err(|_| HttpError::problem(ProblemCode::ServiceUnavailable))? } }; audit.respond(record).await.map_err(|error| { tracing::error!(error = %error, "the Messaging audit destination refused a submission response"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; let answer = match result { Ok(answer) => answer, @@ -519,7 +523,7 @@ async fn submit_message( }; let status = StatusCode::from_u16(answer.status).map_err(|_| { tracing::error!("a stored Messaging receipt carries an invalid status"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; Ok((status, Json(answer.receipt)).into_response()) } @@ -618,7 +622,7 @@ impl SubmissionRecord { .principal_pseudonym(&caller.identity) .map_err(|error| { tracing::error!(error = %error, "a Messaging principal pseudonym failed"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; Ok(Self { event, @@ -662,7 +666,7 @@ async fn get_message( let message = service .visible_message(&caller, &message_id) .await - .map_err(HttpError)?; + .map_err(HttpError::problem)?; Ok(Json(message.view)) } @@ -674,25 +678,25 @@ async fn message_receipt( // Observation neither renders nor submits. Keep the original receipt // available even when the caller has spent its submission budget. if !is_json(request.headers()) { - return Err(HttpError(ProblemCode::RequestUnsupportedMediaType)); + return Err(HttpError::problem(ProblemCode::RequestUnsupportedMediaType)); } let key = request .headers() .get(IDEMPOTENCY_KEY_HEADER) .filter(|key| valid_idempotency_key(key.as_bytes())) .and_then(|key| key.to_str().ok()) - .ok_or(HttpError(ProblemCode::RequestInvalid))? + .ok_or(HttpError::problem(ProblemCode::RequestInvalid))? .to_owned(); let body = read_request_body(request).await?; let service = state .messages .as_ref() - .ok_or(HttpError(ProblemCode::ServiceUnavailable))?; + .ok_or(HttpError::problem(ProblemCode::ServiceUnavailable))?; Ok(Json( service .message_receipt(&caller, &key, &body) .await - .map_err(HttpError)?, + .map_err(HttpError::problem)?, ) .into_response()) } @@ -708,7 +712,7 @@ async fn cancel_message( let view = service .cancel(&caller, &message_id) .await - .map_err(HttpError)?; + .map_err(HttpError::problem)?; Ok(Json(view)) } @@ -719,7 +723,7 @@ async fn cancel_message( fn message_path(extracted: Result, PathRejection>) -> Result { extracted .map(|Path(message_id)| message_id) - .map_err(|_| HttpError(ProblemCode::MessageNotVisible)) + .map_err(|_| HttpError::problem(ProblemCode::MessageNotVisible)) } /// The message service for a route naming `message_id`. An identifier no @@ -729,9 +733,9 @@ fn visible_service<'a>( message_id: &str, ) -> Result<&'a MessageService, HttpError> { if uuid::Uuid::parse_str(message_id).is_err() { - return Err(HttpError(ProblemCode::MessageNotVisible)); + return Err(HttpError::problem(ProblemCode::MessageNotVisible)); } - message_service(state).map_err(HttpError) + message_service(state).map_err(HttpError::problem) } fn message_service(state: &HttpState) -> Result<&MessageService, ProblemCode> { @@ -781,7 +785,7 @@ async fn preview_template( .await .map_err(|error| { tracing::error!(error = %error, "the Messaging audit destination refused a preview request"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; let headers = request.headers().clone(); let outcome = match read_request_body(request).await { @@ -793,25 +797,25 @@ async fn preview_template( &headers, &body, ), - Err(HttpError(problem)) => PreviewOutcome { + Err(error) => PreviewOutcome { locale: None, - result: Err(problem), + result: Err(error.code()), }, }; let record = PreviewRecord::new(&state, &caller, &template_id, &version, &outcome)?; audit .respond(serde_json::to_value(record).map_err(|_| { - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?) .await .map_err(|error| { tracing::error!(error = %error, "the Messaging audit destination refused a preview response"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; - let preview = outcome.result.map_err(HttpError)?; + let preview = outcome.result.map_err(HttpError::problem)?; let body = preview_json(&preview).map_err(|error| { tracing::error!(error = %error, "a Messaging preview could not be serialized"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; Ok((StatusCode::OK, [(CONTENT_TYPE, "application/json")], body).into_response()) } @@ -827,7 +831,7 @@ pub(crate) async fn read_request_body(request: Request) -> Result ProblemCode::RequestBodyTooLarge, _ => ProblemCode::RequestInvalid, }; - HttpError(problem) + HttpError::problem(problem) }) } @@ -917,7 +921,7 @@ impl PreviewRecord { .principal_pseudonym(&caller.identity) .map_err(|error| { tracing::error!(error = %error, "a Messaging principal pseudonym failed"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; let template = state @@ -950,11 +954,8 @@ impl PreviewRecord { async fn authenticate(state: &HttpState, headers: &HeaderMap) -> Result { let result = match bearer_token(headers) { - Some(token) => state.authenticator.authenticate(token).await, - None => { - state.authenticator.record_header_refusal(); - Err(AuthenticationError::Refused) - } + Ok(token) => state.authenticator.authenticate(token).await, + Err(check) => Err(AuthenticationError::Refused(check)), }; result.map_err(|error| { state.metrics.record_authentication_refusal(error); @@ -962,25 +963,160 @@ async fn authenticate(state: &HttpState, headers: &HeaderMap) -> Result Option<&str> { - let authorization = headers.get(AUTHORIZATION)?.to_str().ok()?; - parse_bearer_token(authorization).ok() +/// The bearer credential an `Authorization` header carries, or the check that +/// refuses it: no header, or not the Bearer scheme, is a missing credential. An +/// unreadable or misshapen header is a malformed one. +fn bearer_token(headers: &HeaderMap) -> Result<&str, FailedCheck> { + let authorization = headers + .get(AUTHORIZATION) + .ok_or(FailedCheck::CredentialMissing)? + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + parse_bearer_token(authorization).map_err(|error| match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) } fn authentication_problem(error: AuthenticationError) -> HttpError { match error { - AuthenticationError::Refused | AuthenticationError::Claims => { - HttpError(ProblemCode::AuthenticationRefused) + AuthenticationError::Refused(check) | AuthenticationError::Claims(check) => { + HttpError::refused(ProblemCode::AuthenticationRefused, check) + } + AuthenticationError::Profile(check) => { + HttpError::refused(ProblemCode::ProfileNotAuthorized, check) } - AuthenticationError::Profile => HttpError(ProblemCode::ProfileNotAuthorized), // The verifier reached no verdict, so the credential is not what is // wrong. `service.unavailable` carries `Retry-After` instead of a - // challenge that would send the caller rotating a good token. - AuthenticationError::Unavailable => HttpError(ProblemCode::ServiceUnavailable), + // challenge that would send the caller rotating a good token. The + // answer counts under the key source it could not use. + AuthenticationError::Unavailable => HttpError::refused( + ProblemCode::ServiceUnavailable, + FailedCheck::KeySourceUnavailable, + ), + } +} + +/// A problem answer, and the check that failed when the problem refuses the +/// caller. The check travels with the answer to the one layer that records +/// it; it is never written to the response. +pub struct HttpError { + problem: ProblemCode, + check: Option, +} + +impl HttpError { + /// An answer whose check the producer names: a refusal, or an answer that + /// counts under a check although it is not one. + pub(crate) fn refused(problem: ProblemCode, check: FailedCheck) -> Self { + Self { + problem, + check: Some(check), + } + } + + /// An answer whose check follows from its problem code alone: the + /// problems the service answers once a caller is resolved. + /// [`attribution`] sorts every problem code, so a code added to the + /// vocabulary does not compile until it says which side it is on. + pub(crate) fn problem(problem: ProblemCode) -> Self { + let check = match attribution(problem) { + Attribution::Plain => None, + Attribution::Service(check) => Some(check), + Attribution::Named => { + tracing::error!("a refusal that names its failed check was answered without one"); + None + } + }; + Self { problem, check } + } + + /// The problem this answer carries. + pub(crate) fn code(&self) -> ProblemCode { + self.problem + } +} + +/// How a problem code relates to the failed-check record. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Attribution { + /// The problem does not refuse the caller. + Plain, + /// The problem refuses the caller, and every producer past + /// authentication means this one check. + Service(FailedCheck), + /// The problem refuses the caller, and its producer (authentication or + /// the callback verifier) names the check itself. + Named, +} + +/// Sort every problem code. No wildcard arm: a new code must pick a side. +#[deny(clippy::wildcard_enum_match_arm)] +const fn attribution(problem: ProblemCode) -> Attribution { + match problem { + ProblemCode::AuthenticationRefused | ProblemCode::CallbackUnverified => Attribution::Named, + // Past authentication, the sender role, the sender profile, the + // template and direct content are what the profile does not allow. + ProblemCode::OperationNotAuthorized | ProblemCode::ProfileNotAuthorized => { + Attribution::Service(FailedCheck::Operation) + } + ProblemCode::MessageNotVisible => Attribution::Service(FailedCheck::Visibility), + ProblemCode::RateLimitExceeded => Attribution::Service(FailedCheck::RateLimit), + ProblemCode::CallbackUnreadable + | ProblemCode::ContentInvalid + | ProblemCode::ContentTooLarge + | ProblemCode::ContentTooManySegments + | ProblemCode::IdempotencyExpired + | ProblemCode::IdempotencyKeyReused + | ProblemCode::MessageDispatchStarted + | ProblemCode::MessageTerminal + | ProblemCode::QuotaExceeded + | ProblemCode::ReceiptUnresolved + | ProblemCode::RequestBodyTooLarge + | ProblemCode::RequestInvalid + | ProblemCode::RequestMethodNotAllowed + | ProblemCode::RequestNotFound + | ProblemCode::RequestUnprocessable + | ProblemCode::RequestUnsupportedMediaType + | ProblemCode::ServiceUnavailable + | ProblemCode::TemplateDataInvalid + | ProblemCode::TemplateLocaleUnavailable + | ProblemCode::TemplateNotFound + | ProblemCode::TemplateRenderRefused => Attribution::Plain, } } -pub struct HttpError(pub ProblemCode); +/// The fixed advice a refusal's log line carries for the checks an operator +/// fixes in the access profiles or the issuer's scope claim. +const fn remedy(check: FailedCheck) -> Option<&'static str> { + match check { + FailedCheck::Scope => { + Some("check authentication.oidc.scopeClaim and accessProfiles requiredScopes") + } + FailedCheck::AccessProfile | FailedCheck::ActorKind => { + Some("check accessProfiles actorKind and requesterClients") + } + _ => None, + } +} + +/// Count a refused request and write its admitted log line. The note rides in +/// the answer's extensions, which no serializer reads. +async fn record_refusals( + State(metrics): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::().copied() { + record_refusal!( + metrics.refusal_recorder(), + note, + trace_id = current_trace().trace_id + ); + } + response +} /// Render a refused submission: its problem, with `Retry-After` in whole /// seconds, never below one, when a limit says how long to wait. @@ -1010,7 +1146,7 @@ fn retry_after_seconds(wait: std::time::Duration) -> u64 { impl IntoResponse for HttpError { fn into_response(self) -> Response { - problem_response(self.0) + problem_answer(self.problem, self.check) } } @@ -1020,9 +1156,16 @@ fn current_trace() -> TraceContext { .unwrap_or_else(|_| TraceContext::server_created()) } -/// Render one problem: the pinned code, title, status, and detail from the -/// closed vocabulary, under the answering request's trace. +/// Render one problem whose failed check, if it refuses the caller, follows +/// from its code. fn problem_response(problem: ProblemCode) -> Response { + HttpError::problem(problem).into_response() +} + +/// Render one problem: the pinned code, title, status, and detail from the +/// closed vocabulary, under the answering request's trace. The failed check +/// rides in the response extensions for [`record_refusals`]. +fn problem_answer(problem: ProblemCode, check: Option) -> Response { let trace = current_trace(); let status = problem.http_status(); let body = ProblemBody { @@ -1056,6 +1199,12 @@ fn problem_response(problem: ProblemCode) -> Response { .expect("the retry interval is a valid header value"), ); } + if let Some(check) = check { + let note = RefusalNote::new(check); + response + .extensions_mut() + .insert(remedy(check).map_or(note, |remedy| note.with_remedy(remedy))); + } response } @@ -2532,6 +2681,748 @@ mod tests { .await; } + /// One refusal answer reduced to what a caller can observe: the status, + /// the headers that carry a decision, and the body without its per-request + /// `traceId`. + async fn answer_snapshot(name: &str, response: Response) -> serde_json::Value { + let status = response.status().as_u16(); + let header = |response: &Response, name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().unwrap().to_owned()) + }; + let headers = json!({ + "content-type": header(&response, "content-type"), + "www-authenticate": header(&response, "www-authenticate"), + "retry-after": header(&response, "retry-after"), + "cache-control": header(&response, "cache-control"), + }); + let bytes = to_bytes(response.into_body(), 64 * 1024).await.unwrap(); + let mut body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert!(body["traceId"].is_string(), "{name}: {body}"); + body.as_object_mut().unwrap().remove("traceId"); + json!({"name": name, "status": status, "headers": headers, "body": body}) + } + + /// Every authentication, authorization, visibility and rate refusal the + /// HTTP surface answers without a database. + async fn refusal_snapshots() -> Vec { + let mut snapshots = Vec::new(); + let (app, _) = app(); + let message = "/v1/messages/0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; + snapshots.push( + answer_snapshot( + "no credential", + call(app.clone(), "GET", message, None).await, + ) + .await, + ); + let basic = Request::builder() + .uri(message) + .header(AUTHORIZATION, "Basic dXNlcjpwYXNz") + .body(Body::empty()) + .unwrap(); + snapshots.push( + answer_snapshot( + "not the bearer scheme", + app.clone().oneshot(basic).await.unwrap(), + ) + .await, + ); + snapshots.push( + answer_snapshot( + "not a compact token", + call(app.clone(), "GET", message, Some("not-a-jwt")).await, + ) + .await, + ); + let forged = token_signed_with(sender_claims(), b"another-secret-another-secret-another!"); + snapshots.push( + answer_snapshot( + "forged signature", + call(app.clone(), "GET", message, Some(&forged)).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["aud"] = json!("urn:elsewhere"); + snapshots.push( + answer_snapshot( + "other audience", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["azp"] = json!("unrelated-app"); + snapshots.push( + answer_snapshot( + "client the verifier does not admit", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["azp"] = json!(UNPROFILED_CLIENT); + snapshots.push( + answer_snapshot( + "client with no access profile", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["registry_scopes"] = json!("messaging:read"); + snapshots.push( + answer_snapshot( + "scope the profile requires is missing", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["registry_actor_kind"] = json!("human"); + snapshots.push( + answer_snapshot( + "actor kind the profile does not admit", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["registry_actor_kind"] = json!("robot"); + snapshots.push( + answer_snapshot( + "malformed actor kind", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims.as_object_mut().unwrap().remove("sub"); + snapshots.push( + answer_snapshot( + "no principal", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims[registry_platform_oidc::ASSERTION_ISSUER_CLAIM] = + json!("https://assertions.example.test"); + snapshots.push( + answer_snapshot( + "exchanged token with no declared authority", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "a message id no message can carry", + call( + app.clone(), + "GET", + "/v1/messages/not-an-id", + Some(&token(sender_claims())), + ) + .await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "operator submits", + post_json( + app.clone(), + "/v1/messages", + Some(&token(operator_claims())), + &json!({}), + ) + .await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "operator previews", + post_json( + app.clone(), + PREVIEW, + Some(&token(operator_claims())), + &sample_request(), + ) + .await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "sender previews a template its profile does not list", + post_json( + app.clone(), + "/v1/templates/unlisted-template/versions/1/preview", + Some(&token(sender_claims())), + &sample_request(), + ) + .await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "callback for a provider that receives none", + post( + app, + "/v1/provider-callbacks/mail-relay", + None, + Some("application/json"), + b"{}".to_vec(), + ) + .await, + ) + .await, + ); + let mut state = callback_state(path_token_verifier()); + state.callback_limits = Arc::new(CallbackLimits::new(60, 2).unwrap()); + let app = router(state); + let mut limited = None; + for _ in 0..3 { + limited = Some( + post( + app.clone(), + "/v1/provider-callbacks/sms-gateway/callback-token-000000", + None, + Some("application/json"), + b"{}".to_vec(), + ) + .await, + ); + } + snapshots.push(answer_snapshot("callback past the rate", limited.unwrap()).await); + let issuer_keys = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/jwks.json")) + .respond_with(ResponseTemplate::new(503)) + .mount(&issuer_keys) + .await; + let outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( + format!("{}/jwks.json", issuer_keys.uri()), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::dev(), + ))); + let app = router(state_with(outage, true)); + snapshots.push( + answer_snapshot( + "key endpoint outage", + call(app, "GET", message, Some(&token(sender_claims()))).await, + ) + .await, + ); + snapshots + } + + /// The refusal answers are frozen in `tests/golden/refusals.json`. Set + /// `REGISTRY_UPDATE_GOLDEN=1` to rewrite the file from the current code. + #[tokio::test] + async fn refusal_answers_match_the_golden_file() { + let golden = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusals.json"); + let actual = serde_json::Value::Array(refusal_snapshots().await); + if std::env::var_os("REGISTRY_UPDATE_GOLDEN").is_some() { + std::fs::create_dir_all(golden.parent().unwrap()).unwrap(); + let mut text = serde_json::to_string_pretty(&actual).unwrap(); + text.push('\n'); + std::fs::write(&golden, text).unwrap(); + } + let expected: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&golden).expect("the golden file")) + .expect("the golden file is JSON"); + assert_eq!(actual, expected); + } + + fn request( + method: &str, + uri: &str, + authorization: Option, + body: Option<&serde_json::Value>, + ) -> Request { + let mut request = Request::builder().method(method).uri(uri); + if let Some(authorization) = authorization { + request = request.header(AUTHORIZATION, authorization); + } + match body { + Some(body) => request + .header(CONTENT_TYPE, "application/json") + .body(Body::from(serde_json::to_vec(body).unwrap())) + .unwrap(), + None => request.body(Body::empty()).unwrap(), + } + } + + fn bearer(token: &str) -> Option { + Some(format!("Bearer {token}")) + } + + /// The request counts under `check` once: the counter moved by one, and + /// the log carries one line naming it. + fn assert_counted_under(metrics: &Metrics, logs: &str, check: FailedCheck, context: &str) { + let text = metrics.render(None); + assert!( + text.contains(&format!( + "messaging_request_refusals_total{{check=\"{}\"}} 1\n", + check.as_str() + )), + "{context}: {text}" + ); + let counted: u64 = text + .lines() + .filter(|line| line.starts_with("messaging_request_refusals_total{")) + .map(|line| line.rsplit(' ').next().unwrap().parse::().unwrap()) + .sum(); + assert_eq!(counted, 1, "{context}: {text}"); + assert!( + logs.contains(&format!("failed_check=\"{}\"", check.as_str())), + "{context}: {logs}" + ); + assert_eq!( + logs.matches("request refused").count(), + 1, + "{context}: {logs}" + ); + } + + /// One request per check the service decides, each answered by the golden + /// problem and counted and logged under the check that failed. + #[tokio::test] + async fn each_refusal_is_counted_and_logged_under_the_check_that_failed() { + use crate::smtp::tests::Captured; + let message = "/v1/messages/0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; + let claims_with = |key: &str, value: serde_json::Value| { + let mut claims = sender_claims(); + claims[key] = value; + token(claims) + }; + let forged = token_signed_with(sender_claims(), b"another-secret-another-secret-another!"); + let mut without_principal = sender_claims(); + without_principal.as_object_mut().unwrap().remove("sub"); + let basic = Some("Basic dXNlcjpwYXNz".to_owned()); + let cases: Vec<(&str, FailedCheck, Request)> = vec![ + ( + "no credential", + FailedCheck::CredentialMissing, + request("GET", message, None, None), + ), + ( + "not the bearer scheme", + FailedCheck::CredentialMissing, + request("GET", message, basic, None), + ), + ( + "not a compact token", + FailedCheck::CredentialMalformed, + request("GET", message, bearer("not-a-jwt"), None), + ), + ( + "forged signature", + FailedCheck::TokenSignature, + request("GET", message, bearer(&forged), None), + ), + ( + "other audience", + FailedCheck::TokenAudience, + request( + "GET", + message, + bearer(&claims_with("aud", json!("urn:elsewhere"))), + None, + ), + ), + ( + "other issuer", + FailedCheck::TokenIssuer, + request( + "GET", + message, + bearer(&claims_with("iss", json!("https://elsewhere.test"))), + None, + ), + ), + ( + "client the verifier does not admit", + FailedCheck::TokenClient, + request( + "GET", + message, + bearer(&claims_with("azp", json!("unrelated-app"))), + None, + ), + ), + ( + "client with no access profile", + FailedCheck::AccessProfile, + request( + "GET", + message, + bearer(&claims_with("azp", json!(UNPROFILED_CLIENT))), + None, + ), + ), + ( + "missing scope", + FailedCheck::Scope, + request( + "GET", + message, + bearer(&claims_with("registry_scopes", json!("messaging:read"))), + None, + ), + ), + ( + "actor kind the profile does not admit", + FailedCheck::ActorKind, + request( + "GET", + message, + bearer(&claims_with("registry_actor_kind", json!("human"))), + None, + ), + ), + ( + "malformed actor kind", + FailedCheck::ActorKind, + request( + "GET", + message, + bearer(&claims_with("registry_actor_kind", json!("robot"))), + None, + ), + ), + ( + "no principal", + FailedCheck::TokenClaims, + request("GET", message, bearer(&token(without_principal)), None), + ), + ( + "exchanged token with no declared authority", + FailedCheck::TokenAssertionIssuer, + request( + "GET", + message, + bearer(&claims_with( + registry_platform_oidc::ASSERTION_ISSUER_CLAIM, + json!("https://assertions.example.test"), + )), + None, + ), + ), + ( + "a message id no message can carry", + FailedCheck::Visibility, + request( + "GET", + "/v1/messages/not-an-id", + bearer(&token(sender_claims())), + None, + ), + ), + ( + "operator submits", + FailedCheck::Operation, + request( + "POST", + "/v1/messages", + bearer(&token(operator_claims())), + Some(&json!({})), + ), + ), + ( + "operator previews", + FailedCheck::Operation, + request( + "POST", + PREVIEW, + bearer(&token(operator_claims())), + Some(&sample_request()), + ), + ), + ( + "sender previews a template its profile does not list", + FailedCheck::Operation, + request( + "POST", + "/v1/templates/unlisted-template/versions/1/preview", + bearer(&token(sender_claims())), + Some(&sample_request()), + ), + ), + ]; + for (name, check, request) in cases { + let (app, metrics) = app(); + let captured = Captured::install(); + let response = app.oneshot(request).await.unwrap(); + let logs = captured.finish(); + assert!(response.status().is_client_error(), "{name}"); + assert_counted_under(&metrics, &logs, check, name); + } + } + + #[tokio::test] + async fn a_key_endpoint_outage_counts_under_the_key_source() { + use crate::smtp::tests::Captured; + let issuer_keys = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/jwks.json")) + .respond_with(ResponseTemplate::new(503)) + .mount(&issuer_keys) + .await; + let outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( + format!("{}/jwks.json", issuer_keys.uri()), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::dev(), + ))); + let state = state_with(outage, true); + let metrics = Arc::clone(&state.metrics); + let captured = Captured::install(); + let response = call( + router(state), + "GET", + "/v1/messages/0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d", + Some(&token(sender_claims())), + ) + .await; + let logs = captured.finish(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_counted_under(&metrics, &logs, FailedCheck::KeySourceUnavailable, "outage"); + } + + #[tokio::test] + async fn each_callback_refusal_is_counted_and_logged_under_the_check_that_failed() { + use crate::smtp::tests::Captured; + let signed_wrong = Request::builder() + .method("POST") + .uri("/v1/provider-callbacks/sms-gateway") + .header(CONTENT_TYPE, "application/json") + .header("x-gateway-signature", "00".repeat(32)) + .body(Body::from(br#"{"id":"gw-1"}"#.to_vec())) + .unwrap(); + let unsigned = Request::builder() + .method("POST") + .uri("/v1/provider-callbacks/sms-gateway") + .header(CONTENT_TYPE, "application/json") + .body(Body::from(br#"{"id":"gw-1"}"#.to_vec())) + .unwrap(); + let callback = |uri: &str| request("POST", uri, None, Some(&json!({}))); + let cases: Vec<(&str, serde_json::Value, FailedCheck, Request)> = vec![ + ( + "no provider that receives callbacks", + path_token_verifier(), + FailedCheck::DeliveryBinding, + callback("/v1/provider-callbacks/no-such-provider"), + ), + ( + "a token on a route the verifier does not use", + body_verifier(), + FailedCheck::DeliveryBinding, + callback("/v1/provider-callbacks/sms-gateway/anything"), + ), + ( + "no token on the route that needs one", + path_token_verifier(), + FailedCheck::DeliveryBinding, + callback("/v1/provider-callbacks/sms-gateway"), + ), + ( + "a wrong path token", + path_token_verifier(), + FailedCheck::SharedSecret, + callback("/v1/provider-callbacks/sms-gateway/callback-token-000000"), + ), + ( + "a wrong signature", + body_verifier(), + FailedCheck::DeliverySignature, + signed_wrong, + ), + ( + "a missing signature", + body_verifier(), + FailedCheck::DeliverySignature, + unsigned, + ), + ]; + for (name, verifier, check, request) in cases { + let (app, metrics) = callback_app(verifier); + let captured = Captured::install(); + let response = app.oneshot(request).await.unwrap(); + let logs = captured.finish(); + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{name}"); + assert_counted_under(&metrics, &logs, check, name); + for needle in ["callback-token", "sms-gateway", "no-such-provider", "gw-1"] { + assert!( + !logs.contains(needle), + "{name}: the log carries {needle:?}: {logs}" + ); + } + } + } + + #[tokio::test] + async fn a_callback_past_the_rate_and_a_caller_past_the_rate_count_as_rate_limits() { + use crate::smtp::tests::Captured; + let mut state = callback_state(path_token_verifier()); + state.callback_limits = Arc::new(CallbackLimits::new(60, 1).unwrap()); + let metrics = Arc::clone(&state.metrics); + let app = router(state); + let uri = "/v1/provider-callbacks/sms-gateway/callback-token-000000"; + let first = post( + app.clone(), + uri, + None, + Some("application/json"), + b"{}".to_vec(), + ) + .await; + assert_eq!(first.status(), StatusCode::FORBIDDEN); + let captured = Captured::install(); + let second = post(app, uri, None, Some("application/json"), b"{}".to_vec()).await; + let logs = captured.finish(); + assert_eq!(second.status(), StatusCode::TOO_MANY_REQUESTS); + let text = metrics.render(None); + assert!( + text.contains("messaging_request_refusals_total{check=\"rate-limit\"} 1\n"), + "{text}" + ); + assert!(logs.contains("failed_check=\"rate-limit\""), "{logs}"); + + let package = starter_package(); + let profiles = package + .access_profiles() + .iter() + .cloned() + .map(|profile| registry_messaging_core::AccessProfile { + requests_per_minute: 60, + burst: 1, + ..profile + }) + .collect(); + let mut state = state_with(authenticator(), true); + state.limits = Arc::new( + CallerLimits::new(®istry_messaging_core::AccessProfiles::new(profiles).unwrap()) + .unwrap(), + ); + let metrics = Arc::clone(&state.metrics); + let app = router(state); + let sender = token(sender_claims()); + let submit = |app: Router| { + let sender = sender.clone(); + async move { post_json(app, "/v1/messages", Some(&sender), &json!({})).await } + }; + assert_ne!( + submit(app.clone()).await.status(), + StatusCode::TOO_MANY_REQUESTS + ); + let limited = submit(app).await; + assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS); + let text = metrics.render(None); + assert!( + text.contains("messaging_request_refusals_total{check=\"rate-limit\"} 1\n"), + "{text}" + ); + } + + #[tokio::test] + async fn a_refusal_log_carries_the_check_and_a_fixed_remedy_and_no_value() { + use crate::smtp::tests::Captured; + let (app, _) = app(); + let credential = token(sender_claims_with_scope("messaging:read")); + let captured = Captured::install(); + call(app.clone(), "GET", "/v1/messages/m-1", Some(&credential)).await; + let logs = captured.finish(); + assert!(logs.contains("failed_check=\"scope\""), "{logs}"); + assert!(logs.contains("scopeClaim"), "{logs}"); + for needle in [ + credential.as_str(), + "messaging:read", + "case-system", + "registry_actor_kind", + "registry_scopes", + "messaging:send", + "case-notices", + "m-1", + ] { + assert!(!logs.contains(needle), "logs carry {needle:?}:\n{logs}"); + } + let human = { + let mut claims = sender_claims(); + claims["registry_actor_kind"] = json!("human"); + token(claims) + }; + let captured = Captured::install(); + call(app, "GET", "/v1/messages/m-1", Some(&human)).await; + let logs = captured.finish(); + assert!(logs.contains("failed_check=\"actor-kind\""), "{logs}"); + assert!(!logs.contains("scopeClaim"), "{logs}"); + } + + fn sender_claims_with_scope(scope: &str) -> serde_json::Value { + let mut claims = sender_claims(); + claims["registry_scopes"] = json!(scope); + claims + } + + #[tokio::test] + async fn malformed_credentials_log_a_bounded_value_free_line() { + use crate::smtp::tests::Captured; + use registry_platform_testing::malformed_access_token_fixtures; + let tokens = malformed_access_token_fixtures(); + let (app, metrics) = app(); + let captured = Captured::install(); + for _ in 0..3 { + for token in &tokens { + let response = call(app.clone(), "GET", "/v1/messages/m-1", Some(token)).await; + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + } + } + let logs = captured.finish(); + let sent = u64::try_from(3 * tokens.len()).unwrap(); + let text = metrics.render(None); + assert!( + text.contains(&format!( + "messaging_request_refusals_total{{check=\"credential-malformed\"}} {sent}\n" + )), + "{text}" + ); + assert_eq!(logs.matches("request refused").count(), 5, "{logs}"); + for token in &tokens { + assert!(token.is_empty() || !logs.contains(token.as_str()), "{logs}"); + } + } + + #[test] + fn every_problem_that_answers_401_or_403_is_attributed() { + for problem in ProblemCode::ALL { + let refuses = matches!(problem.http_status(), 401 | 403); + assert!( + !refuses || attribution(*problem) != Attribution::Plain, + "{problem:?} refuses a caller and names no check" + ); + } + assert_eq!( + attribution(ProblemCode::MessageNotVisible), + Attribution::Service(FailedCheck::Visibility) + ); + assert_eq!( + attribution(ProblemCode::RateLimitExceeded), + Attribution::Service(FailedCheck::RateLimit) + ); + assert_eq!( + attribution(ProblemCode::OperationNotAuthorized), + Attribution::Service(FailedCheck::Operation) + ); + } + #[test] fn the_operation_table_answers_only_catalogued_problems_and_unique_ids() { let mut ids = std::collections::BTreeSet::new(); diff --git a/crates/registry-messaging/src/http_provider/settings.rs b/crates/registry-messaging/src/http_provider/settings.rs index 44f9175d0e..6a5ddeb319 100644 --- a/crates/registry-messaging/src/http_provider/settings.rs +++ b/crates/registry-messaging/src/http_provider/settings.rs @@ -17,7 +17,6 @@ //! platform grammar is a later extraction. use std::fmt; -use std::net::IpAddr; use std::time::Duration; use ipnet::IpNet; @@ -1291,12 +1290,10 @@ fn split_base_url( let development = match parsed.scheme() { "https" => false, "http" => { - let loopback = match parsed.host() { - Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), - Some(url::Host::Ipv4(address)) => IpAddr::V4(address).is_loopback(), - Some(url::Host::Ipv6(address)) => IpAddr::V6(address).is_loopback(), - None => false, - }; + let loopback = parsed + .host_str() + .and_then(registry_platform_httputil::loopback::loopback_host) + .is_some(); if !loopback { return Err(invalid( field, @@ -1412,3 +1409,38 @@ fn token_form_body( } Ok(Zeroizing::new(serializer.finish().into_bytes())) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_http_is_allowed_only_to_a_loopback_host() { + for base_url in [ + "http://127.0.0.1:9/v1/", + "http://127.4.5.6:9/v1/", + "http://[::1]:9/v1/", + "http://[::ffff:127.0.0.1]:9/v1/", + "http://localhost:9/v1/", + "http://LOCALHOST:9/v1/", + ] { + let (_, _, development) = split_base_url("baseUrl", base_url, true) + .unwrap_or_else(|error| panic!("{base_url}: {error}")); + assert!(development, "{base_url}"); + } + for base_url in [ + "http://localhost.:9/v1/", + "http://gateway.localhost:9/v1/", + "http://10.0.0.1:9/v1/", + "http://0.0.0.0:9/v1/", + "http://[::]:9/v1/", + "http://[::ffff:10.0.0.1]:9/v1/", + "http://169.254.169.254/v1/", + ] { + let error = split_base_url("baseUrl", base_url, true) + .expect_err(base_url) + .to_string(); + assert!(error.contains("loopback"), "{base_url}: {error}"); + } + } +} diff --git a/crates/registry-messaging/src/metrics.rs b/crates/registry-messaging/src/metrics.rs index 48c472e409..8a8404c387 100644 --- a/crates/registry-messaging/src/metrics.rs +++ b/crates/registry-messaging/src/metrics.rs @@ -17,7 +17,10 @@ //! //! Authentication refusals are counted here rather than written to the audit //! journal: a refused credential names no principal to hold accountable, and -//! journaling it would let an unauthenticated caller grow the journal. +//! journaling it would let an unauthenticated caller grow the journal. Every +//! request the service refuses is also counted by the check that failed, in +//! `messaging_request_refusals_total`, whose label is the closed +//! [`FailedCheck`] set and nothing a caller sent. //! //! Provider callbacks are counted by [`CallbackOutcome`] alone. The provider //! id in a callback path is caller text until it names an activated @@ -49,6 +52,7 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{Method, Request, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -79,6 +83,9 @@ pub struct Metrics { limits: CounterVec, retention: CounterVec, sample_failures: CounterVec, + /// Refused requests by the check that failed, and the bounded log line + /// that goes with each. + request_refusals: RefusalRecorder, } impl fmt::Debug for Metrics { @@ -133,6 +140,7 @@ impl Default for Metrics { "sample", ["dispatch-queue"], ), + request_refusals: RefusalRecorder::new("messaging").expect(DECLARATION), } } } @@ -298,12 +306,19 @@ impl Metrics { ); } + /// The recorder that counts a refused request by the check that failed + /// and decides which refusals reach the log. + #[must_use] + pub fn refusal_recorder(&self) -> &RefusalRecorder { + &self.request_refusals + } + /// Count one authentication refusal by its outcome. pub fn record_authentication_refusal(&self, error: AuthenticationError) { let reason = match error { - AuthenticationError::Refused => "refused", - AuthenticationError::Claims => "claims", - AuthenticationError::Profile => "profile", + AuthenticationError::Refused(_) => "refused", + AuthenticationError::Claims(_) => "claims", + AuthenticationError::Profile(_) => "profile", AuthenticationError::Unavailable => "unavailable", }; count(&self.refusals, &[reason]); @@ -345,6 +360,10 @@ impl Metrics { ] { counter.write(&mut out).expect(DECLARATION); } + self.request_refusals + .counter() + .write(&mut out) + .expect(DECLARATION); out.header( "messaging_dispatch_jobs", Some("Messages waiting to be sent, being sent, or held unknown, sampled at scrape."), @@ -478,6 +497,7 @@ pub async fn scrape( #[cfg(test)] mod tests { use super::*; + use registry_platform_authcommon::FailedCheck; #[test] fn labels_are_closed() { @@ -516,7 +536,8 @@ mod tests { StatusCode::OK, ); metrics.record_authentication_refusal(AuthenticationError::Unavailable); - metrics.record_authentication_refusal(AuthenticationError::Claims); + metrics + .record_authentication_refusal(AuthenticationError::Claims(FailedCheck::TokenClaims)); metrics.record_callback(CallbackOutcome::Unmatched); metrics.record_callback(CallbackOutcome::Unmatched); metrics.record_attempt(AttemptOutcome::MaybeSent); @@ -561,9 +582,11 @@ messaging_retention_runs_total{outcome=\"failed\"} 1 # HELP messaging_metrics_sample_failures_total Scrape-time database reads that failed, by which read. A failed read leaves its gauges without samples. # TYPE messaging_metrics_sample_failures_total counter messaging_metrics_sample_failures_total{sample=\"dispatch-queue\"} 0 -# HELP messaging_dispatch_jobs Messages waiting to be sent, being sent, or held unknown, sampled at scrape. -# TYPE messaging_dispatch_jobs gauge "; + let head = format!( + "{head}{}# HELP messaging_dispatch_jobs Messages waiting to be sent, being sent, or held unknown, sampled at scrape.\n# TYPE messaging_dispatch_jobs gauge\n", + refusal_series() + ); assert_eq!(metrics.render(None), head); assert_eq!( metrics.render(Some(DispatchDepth { @@ -577,6 +600,21 @@ messaging_metrics_sample_failures_total{sample=\"dispatch-queue\"} 0 ); } + /// The `messaging_request_refusals_total` exposition of a recorder that + /// counted nothing: one zero series for each member of the closed set. + fn refusal_series() -> String { + let mut text = String::from( + "# HELP messaging_request_refusals_total Requests refused, by the check that failed.\n# TYPE messaging_request_refusals_total counter\n", + ); + for check in FailedCheck::ALL { + text.push_str(&format!( + "messaging_request_refusals_total{{check=\"{}\"}} 0\n", + check.as_str() + )); + } + text + } + #[test] fn every_callback_outcome_is_exposed_from_zero() { let metrics = Metrics::default(); diff --git a/crates/registry-messaging/src/smtp/mod.rs b/crates/registry-messaging/src/smtp/mod.rs index 7bd295495c..4e7cc015bd 100644 --- a/crates/registry-messaging/src/smtp/mod.rs +++ b/crates/registry-messaging/src/smtp/mod.rs @@ -446,7 +446,9 @@ impl SmtpProvider { } for address in &answers { let allowed = match self.transport { - Transport::DevelopmentLoopback => address.to_canonical().is_loopback(), + Transport::DevelopmentLoopback => { + registry_platform_httputil::loopback::loopback_address(*address) + } Transport::Starttls(_) | Transport::Implicit(_) => { self.policy.classify(*address).is_ok() } diff --git a/crates/registry-messaging/src/smtp/settings.rs b/crates/registry-messaging/src/smtp/settings.rs index 3d45e3d40f..c9ea86aa10 100644 --- a/crates/registry-messaging/src/smtp/settings.rs +++ b/crates/registry-messaging/src/smtp/settings.rs @@ -377,8 +377,10 @@ impl SmtpProviderSettings { return Err(SmtpSettingsError::DevelopmentNotPermitted); } let loopback = match host_literal { - Some(ip) => ip.to_canonical().is_loopback(), - None => self.host.eq_ignore_ascii_case("localhost"), + Some(ip) => registry_platform_httputil::loopback::loopback_address(ip), + None => { + registry_platform_httputil::loopback::loopback_host(&self.host).is_some() + } }; if !loopback { return Err(SmtpSettingsError::DevelopmentRequiresLoopbackHost); @@ -571,6 +573,7 @@ pub(super) mod tests { "0.0.0.0", "::", "localhost.example.org", + "relay.localhost", ] { let settings = SmtpProviderSettings { host: host.to_owned(), @@ -583,6 +586,10 @@ pub(super) mod tests { "{host}" ); } + assert_eq!( + development("localhost.").check(false), + Err(SmtpSettingsError::InvalidHost) + ); for host in [ "127.0.0.1", "127.3.2.1", @@ -590,6 +597,7 @@ pub(super) mod tests { "localhost", "LOCALHOST", "::ffff:127.0.0.1", + "::ffff:127.9.8.7", ] { assert!(development(host).check(false).is_ok(), "{host}"); } diff --git a/crates/registry-messaging/tests/golden/refusals.json b/crates/registry-messaging/tests/golden/refusals.json new file mode 100644 index 0000000000..35a0a31ecf --- /dev/null +++ b/crates/registry-messaging/tests/golden/refusals.json @@ -0,0 +1,325 @@ +[ + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "no credential", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "not the bearer scheme", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "not a compact token", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "forged signature", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "other audience", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "client the verifier does not admit", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "client with no access profile", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "scope the profile requires is missing", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "actor kind the profile does not admit", + "status": 403 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "malformed actor kind", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "no principal", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "exchanged token with no declared authority", + "status": 403 + }, + { + "body": { + "code": "message.not-visible", + "detail": "No message with this identifier is visible to the caller.", + "status": 404, + "title": "Message not visible", + "type": "https://id.registrystack.org/problems/registry-messaging/message/not-visible" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "a message id no message can carry", + "status": 404 + }, + { + "body": { + "code": "operation.not-authorized", + "detail": "Your Messaging access profile does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/operation/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "operator submits", + "status": 403 + }, + { + "body": { + "code": "operation.not-authorized", + "detail": "Your Messaging access profile does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/operation/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "operator previews", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "sender previews a template its profile does not list", + "status": 403 + }, + { + "body": { + "code": "callback.unverified", + "detail": "The callback did not verify for a provider this deployment accepts callbacks from.", + "status": 403, + "title": "Callback not verified", + "type": "https://id.registrystack.org/problems/registry-messaging/callback/unverified" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "callback for a provider that receives none", + "status": 403 + }, + { + "body": { + "code": "rate-limit.exceeded", + "detail": "The request rate accepted from this caller is exceeded. Try again after the time in Retry-After.", + "status": 429, + "title": "Request rate exceeded", + "type": "https://id.registrystack.org/problems/registry-messaging/rate-limit/exceeded" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "1", + "www-authenticate": null + }, + "name": "callback past the rate", + "status": 429 + }, + { + "body": { + "code": "service.unavailable", + "detail": "Messaging is unavailable. Try again after the service recovers.", + "status": 503, + "title": "Messaging service unavailable", + "type": "https://id.registrystack.org/problems/registry-messaging/service/unavailable" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "5", + "www-authenticate": null + }, + "name": "key endpoint outage", + "status": 503 + } +] diff --git a/crates/registry-messaging/tests/token_characterisation.rs b/crates/registry-messaging/tests/token_characterisation.rs index d0de187b95..59b11f0cd7 100644 --- a/crates/registry-messaging/tests/token_characterisation.rs +++ b/crates/registry-messaging/tests/token_characterisation.rs @@ -179,13 +179,13 @@ async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { .map_or("unspecified", ActorKind::as_str) .to_owned(), )), - Err(AuthenticationError::Claims) => refusal("claims"), + Err(AuthenticationError::Claims(_)) => refusal("claims"), Err(AuthenticationError::Unavailable) => refusal("unavailable"), - Err(error @ (AuthenticationError::Refused | AuthenticationError::Profile)) => { + Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { let reference = TokenVerifier::new(config.verifier_profile(&admitted), keys); match reference.verify(token).await { Err(failure) => refusal(failure.authentication_stage().label()), - Ok(verified) if error == AuthenticationError::Profile => { + Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { if verified.scopes.iter().any(|held| held == &scope) { refusal("profile") } else { diff --git a/crates/registry-messagingctl/src/dev/borrowed.rs b/crates/registry-messagingctl/src/dev/borrowed.rs index d07f577c13..186a489d31 100644 --- a/crates/registry-messagingctl/src/dev/borrowed.rs +++ b/crates/registry-messagingctl/src/dev/borrowed.rs @@ -18,8 +18,8 @@ use registry_messaging_core::{AccessProfile, ActorKind, Caller}; use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::{PrivateKeyJwt, PrivateKeyJwtConfig, TokenProvider}; use registry_platform_oidc::{ - access_token_typ_set, parse_static_jwks, JwksFetcher, JwksFetcherConfig, TokenVerifier, - TokenVerifierConfig, + access_token_typ_set, parse_static_jwks, JwksFetcher, JwksFetcherConfig, OidcError, + TokenVerifier, TokenVerifierConfig, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -141,6 +141,17 @@ fn refusal() -> super::DevFailure { refused("the borrowed client could not authenticate with the Messaging profile; check the owner's client, resource, scopes and claims, then restart messagingctl dev".to_owned()) } +/// The refusal of the owner's key document. A document that breaks the shared +/// public-key rule says which rule, in words that carry no key value. +fn static_key_refusal(error: OidcError) -> super::DevFailure { + match error { + OidcError::StaticKeySet(rule) => refused(format!( + "the borrowed owner's secrets/jwks.json is not a usable static key set: {rule}" + )), + _ => refusal(), + } +} + fn runtime() -> DevResult { tokio::runtime::Builder::new_current_thread() .enable_all() @@ -378,7 +389,7 @@ pub(super) async fn verify( let bytes = private::read(&root.join("secrets/jwks.json"), 256 * 1024).map_err(|_| refusal())?; let keys = Arc::new(JwksFetcher::new_static( - parse_static_jwks(&bytes).map_err(|_| refusal())?, + parse_static_jwks(&bytes).map_err(static_key_refusal)?, JwksFetcherConfig::defaults(), )); let verifier = TokenVerifierConfig::access_token_profile( diff --git a/crates/registry-messagingctl/src/dev/borrowed_tests.rs b/crates/registry-messagingctl/src/dev/borrowed_tests.rs index 30118cf28e..3cb90efc2b 100644 --- a/crates/registry-messagingctl/src/dev/borrowed_tests.rs +++ b/crates/registry-messagingctl/src/dev/borrowed_tests.rs @@ -675,3 +675,27 @@ fn a_stop_request_during_the_export_stops_bregctl() { assert!(fixture.exported_files().is_empty()); assert!(!fixture.snapshot().exists()); } + +#[test] +fn a_key_document_that_breaks_the_public_key_rule_names_the_rule() { + let error = parse_static_jwks( + br#"{"keys":[{"kty":"RSA","kid":"a","n":"AQAB","e":"AQAB","d":"canary-private-value"}]}"#, + ) + .expect_err("a private member is refused"); + let failure = static_key_refusal(error); + assert_eq!(failure.code, "dev.refused"); + assert!( + failure.message.contains("private-key member \"d\""), + "{}", + failure.message + ); + assert!(!failure.message.contains("canary-private-value")); +} + +#[test] +fn any_other_key_document_refusal_keeps_the_generic_message() { + assert_eq!( + static_key_refusal(registry_platform_oidc::OidcError::Parse).message, + refusal().message + ); +} diff --git a/crates/registry-render/Cargo.toml b/crates/registry-render/Cargo.toml index c0abdb5972..ba9f3f795a 100644 --- a/crates/registry-render/Cargo.toml +++ b/crates/registry-render/Cargo.toml @@ -10,14 +10,14 @@ publish = false [dependencies] registry-platform-audit = { workspace = true } -registry-platform-authcommon = { workspace = true } +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo = { workspace = true } registry-platform-canonical-json = { workspace = true } registry-platform-config = { workspace = true } registry-platform-oidc = { workspace = true } jsonwebtoken = { workspace = true } registry-platform-crypto = { workspace = true, features = ["cms-signing", "transit"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["refusal-trace-id", "server"] } registry-platform-httputil = { workspace = true } registry-platform-metrics = { workspace = true } registry-platform-yaml = { workspace = true } diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index 7ec23373d1..c723922ab6 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -1,6 +1,7 @@ //! Bearer verification belongs only to the HTTP adapter. use crate::problem::{ProblemKind, RenderProblem}; use crate::runtime::RenderRuntime; +use registry_platform_authcommon::FailedCheck; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, AccessTokenAlgorithm, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, TokenVerifier, @@ -77,12 +78,28 @@ pub(crate) async fn verifier( #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum AuthenticationError { - Refused, - Forbidden { caller_fingerprint: String }, + /// The credential was refused, by the check that refused it. + Refused(FailedCheck), + Forbidden { + caller_fingerprint: String, + check: FailedCheck, + }, Unavailable, } +impl AuthenticationError { + /// The check that refused the caller. A key source that cannot answer is + /// the verifier's own outage. + pub(crate) fn failed_check(&self) -> FailedCheck { + match self { + Self::Refused(check) | Self::Forbidden { check, .. } => *check, + Self::Unavailable => FailedCheck::KeySourceUnavailable, + } + } +} + fn verifier_failure(error: OidcError) -> AuthenticationError { + let check = error.failed_check(); match error { OidcError::Transport(_) | OidcError::BoundedRead(_) @@ -96,7 +113,7 @@ fn verifier_failure(error: OidcError) -> AuthenticationError { | OidcError::ConflictingEndpointConfiguration | OidcError::InsecureHttpRequiresOptIn | OidcError::EndpointRefused { .. } => AuthenticationError::Unavailable, - _ => AuthenticationError::Refused, + _ => AuthenticationError::Refused(check), } } @@ -124,13 +141,16 @@ pub(crate) async fn authenticate( required_scope: &str, ) -> Result { registry_platform_authcommon::validate_compact_access_token(token) - .map_err(|_| AuthenticationError::Refused)?; + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; let verified = verifier.verify(token).await.map_err(verifier_failure)?; // The verifier owns resource membership and the configured client binding. // Unrelated task-grant claims confer no Render authority. let caller_fingerprint = registry_platform_authcommon::fingerprint_api_key(token); if !verified.scopes.iter().any(|scope| scope == required_scope) { - return Err(AuthenticationError::Forbidden { caller_fingerprint }); + return Err(AuthenticationError::Forbidden { + caller_fingerprint, + check: FailedCheck::Scope, + }); } // With an allowlist the verifier has bound the client and records which // claim matched. Without one, the signed claims name it, in the same @@ -143,7 +163,7 @@ pub(crate) async fn authenticate( .clone() .or_else(|| verified.claims.client_id.clone()) .filter(|client| !client.is_empty()), - Err(_) => return Err(AuthenticationError::Refused), + Err(_) => return Err(AuthenticationError::Refused(FailedCheck::TokenClient)), }; // Correlate the exact verified credential, as in legacy API-key mode. // Issuer, subject, and client claims are never written into the audit event. diff --git a/crates/registry-render/src/auth/token_characterisation.rs b/crates/registry-render/src/auth/token_characterisation.rs index f7da0a2610..2aee222487 100644 --- a/crates/registry-render/src/auth/token_characterisation.rs +++ b/crates/registry-render/src/auth/token_characterisation.rs @@ -69,11 +69,18 @@ async fn observe(verifier: &TokenVerifier, token: &str) -> Outcome { match (admission, verdict) { (Ok(_), Ok(_)) => Outcome::Admitted(None), (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), - (Err(_), Err(error)) => stage_of(&error), + (Err(refused), Err(error)) => { + assert_eq!( + refused.failed_check(), + error.failed_check(), + "the recorded check is the verifier's" + ); + stage_of(&error) + } (Err(AuthenticationError::Forbidden { .. }), Ok(_)) => { "refused/scope".parse().expect("result value") } - (Err(AuthenticationError::Refused), Ok(_)) => { + (Err(AuthenticationError::Refused(_)), Ok(_)) => { "refused/claims".parse().expect("result value") } (Err(AuthenticationError::Unavailable), Ok(_)) => { diff --git a/crates/registry-render/src/metrics.rs b/crates/registry-render/src/metrics.rs index e3632fe1fd..2415356a63 100644 --- a/crates/registry-render/src/metrics.rs +++ b/crates/registry-render/src/metrics.rs @@ -14,7 +14,9 @@ //! the metrics are scraped. It reads no database and calls no key provider. use axum::http::StatusCode; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{CounterVec, Exposition, LabelSpace, MetricKind}; +use std::sync::Arc; use time::OffsetDateTime; use crate::seal::Seals; @@ -80,6 +82,7 @@ impl Outcome { pub struct Metrics { documents: CounterVec, + refusals: Arc, } impl std::fmt::Debug for Metrics { @@ -105,11 +108,18 @@ impl Default for Metrics { .expect(DECLARATION), ) .expect(DECLARATION), + refusals: Arc::new(RefusalRecorder::new("render").expect(DECLARATION)), } } } impl Metrics { + /// The recorder that counts each refused request under its check and + /// admits a bounded number of log lines. + pub(crate) fn refusal_recorder(&self) -> &Arc { + &self.refusals + } + /// Count one answered call to a document operation under its status /// class. pub fn record_document(&self, operation: Operation, status: StatusCode) { @@ -128,6 +138,7 @@ impl Metrics { pub fn render(&self, audit_write_failures: u64, seals: &Seals, now: OffsetDateTime) -> String { let mut out = Exposition::new(); self.documents.write(&mut out).expect(DECLARATION); + self.refusals.counter().write(&mut out).expect(DECLARATION); out.header( "render_audit_write_failures_total", Some("Audit entries that could not be written."), diff --git a/crates/registry-render/src/runtime.rs b/crates/registry-render/src/runtime.rs index cbf9d302da..1230b00f7f 100644 --- a/crates/registry-render/src/runtime.rs +++ b/crates/registry-render/src/runtime.rs @@ -3239,6 +3239,8 @@ mod tests { "http://127.0.0.1:3161/tsr", "http://127.0.0.2:3161/tsr", "http://[::1]:3161/tsr", + // An IPv4-mapped form of 127.0.0.0/8 is loopback by the shared rule. + "http://[::ffff:127.0.0.1]/tsr", "https://tsa.example.test/tsr", ] { let seal = SEAL.replace("https://tsa.example.test/tsr", url); @@ -3251,7 +3253,7 @@ mod tests { "http://10.0.0.5/tsr", "http://localhost.example.test/", "http://localhost./tsr", - "http://[::ffff:127.0.0.1]/tsr", + "http://[::ffff:10.0.0.5]/tsr", ] { let seal = SEAL.replace("https://tsa.example.test/tsr", url); let problem = refused(&home, &signing_text(&home, &seal)); diff --git a/crates/registry-render/src/server.rs b/crates/registry-render/src/server.rs index 5d6d848965..6357245be4 100644 --- a/crates/registry-render/src/server.rs +++ b/crates/registry-render/src/server.rs @@ -28,7 +28,8 @@ use serde::{Deserialize, Serialize}; use subtle::ConstantTimeEq; use registry_platform_authcommon::{ - parse_bearer_token, validate_api_key_entropy, MIN_API_KEY_ENTROPY_BYTES, + parse_bearer_token, validate_api_key_entropy, BearerParseError, FailedCheck, RefusalNote, + RefusalRecorder, MIN_API_KEY_ENTROPY_BYTES, }; use registry_platform_canonical_json::parse_json_preserving_integers; use registry_platform_httpsec::{request_body_limit, security_headers, CspBuilder}; @@ -266,12 +267,7 @@ async fn serve_async(runtime_path: &Path) -> Result { } None => None, }; - let app = router(Arc::clone(&service)) - .layer(axum::middleware::from_fn(lifecycle_log)) - .layer(axum::middleware::from_fn_with_state( - Arc::clone(&metrics), - count_documents, - )); + let app = public_app(Arc::clone(&service), &metrics); let grace = runtime.listener.shutdown_grace(); let drain_service = Arc::clone(&service); // The stop signal is observed once and broadcast, so the drain and the @@ -440,6 +436,21 @@ pub(crate) fn router(service: Arc) -> Router { .layer(security_headers(CspBuilder::restrictive())) } +/// The public application: the router under the request log, the refusal +/// recording and the document counter. +fn public_app(service: Arc, metrics: &Arc) -> Router { + router(service) + .layer(axum::middleware::from_fn_with_state( + Arc::clone(metrics.refusal_recorder()), + record_refusals, + )) + .layer(axum::middleware::from_fn(lifecycle_log)) + .layer(axum::middleware::from_fn_with_state( + Arc::clone(metrics), + count_documents, + )) +} + /// The caller guidance a credential without `render:seal` receives on the /// seal route. const SEAL_SCOPE_GUIDANCE: &str = "Obtain a Render resource credential with the render:seal scope."; @@ -478,11 +489,14 @@ async fn require_bearer( Ok(caller) => caller, Err(error) => { use crate::auth::AuthenticationError; + let check = error.failed_check(); let (kind, caller) = match error { - AuthenticationError::Refused => (ProblemKind::Unauthorized, "unknown".to_owned()), - AuthenticationError::Forbidden { caller_fingerprint } => { - (ProblemKind::Forbidden, caller_fingerprint) + AuthenticationError::Refused(_) => { + (ProblemKind::Unauthorized, "unknown".to_owned()) } + AuthenticationError::Forbidden { + caller_fingerprint, .. + } => (ProblemKind::Forbidden, caller_fingerprint), AuthenticationError::Unavailable => { (ProblemKind::AuthenticationUnavailable, "unknown".to_owned()) } @@ -492,7 +506,7 @@ async fn require_bearer( problem = problem.with_public_detail(SEAL_SCOPE_GUIDANCE); } let (path, headers) = (request.uri().path(), request.headers()); - return refuse_access(&service, path, headers, &problem, &caller).await; + return refuse_access(&service, path, headers, &problem, &caller, check).await; } }; // The legacy API key never seals. The runtime already refuses a signing @@ -501,19 +515,29 @@ async fn require_bearer( let problem = RenderProblem::new(ProblemKind::Forbidden, "the legacy API key cannot seal") .with_public_detail(LEGACY_KEY_GUIDANCE); let (path, headers) = (request.uri().path(), request.headers()); - return refuse_access(&service, path, headers, &problem, &caller.fingerprint).await; + return refuse_access( + &service, + path, + headers, + &problem, + &caller.fingerprint, + FailedCheck::Operation, + ) + .await; } request.extensions_mut().insert(caller); next.run(request).await } -/// Audit an access refusal as one response entry, then answer with it. +/// Audit an access refusal as one response entry, then answer with it. The +/// answer carries the check that refused the caller for the recording layer. async fn refuse_access( service: &Service, path: &str, headers: &HeaderMap, problem: &RenderProblem, caller: &str, + check: FailedCheck, ) -> Response { let target = sanitize_route_target(path); let correlation = correlation_id(headers); @@ -529,7 +553,36 @@ async fn refuse_access( if let Err(audit_problem) = service.audit.response(&envelope, event).await { return problem_response(&audit_problem, trace.as_deref()); } - problem_response(problem, trace.as_deref()) + refusal_response(problem, trace.as_deref(), check) +} + +/// A refusal answer with the check that refused the caller in its response +/// extensions, which are never serialized. +fn refusal_response(problem: &RenderProblem, trace: Option<&str>, check: FailedCheck) -> Response { + let mut response = problem_response(problem, trace); + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + +/// Count each refusal answer under its check and write the admitted log line. +/// The trace id is the one the answer carries. +async fn record_refusals( + State(refusals): State>, + request: axum::extract::Request, + next: axum::middleware::Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::() { + match registry_platform_httpsec::response_trace_id(response.headers()) { + Ok(trace) => { + registry_platform_authcommon::record_refusal!(refusals, *note, trace_id = trace); + } + Err(_) => { + registry_platform_authcommon::record_refusal!(refusals, *note); + } + } + } + response } /// The verified caller of an API route. @@ -935,12 +988,24 @@ async fn authorized( ) -> Result { use crate::auth::AuthenticationError; let mut values = headers.get_all(header::AUTHORIZATION).iter(); - let value = values.next().ok_or(AuthenticationError::Refused)?; + let value = values + .next() + .ok_or(AuthenticationError::Refused(FailedCheck::CredentialMissing))?; if values.next().is_some() { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused( + FailedCheck::CredentialMalformed, + )); } - let token = parse_bearer_token(value.to_str().map_err(|_| AuthenticationError::Refused)?) - .map_err(|_| AuthenticationError::Refused)?; + let malformed = || AuthenticationError::Refused(FailedCheck::CredentialMalformed); + let token = + parse_bearer_token(value.to_str().map_err(|_| malformed())?).map_err( + |error| match error { + BearerParseError::InvalidScheme => { + AuthenticationError::Refused(FailedCheck::CredentialMissing) + } + _ => malformed(), + }, + )?; if let Some(verifier) = &service.oidc { let verified = crate::auth::authenticate(verifier, token, scope).await?; return Ok(Caller { @@ -955,7 +1020,7 @@ async fn authorized( fingerprint: service.caller_fingerprint.clone(), client_id: None, }) - .ok_or(AuthenticationError::Refused) + .ok_or(AuthenticationError::Refused(FailedCheck::SharedSecret)) } /// Caller-supplied trace id from a W3C traceparent header, fully @@ -1145,6 +1210,17 @@ impl SealCall { /// Refuse the call before any render starts: one response entry naming /// the seal when it is known, accepted before responding. async fn refuse(&self, service: &Service, problem: RenderProblem) -> Response { + self.refuse_checked(service, problem, None).await + } + + /// Refuse the call as `refuse` does, and record the check that refused + /// the caller when there is one. + async fn refuse_checked( + &self, + service: &Service, + problem: RenderProblem, + check: Option, + ) -> Response { let mut event = RenderAuditEvent::refused( &self.document_type, &problem, @@ -1158,7 +1234,10 @@ impl SealCall { if let Err(audit_problem) = service.audit.response(&self.envelope, event).await { return problem_response(&audit_problem, self.trace.as_deref()); } - problem_response(&problem, self.trace.as_deref()) + match check { + Some(check) => refusal_response(&problem, self.trace.as_deref(), check), + None => problem_response(&problem, self.trace.as_deref()), + } } } @@ -1234,7 +1313,9 @@ async fn seal_route( ProblemKind::SealClientNotAllowed, format!("the verified client is not in signing.seals.{seal_id}.allowedClients"), ); - return call.refuse(&service, problem).await; + return call + .refuse_checked(&service, problem, Some(FailedCheck::RequesterClient)) + .await; } seal.recover_signer().await; // One clock reading decides availability and is the signing time. @@ -2609,4 +2690,410 @@ mod tests { assert_eq!(phases, &["request", "response"]); } } + + /// One refused answer, as the golden freezes it: status, the headers a + /// caller or proxy acts on, and the body without its per-request trace id. + async fn frozen_answer(response: Response) -> serde_json::Value { + let status = response.status().as_u16(); + let mut headers = serde_json::Map::new(); + for name in [ + "content-type", + "www-authenticate", + "cache-control", + "retry-after", + ] { + if let Some(value) = response.headers().get(name) { + headers.insert( + name.to_owned(), + value.to_str().expect("ASCII header").into(), + ); + } + } + let bytes = axum::body::to_bytes(response.into_body(), 16384) + .await + .expect("body"); + let mut body: serde_json::Value = serde_json::from_slice(&bytes).expect("problem body"); + assert!(body["traceId"].is_string(), "{body}"); + body.as_object_mut().expect("object").remove("traceId"); + serde_json::json!({"status": status, "headers": headers, "body": body}) + } + + fn bearer_request( + method: Method, + uri: &str, + credential: Option, + ) -> axum::extract::Request { + let mut request = axum::http::Request::builder().method(method).uri(uri); + if let Some(credential) = credential { + request = request.header(header::AUTHORIZATION, credential); + } + request + .header(header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::from("{}")) + .expect("request") + } + + /// The service a refusal case runs against. + #[derive(Clone, Copy)] + enum Mode { + /// The legacy API key. + Legacy, + /// An OIDC verifier over a static key set. + Oidc, + /// The legacy API key on a service that loaded a seal. + LegacySealed, + /// An OIDC verifier and a seal that allows a different client. + OidcSealed, + /// An OIDC verifier whose key source answers 503. + Outage, + } + + async fn refusal_service(mode: Mode) -> Arc { + use registry_platform_crypto::document_signature::test_support::TestPki; + let lines = AuditLines::new(None); + let mut service = service(&lines, 1); + let inner = Arc::get_mut(&mut service).expect("fixture owns service"); + if matches!(mode, Mode::Oidc | Mode::OidcSealed) { + inner.oidc = Some(crate::auth::tests::test_verifier()); + } + if matches!(mode, Mode::Outage) { + let origin = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("key source listener"); + let url = format!("http://{}/jwks", origin.local_addr().expect("address")); + let keys_app = + Router::new().route("/jwks", get(|| async { StatusCode::SERVICE_UNAVAILABLE })); + tokio::spawn(async move { + axum::serve(origin, keys_app).await.expect("key source"); + }); + let fetch_policy = registry_platform_oidc::IssuerNetworkPolicy::new(&url, true) + .expect("loopback policy") + .declared_jwks_fetch_policy(); + inner.oidc = Some(crate::auth::tests::test_verifier_over(Arc::new( + registry_platform_oidc::JwksFetcher::new_with_fetch_url_policy( + url, + registry_platform_oidc::JwksFetcherConfig::defaults(), + fetch_policy, + ), + ))); + } + if matches!(mode, Mode::LegacySealed | Mode::OidcSealed) { + let pki = TestPki::generate().expect("test PKI"); + let test_seal = pki + .issue_seal(registry_platform_crypto::SigningAlgorithm::Es256) + .expect("test seal"); + let signer = Arc::new(test_seal.signer().expect("test signer")); + inner.seals.insert( + "ministry".to_owned(), + Arc::new(Seal::for_test("ministry", &test_seal, signer)), + ); + // The receipt names the seal, as a sealable document type does. + inner + .bundle + .documents + .get_mut("receipt") + .expect("receipt document") + .spec + .seal = Some("ministry".to_owned()); + } + service + } + + fn token_header(overrides: serde_json::Value) -> Option { + Some(format!("Bearer {}", crate::auth::tests::token(overrides))) + } + + /// One refusal: its name, the service, the request, and the check that + /// must refuse it. + struct RefusalCase { + name: &'static str, + mode: Mode, + method: Method, + uri: &'static str, + credential: Option, + check: &'static str, + } + + impl RefusalCase { + fn new( + name: &'static str, + mode: Mode, + method: Method, + uri: &'static str, + credential: Option, + check: &'static str, + ) -> Self { + Self { + name, + mode, + method, + uri, + credential, + check, + } + } + } + + /// Every refusal the access layers and the seal handler make, with the + /// check each one must record. + fn refusal_cases() -> Vec { + let legacy = |key: &str| Some(format!("Bearer {key}")); + vec![ + RefusalCase::new( + "no-authorization-header", + Mode::Legacy, + Method::GET, + "/v1/documents", + None, + "credential-missing", + ), + RefusalCase::new( + "scheme-not-bearer", + Mode::Legacy, + Method::GET, + "/v1/documents", + Some("Basic dXNlcjpwYXNz".to_owned()), + "credential-missing", + ), + RefusalCase::new( + "empty-bearer-token", + Mode::Legacy, + Method::GET, + "/v1/documents", + Some("Bearer ".to_owned()), + "credential-malformed", + ), + RefusalCase::new( + "legacy-key-mismatch", + Mode::Legacy, + Method::GET, + "/v1/documents", + legacy("canary-wrong-key-0123456789abcdef0123456789"), + "shared-secret", + ), + RefusalCase::new( + "compact-token-shape", + Mode::Oidc, + Method::GET, + "/v1/documents", + Some("Bearer canary-invalid-token".to_owned()), + "credential-malformed", + ), + RefusalCase::new( + "token-audience", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"aud":"urn:other"})), + "token-audience", + ), + RefusalCase::new( + "token-expired", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"exp":1})), + "token-time", + ), + RefusalCase::new( + "token-client", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"client_id":"other"})), + "token-client", + ), + RefusalCase::new( + "scope-on-render-route", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"scope":"other"})), + "scope", + ), + RefusalCase::new( + "render-scope-on-seal-route", + Mode::OidcSealed, + Method::POST, + "/v1/seal/receipt", + token_header(serde_json::json!({})), + "scope", + ), + RefusalCase::new( + "legacy-key-on-seal-route", + Mode::LegacySealed, + Method::POST, + "/v1/seal/receipt", + legacy(TEST_API_KEY), + "operation", + ), + RefusalCase::new( + "key-source-unavailable", + Mode::Outage, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({})), + "key-source-unavailable", + ), + RefusalCase::new( + "seal-client-not-allowed", + Mode::OidcSealed, + Method::POST, + "/v1/seal/receipt", + token_header(serde_json::json!({"scope":"render:seal"})), + "requester-client", + ), + ] + } + + /// The refusals as the whole stack answers them, frozen in a checked-in + /// file that was written from the tree before any recording existed. Run + /// with `REGISTRY_RENDER_WRITE_GOLDEN=1` to rewrite it. + #[tokio::test] + async fn refusal_answers_match_the_golden() { + let mut answers = serde_json::Map::new(); + for RefusalCase { + name, + mode, + method, + uri, + credential, + .. + } in refusal_cases() + { + let service = refusal_service(mode).await; + let response = refusal_stack(service, &Arc::new(Metrics::default())) + .oneshot(bearer_request(method, uri, credential)) + .await + .expect("router"); + answers.insert(name.to_owned(), frozen_answer(response).await); + } + let actual = serde_json::Value::Object(answers); + let path = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/authentication_refusals.json"); + if std::env::var_os("REGISTRY_RENDER_WRITE_GOLDEN").is_some() { + std::fs::create_dir_all(path.parent().expect("parent")).expect("golden directory"); + std::fs::write( + &path, + format!("{}\n", serde_json::to_string_pretty(&actual).expect("json")), + ) + .expect("write golden"); + } + let expected: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).expect("golden file")) + .expect("golden json"); + assert_eq!(actual, expected); + } + + /// The stack `serve` builds around the router, for the refusal tests. + fn refusal_stack(service: Arc, metrics: &Arc) -> Router { + public_app(service, metrics) + } + + /// A subscriber that keeps every formatted line in memory. + #[derive(Clone, Default)] + struct LogCapture(Arc>>); + + impl std::io::Write for LogCapture { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().expect("log").extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogCapture { + type Writer = Self; + + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } + } + + /// Every refusal is counted once under the check that refused it, writes + /// one value-free log line that names that check and the request's trace + /// id, and leaves every other check at zero. + #[tokio::test] + async fn each_refusal_is_counted_and_logged_under_its_check() { + let canaries = [ + "canary-wrong-key-0123456789abcdef0123456789", + "canary-invalid-token", + "canary-principal", + ]; + for RefusalCase { + name, + mode, + method, + uri, + credential, + check, + } in refusal_cases() + { + let logs = LogCapture::default(); + let subscriber = tracing_subscriber::fmt() + .json() + .with_max_level(tracing::Level::INFO) + .with_writer(logs.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let service = refusal_service(mode).await; + let metrics = Arc::new(Metrics::default()); + let response = refusal_stack(Arc::clone(&service), &metrics) + .oneshot(bearer_request(method, uri, credential)) + .await + .expect("router"); + let trace = registry_platform_httpsec::response_trace_id(response.headers()) + .expect("trace id") + .to_string(); + let text = scraped(&service, &metrics).await; + let counted: Vec<&str> = text + .lines() + .filter(|line| line.starts_with("render_request_refusals_total{")) + .filter(|line| !line.ends_with(" 0")) + .collect(); + assert_eq!( + counted, + [format!( + "render_request_refusals_total{{check=\"{check}\"}} 1" + )], + "{name}" + ); + let written = String::from_utf8(logs.0.lock().expect("log").clone()).expect("UTF-8"); + let lines: Vec = written + .lines() + .map(|line| serde_json::from_str::(line).expect("JSON log line")) + .filter(|line| line["fields"]["message"] == "request refused") + .collect(); + assert_eq!(lines.len(), 1, "{name}: {written}"); + let fields = &lines[0]["fields"]; + assert_eq!(fields["decision"], "refused", "{name}"); + assert_eq!(fields["failed_check"], check, "{name}"); + assert_eq!(fields["trace_id"], trace.as_str(), "{name}"); + for canary in canaries { + assert!(!written.contains(canary), "{name}: {written}"); + } + } + } + + #[tokio::test] + async fn the_refusal_counter_is_exposed_from_zero_for_every_check() { + let service = refusal_service(Mode::Legacy).await; + let text = scraped(&service, &Arc::new(Metrics::default())).await; + assert!(text.contains( + "# HELP render_request_refusals_total Requests refused, by the check that failed.\n# TYPE render_request_refusals_total counter\n" + )); + for check in registry_platform_authcommon::FailedCheck::ALL { + assert!( + text.contains(&format!( + "render_request_refusals_total{{check=\"{}\"}} 0", + check.as_str() + )), + "{}", + check.as_str() + ); + } + } } diff --git a/crates/registry-render/tests/golden/authentication_refusals.json b/crates/registry-render/tests/golden/authentication_refusals.json new file mode 100644 index 0000000000..8dfc7162c8 --- /dev/null +++ b/crates/registry-render/tests/golden/authentication_refusals.json @@ -0,0 +1,192 @@ +{ + "compact-token-shape": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "empty-bearer-token": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "key-source-unavailable": { + "body": { + "code": "render.authentication-unavailable", + "detail": "Credential verification is unavailable; retry when the issuer keys are available.", + "status": 503, + "title": "authentication-unavailable", + "type": "https://render.registrystack.org/problems/authentication-unavailable" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 503 + }, + "legacy-key-mismatch": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "legacy-key-on-seal-route": { + "body": { + "code": "render.forbidden", + "detail": "The legacy API key cannot seal; present an OIDC resource credential with the render:seal scope.", + "status": 403, + "title": "forbidden", + "type": "https://render.registrystack.org/problems/forbidden" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "no-authorization-header": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "render-scope-on-seal-route": { + "body": { + "code": "render.forbidden", + "detail": "Obtain a Render resource credential with the render:seal scope.", + "status": 403, + "title": "forbidden", + "type": "https://render.registrystack.org/problems/forbidden" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "scheme-not-bearer": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "scope-on-render-route": { + "body": { + "code": "render.forbidden", + "detail": "Obtain a Render resource credential with the render:render scope.", + "status": 403, + "title": "forbidden", + "type": "https://render.registrystack.org/problems/forbidden" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "seal-client-not-allowed": { + "body": { + "code": "render.seal-client-not-allowed", + "detail": "This client is not allowed to use this document type's seal.", + "status": 403, + "title": "seal-client-not-allowed", + "type": "https://render.registrystack.org/problems/seal-client-not-allowed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "token-audience": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "token-client": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "token-expired": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + } +} diff --git a/crates/registry-scheduling/Cargo.toml b/crates/registry-scheduling/Cargo.toml index 9e81ef5156..04d9bba46a 100644 --- a/crates/registry-scheduling/Cargo.toml +++ b/crates/registry-scheduling/Cargo.toml @@ -38,16 +38,17 @@ jsonwebtoken.workspace = true registry-scheduling-core.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-calendar.workspace = true registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true registry-platform-dispatch = { workspace = true, features = ["postgres"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-httputil.workspace = true registry-platform-hooks = { workspace = true, features = ["postgres"] } +registry-platform-loopback.workspace = true registry-platform-metrics.workspace = true registry-platform-oidc.workspace = true registry-platform-yaml.workspace = true diff --git a/crates/registry-scheduling/src/auth.rs b/crates/registry-scheduling/src/auth.rs index 730a7ed76f..e74ffb7bc7 100644 --- a/crates/registry-scheduling/src/auth.rs +++ b/crates/registry-scheduling/src/auth.rs @@ -35,9 +35,9 @@ use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use chrono::{DateTime, Utc}; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, FailedCheck, RefusalRecorder}; use registry_platform_oidc::{ - actor_kind, grant_claims, ClaimNames, JwksFetcher, OidcError, TokenVerifier, + actor_kind, grant_claims, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, }; use serde_json::Value; @@ -63,15 +63,16 @@ pub struct SchedulingAuthenticator { busy_import_profiles: BTreeMap, /// Whether the deployment declared any assertion authority at all. binds_assertion_issuers: bool, + /// Counts and logs every refusal the HTTP edge answers, by failed check. + refusals: Arc, } impl SchedulingAuthenticator { - pub(crate) fn record_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Header, - "Scheduling authentication refused" - ); + /// The recorder the HTTP edge reports each refusal to, and whose counter + /// the metrics listener exposes. + #[must_use] + pub fn refusals(&self) -> &Arc { + &self.refusals } #[must_use] @@ -91,6 +92,9 @@ impl SchedulingAuthenticator { appointment_read_profiles: oidc.appointment_read_profiles.clone(), busy_import_profiles: oidc.busy_import_profiles.clone(), binds_assertion_issuers: !oidc.clients.assertion_issuers.is_empty(), + refusals: Arc::new( + RefusalRecorder::new("scheduling").expect("the refusal counter is declared once"), + ), } } @@ -135,7 +139,7 @@ impl SchedulingAuthenticator { }) { return Ok((caller, DetailAdmission::Grant)); } - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) } /// The profile the separately authorized explain path demands: the caller @@ -146,7 +150,7 @@ impl SchedulingAuthenticator { } /// Admit a verified caller holding `required`, or refuse it as a profile - /// miss. Diagnostics name only the fixed stage, never scope or claim values. + /// miss. Nothing about the refusal names a scope or claim value. fn require_scope( &self, caller: Caller, @@ -157,13 +161,7 @@ impl SchedulingAuthenticator { if scopes.iter().any(|scope| scope == required) { return Ok(caller); } - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Scope, - "Scheduling authentication profile refused", - remedy = "check authentication.oidc.scopeClaim and readsScope or explainScope" - ); - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) } /// The profile the commitments demand: no product scope, because the @@ -183,16 +181,16 @@ impl SchedulingAuthenticator { profile_selector: &str, ) -> Result { let (caller, scopes, client) = self.verified_caller(token).await?; - let client = client.ok_or(AuthenticationError::Claims)?; + let client = client.ok_or(AuthenticationError::Claims(FailedCheck::TokenClient))?; let identity = BusySourceIdentity::new(caller.issuer, caller.subject, client) - .map_err(|_| AuthenticationError::Profile)?; + .map_err(|_| AuthenticationError::Profile(FailedCheck::TokenClaims))?; authorize_busy_source( &self.busy_import_profiles, &scopes, Some(profile_selector), identity, ) - .map_err(|_| AuthenticationError::Profile) + .map_err(|error| AuthenticationError::Profile(error.failed_check())) } /// Verify one token and authorize exactly one opt-in operational profile @@ -206,9 +204,9 @@ impl SchedulingAuthenticator { now: DateTime, ) -> Result { let (caller, scopes, client) = self.verified_caller(token).await?; - let client = client.ok_or(AuthenticationError::Claims)?; + let client = client.ok_or(AuthenticationError::Claims(FailedCheck::TokenClient))?; let identity = OperationalIdentity::new(caller.issuer, caller.subject, client) - .map_err(|_| AuthenticationError::Claims)?; + .map_err(|_| AuthenticationError::Claims(FailedCheck::TokenClaims))?; authorize_operational_read( &self.appointment_read_profiles, &scopes, @@ -217,7 +215,7 @@ impl SchedulingAuthenticator { filter, now, ) - .map_err(|_| AuthenticationError::Profile) + .map_err(|_| AuthenticationError::Profile(FailedCheck::AccessProfile)) } /// Verify one credential and resolve its caller. A present grant is bound @@ -227,18 +225,13 @@ impl SchedulingAuthenticator { &self, token: &str, ) -> Result<(Caller, Vec, Option), AuthenticationError> { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Scheduling authentication refused" - ); - verifier_failure(&error) - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| verifier_failure(&error))?; // An exchanged token names the authority whose assertion produced it. // The platform applies no rule while the deployment's map is empty, so // an empty map would trust every authority the issuer federates. @@ -247,23 +240,27 @@ impl SchedulingAuthenticator { if !self.binds_assertion_issuers && verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - tracing::debug!( - "an exchanged credential arrived at a deployment that declared no assertion authority" - ); - return Err(AuthenticationError::Profile); + return Err(AuthenticationError::Profile( + FailedCheck::TokenAssertionIssuer, + )); } let kind = actor_kind(&verified.claims, &self.claim_names) - .map_err(|_| AuthenticationError::Claims)?; - let grant = grant_claims(&verified.claims, &self.claim_names, unix_now()?) - .map_err(|_| AuthenticationError::Claims)?; + .map_err(|_| AuthenticationError::Claims(FailedCheck::ActorKind))?; + let grant = + grant_claims(&verified.claims, &self.claim_names, unix_now()?).map_err(|error| { + AuthenticationError::Claims(match error { + ClaimError::Expired => FailedCheck::TaskGrantExpired, + _ => FailedCheck::TaskGrantClaims, + }) + })?; if let Some(grant) = &grant { grant .verify_context(&verified, &self.audience) - .map_err(|_| AuthenticationError::Profile)?; + .map_err(|_| AuthenticationError::Profile(FailedCheck::TaskGrantBinding))?; } let client = verified .matched_client_id() - .map_err(|_| AuthenticationError::Claims)? + .map_err(|_| AuthenticationError::Claims(FailedCheck::TokenClient))? .filter(|client| !client.is_empty()) .map(str::to_owned); // A task-grant exchange preserves the subjects its source authority @@ -287,18 +284,18 @@ impl SchedulingAuthenticator { .iss .clone() .filter(|issuer| !issuer.is_empty()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; let subject = verified .claims .sub .clone() .filter(|subject| !subject.is_empty()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; let credential_exp_unix = verified .claims .exp .and_then(|value| u64::try_from(value).ok()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; Ok(( Caller { actor_kind: kind.as_str().to_owned(), @@ -330,14 +327,17 @@ impl std::fmt::Debug for SchedulingAuthenticator { } } +/// Why authentication refused a request. Each refusal carries the check it +/// failed, which only the operator sees: the answer to the caller is the same +/// for every check of one kind. #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] - Refused, + Refused(FailedCheck), #[error("the verified identity claims are invalid")] - Claims, + Claims(FailedCheck), #[error("the caller's authentication profile is not authorized for this request")] - Profile, + Profile(FailedCheck), /// The verifier could not reach a verdict at all. #[error("the credential could not be verified because this verifier cannot answer")] Unavailable, @@ -368,8 +368,9 @@ fn verifier_failure(error: &OidcError) -> AuthenticationError { // signal, not an outage, and answering 503 there would let a caller // probe the key set. A variant added to the platform later is read as // a credential refusal until it is classified here, so a new outcome - // can never widen the door. - _ => AuthenticationError::Refused, + // can never widen the door. The check the refusal records is the + // shared verifier's own map. + _ => AuthenticationError::Refused(error.failed_check()), } } @@ -641,7 +642,7 @@ mod tests { assert_eq!(admission, DetailAdmission::Grant); assert!(matches!( authenticator.authenticate_read(&credential).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); let without_action = token(merged("scheduling-explain", grant_claims_value(AUDIENCE))); @@ -649,7 +650,7 @@ mod tests { authenticator .authenticate_appointment_detail(&without_action) .await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); } @@ -664,7 +665,7 @@ mod tests { let authenticator = authenticator(); assert!(matches!( authenticator.authenticate_read(&credential).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); // Mutating routes demand no product scope: their authority is the // task grant, checked per offering in the service. @@ -692,7 +693,7 @@ mod tests { Utc::now(), ) .await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::AccessProfile)) ); let grant_only = token(merged("", grant_claims_value(AUDIENCE))); @@ -700,7 +701,7 @@ mod tests { authenticator .authenticate_operational_read(&grant_only, None, operational_filter(), Utc::now(),) .await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::AccessProfile)) ); let two_roles = token(json!({ @@ -713,7 +714,7 @@ mod tests { authenticator .authenticate_operational_read(&two_roles, None, operational_filter(), Utc::now(),) .await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::AccessProfile)) ); let authorized = authenticator .authenticate_operational_read( @@ -738,7 +739,7 @@ mod tests { })); assert!(matches!( authenticator.authenticate_explain(&reader).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); let explainer = token(json!({ "sub": "principal-2", @@ -799,7 +800,7 @@ mod tests { )); assert!(matches!( authenticator().authenticate_mutate(&credential).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::TaskGrantBinding)) )); } @@ -812,7 +813,7 @@ mod tests { let credential = token(merged("scheduling-read", grant)); assert!(matches!( authenticator().authenticate_mutate(&credential).await, - Err(AuthenticationError::Claims) + Err(AuthenticationError::Claims(FailedCheck::TaskGrantClaims)) )); } @@ -826,7 +827,7 @@ mod tests { })); assert!(matches!( authenticator().authenticate_read(&credential).await, - Err(AuthenticationError::Claims) + Err(AuthenticationError::Claims(FailedCheck::ActorKind)) )); } @@ -843,7 +844,9 @@ mod tests { assert!( matches!( authenticator().authenticate_read(&credential).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile( + FailedCheck::TokenAssertionIssuer + )) ), "an exchanged token was accepted by a deployment that declared no assertion authority" ); @@ -867,7 +870,9 @@ mod tests { })); assert!(matches!( authenticator_with(declared).authenticate_read(&other).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused( + FailedCheck::TokenAssertionIssuer + )) )); } @@ -985,7 +990,7 @@ mod tests { ] { assert_eq!( verifier_failure(&refusal), - AuthenticationError::Refused, + AuthenticationError::Refused(refusal.failed_check()), "{refusal} was excused as an outage" ); } @@ -1016,40 +1021,21 @@ mod tests { .unwrap(); assert!(matches!( authenticator().authenticate_read(&forged).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(FailedCheck::TokenSignature)) )); } #[tokio::test] - async fn compact_token_admission_logs_one_value_free_header_diagnostic() { - use registry_platform_testing::{malformed_access_token_fixtures, CapturedDiagnosticLogs}; - use tracing::instrument::WithSubscriber; - let captured = CapturedDiagnosticLogs::default(); - let subscriber = captured.subscriber(); - let tokens = malformed_access_token_fixtures(); + async fn malformed_compact_tokens_are_refused_as_malformed_credentials() { + let tokens = registry_platform_testing::malformed_access_token_fixtures(); let auth = authenticator(); - for _ in 0..3 { - for token in &tokens { - assert!(matches!( - auth.authenticate_read(token) - .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - assert!(matches!( - auth.authenticate_explain(token) - .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - assert!(matches!( - auth.authenticate_mutate(token) - .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - } + for token in &tokens { + let malformed = Some(AuthenticationError::Refused( + FailedCheck::CredentialMalformed, + )); + assert_eq!(auth.authenticate_read(token).await.err(), malformed); + assert_eq!(auth.authenticate_explain(token).await.err(), malformed); + assert_eq!(auth.authenticate_mutate(token).await.err(), malformed); } - captured.assert_one_value_free_header_diagnostic(&tokens); } #[tokio::test] @@ -1084,7 +1070,7 @@ mod tests { let auth = &auth; async move { auth.authenticate_read(&token).await } }, - |error| matches!(error, AuthenticationError::Refused), + |error| matches!(error, AuthenticationError::Refused(_)), ) .await; // A valid symmetric JWT is outside the asymmetric production baseline. @@ -1093,21 +1079,21 @@ mod tests { ); assert!(matches!( auth.authenticate_read(&token).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(_)) )); let mut wrong_actor = claims.clone(); wrong_actor["registry_actor_kind"] = json!("canary-invalid-actor"); let token = sign(wrong_actor, "at+jwt"); assert!(matches!( auth.authenticate_read(&token).await, - Err(AuthenticationError::Claims) + Err(AuthenticationError::Claims(FailedCheck::ActorKind)) )); let mut missing = claims.clone(); missing["registry_scopes"] = json!(""); let token = sign(missing, "at+jwt"); assert!(matches!( auth.authenticate_read(&token).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); } } diff --git a/crates/registry-scheduling/src/config.rs b/crates/registry-scheduling/src/config.rs index dab6998f8d..868763eaea 100644 --- a/crates/registry-scheduling/src/config.rs +++ b/crates/registry-scheduling/src/config.rs @@ -28,10 +28,12 @@ pub use registry_platform_config::{ SecretProvidersConfig, TaskGrantStatusConfig, TlsTermination, UrlHookDestinationConfig, }; use registry_platform_httputil::destination::validate_fixed_destination_path; +use registry_platform_loopback::loopback_host; use registry_platform_oidc::task_grant::{TaskGrantStatusEndpoint, TaskGrantStatusRegistry}; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifierConfig, }; use registry_platform_yaml::{ escape_pointer_segment, Diagnostic, Invalid, LocalId, Report, RetiredApiVersion, @@ -1166,8 +1168,18 @@ impl RuntimeConfig { &error, )) })?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| RuntimeConfigError::Oidc)?; + let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { + match error { + // The operator's document broke a key set rule: say + // which, so the fix does not start at the issuer. + OidcError::StaticKeySet(refusal) => { + RuntimeConfigError::OidcJwksSecret(format!( + "the document at authentication.oidc.jwksSource.documentRef was refused: {refusal}" + )) + } + _ => RuntimeConfigError::Oidc, + } + })?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -1280,10 +1292,9 @@ fn valid_destination_url(value: &str) -> bool { { match parsed.scheme() { "https" => true, - "http" => matches!( - parsed.host_str(), - Some("127.0.0.1") | Some("localhost") | Some("[::1]") - ), + "http" => parsed + .host_str() + .is_some_and(|host| loopback_host(host).is_some()), _ => false, } } else { @@ -4420,7 +4431,9 @@ holdPolicy: /// The runtime's static JWKS arm hands the resolved document to the /// shared parser and refuses a key set it cannot trust before any /// verifier exists: a symmetric key, an unnamed key, two keys sharing a - /// name, or no key at all. + /// name, a private key member, or no key at all. The operator is told + /// which rule the file broke, under the code for an unusable key file + /// and never the issuer-unreachable one. #[cfg(unix)] #[tokio::test] async fn static_jwks_requires_unique_named_asymmetric_keys() { @@ -4447,14 +4460,42 @@ holdPolicy: .await .expect("one named asymmetric key is accepted"); - for (case, invalid) in [ - ("symmetric", br#"{"keys":[{"kty":"oct","kid":"one","k":"AA"}]}"#.as_slice()), - ("unnamed", br#"{"keys":[{"kty":"RSA","n":"AQAB","e":"AQAB"}]}"#), + // Members the key set rule does not name are not inspected. + write_jwks( + br#"{"issuer":"https://issuer.test","keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","ext":true,"x5c":["AA=="],"x5t":"AA","x5u":"https://issuer.test/chain"}]}"#, + ); + config + .oidc_verifier(&secrets) + .await + .expect("unknown public members are ignored"); + + for (case, invalid, text) in [ + ( + "symmetric", + br#"{"keys":[{"kty":"oct","kid":"one","k":"AA"}]}"#.as_slice(), + "symmetric key", + ), + ( + "unnamed", + br#"{"keys":[{"kty":"RSA","n":"AQAB","e":"AQAB"}]}"#, + "has no \"kid\"", + ), ( "duplicate name", br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + "repeats the \"kid\"", + ), + ("empty", br#"{"keys":[]}"#, "holds no keys"), + ( + "private member", + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","d":"AQAB"}]}"#, + "private-key member \"d\"", + ), + ( + "repeated member name", + br#"{"keys":[{"kty":"RSA","kid":"one","kid":"two","n":"AQAB","e":"AQAB"}]}"#, + "repeats a member name", ), - ("empty", br#"{"keys":[]}"#), ] { write_jwks(invalid); let error = config @@ -4465,15 +4506,47 @@ holdPolicy: assert_eq!( refusal(&error), ( - "scheduling.runtime-dependency.unavailable".to_owned(), - "/authentication/oidc".to_owned() + "scheduling.runtime.unreadable-jwks-secret".to_owned(), + "/authentication/oidc/jwksSource/documentRef".to_owned() ), "{case}" ); + assert!(error.to_string().contains(text), "{case}: {error}"); assert!(!error.in_file(), "{case}"); } } + /// A reminder or hook destination takes plain http only on a loopback + /// host: any address of 127.0.0.0/8, `::1`, a mapped loopback address, or + /// the exact name `localhost`. Another host, or another spelling of the + /// name, is refused. + #[test] + fn plain_http_destinations_take_only_loopback_hosts() { + for accepted in [ + "http://127.0.0.1:8080/hook", + "http://127.0.0.2:8080/hook", + "http://[::1]:8080/hook", + "http://[::ffff:127.0.0.1]:8080/hook", + "http://localhost:8080/hook", + "http://LOCALHOST:8080/hook", + "https://example.test/hook", + ] { + assert!(valid_destination_url(accepted), "{accepted}"); + } + for refused in [ + "http://10.0.0.1:8080/hook", + "http://[::ffff:10.0.0.1]:8080/hook", + "http://0.0.0.0:8080/hook", + "http://[::]:8080/hook", + "http://169.254.169.254/hook", + "http://a.localhost:8080/hook", + "http://localhost.:8080/hook", + "http://example.test/hook", + ] { + assert!(!valid_destination_url(refused), "{refused}"); + } + } + /// A runtime file that breaks three rules, each away from the others. fn file_breaking_three_rules(root: &Path) -> PathBuf { let mut document = operator_value(&root.join("package"), "development-loopback"); diff --git a/crates/registry-scheduling/src/http.rs b/crates/registry-scheduling/src/http.rs index f6b5e21afb..065c8c302f 100644 --- a/crates/registry-scheduling/src/http.rs +++ b/crates/registry-scheduling/src/http.rs @@ -32,7 +32,9 @@ use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post, put}; use axum::{Json, Router}; use chrono::{DateTime, Utc}; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, record_refusal, BearerParseError, FailedCheck, RefusalNote, RefusalRecorder, +}; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, FrameworkRejection, ProblemBody, TraceContext, @@ -53,7 +55,9 @@ use uuid::Uuid; use crate::auth::{AuthenticationError, SchedulingAuthenticator}; use crate::metrics::{serve_metrics, Metrics, MetricsState, METRICS_PATH}; -use crate::service::{Caller, CommitmentAnswer, DetailAdmission, SchedulingService, ServiceError}; +use crate::service::{ + Caller, CommitmentAnswer, DetailAdmission, RefusalCode, SchedulingService, ServiceError, +}; use crate::source_busy::{ validate_busy_reconciliation_request, BusyReconciliationRequest, BusyRequestError, BUSY_SOURCE_APPLY_PATH, BUSY_SOURCE_PREVIEW_PATH, @@ -87,7 +91,8 @@ pub fn metrics_router(metrics: Arc, store: PostgresStore) -> Router { } pub fn router(state: HttpState) -> Router { - http_edge( + let refusals = Arc::clone(state.authenticator.refusals()); + http_edge(with_refusal_recording( Router::new() .route(HEALTH_PATH, get(health)) .route(READY_PATH, get(ready)) @@ -117,7 +122,8 @@ pub fn router(state: HttpState) -> Router { .route(APPOINTMENT_CANCEL_ROUTE, post(cancel_appointment)) .route(APPOINTMENT_HISTORY_ROUTE, get(appointment_history)) .route(APPOINTMENT_ATTENDANCE_ROUTE, put(record_attendance)), - ) + refusals, + )) .with_state(state) } @@ -167,10 +173,9 @@ async fn authenticate_busy_source( profile: &str, ) -> Result { if !valid_identifier(profile) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_busy_source(token, profile) @@ -180,26 +185,28 @@ async fn authenticate_busy_source( fn busy_request_problem(error: BusyRequestError) -> HttpError { match error { - BusyRequestError::Authority => HttpError(ProblemCode::ProfileNotAuthorized), + BusyRequestError::Authority => { + HttpError::refused(RefusalCode::ProfileNotAuthorized, FailedCheck::Operation) + } BusyRequestError::Invalid | BusyRequestError::Bound => { - HttpError(ProblemCode::RequestInvalid) + HttpError::plain(ProblemCode::RequestInvalid) } } } fn busy_store_problem(error: BusyStoreError) -> HttpError { match error { - BusyStoreError::RevisionMismatch { .. } => HttpError(ProblemCode::RevisionMismatch), + BusyStoreError::RevisionMismatch { .. } => HttpError::plain(ProblemCode::RevisionMismatch), BusyStoreError::CoverageBoundary | BusyStoreError::ObservationConflict => { - HttpError(ProblemCode::PreconditionFailed) + HttpError::plain(ProblemCode::PreconditionFailed) } - BusyStoreError::ResourceMissing => HttpError(ProblemCode::ResourceUnavailable), + BusyStoreError::ResourceMissing => HttpError::plain(ProblemCode::ResourceUnavailable), BusyStoreError::AuditUnavailable | BusyStoreError::RecoveryUnavailable | BusyStoreError::Query(_) | BusyStoreError::Store(_) => { tracing::error!(%error, "the source-busy operation failed"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::plain(ProblemCode::ServiceUnavailable) } } } @@ -267,7 +274,7 @@ async fn ready(State(state): State) -> Result { if state.service.ready().await.is_ok() { Ok(probe_response(READY_BODY)) } else { - Err(HttpError(ProblemCode::ServiceUnavailable)) + Err(HttpError::plain(ProblemCode::ServiceUnavailable)) } } @@ -282,7 +289,7 @@ async fn readyz(State(state): State) -> Result if state.service.ready().await.is_ok() { Ok(StatusCode::OK) } else { - Err(HttpError(ProblemCode::ServiceUnavailable)) + Err(HttpError::plain(ProblemCode::ServiceUnavailable)) } } @@ -618,13 +625,13 @@ async fn list_operational_appointments( record_type, identifier, }), - _ => return Err(HttpError(ProblemCode::RequestInvalid)), + _ => return Err(HttpError::plain(ProblemCode::RequestInvalid)), }; if profile .as_deref() .is_some_and(|profile| !valid_identifier(profile)) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } let filter = crate::operational::OperationalReadFilter::with_optional_filters( service, @@ -637,9 +644,8 @@ async fn list_operational_appointments( start, end, ) - .map_err(|_| HttpError(ProblemCode::RequestInvalid))?; - let token = - bearer_token(&headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + .map_err(|_| HttpError::plain(ProblemCode::RequestInvalid))?; + let token = bearer_token(&headers)?; let authority = state .authenticator .authenticate_operational_read( @@ -852,7 +858,7 @@ fn bounded_selection( if duration_minutes.is_some_and(|value| { !(1..=registry_scheduling_core::MAXIMUM_BOOKING_DURATION_MINUTES).contains(&value) }) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } if let Some(resource) = &resource { bounded_identifier(resource)?; @@ -873,21 +879,19 @@ struct ExplainQuery { } async fn authenticate_read(state: &HttpState, headers: &HeaderMap) -> Result { - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_read(token) .await - .map_err(authentication_problem) + .map_err(|error| authentication_problem(error).with_scope_remedy()) } async fn authenticate_appointment_detail( state: &HttpState, headers: &HeaderMap, ) -> Result<(Caller, DetailAdmission), HttpError> { - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_appointment_detail(token) @@ -896,18 +900,16 @@ async fn authenticate_appointment_detail( } async fn authenticate_explain(state: &HttpState, headers: &HeaderMap) -> Result { - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_explain(token) .await - .map_err(authentication_problem) + .map_err(|error| authentication_problem(error).with_scope_remedy()) } async fn authenticate_mutate(state: &HttpState, headers: &HeaderMap) -> Result { - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_mutate(token) @@ -916,24 +918,36 @@ async fn authenticate_mutate(state: &HttpState, headers: &HeaderMap) -> Result Result<&str, HttpError> { + let refused = |check| HttpError::refused(RefusalCode::AuthenticationRefused, check); let authorization = headers .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .ok_or(HttpError(ProblemCode::AuthenticationRefused))?; - parse_bearer_token(authorization).map_err(|_| HttpError(ProblemCode::AuthenticationRefused)) + .ok_or_else(|| refused(FailedCheck::CredentialMissing))? + .to_str() + .map_err(|_| refused(FailedCheck::CredentialMalformed))?; + parse_bearer_token(authorization).map_err(|error| { + refused(match error { + // Another scheme is a credential this route does not take. + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) + }) } fn authentication_problem(error: AuthenticationError) -> HttpError { match error { - AuthenticationError::Refused | AuthenticationError::Claims => { - HttpError(ProblemCode::AuthenticationRefused) + AuthenticationError::Refused(check) | AuthenticationError::Claims(check) => { + HttpError::refused(RefusalCode::AuthenticationRefused, check) + } + AuthenticationError::Profile(check) => { + HttpError::refused(RefusalCode::ProfileNotAuthorized, check) } - AuthenticationError::Profile => HttpError(ProblemCode::ProfileNotAuthorized), // The verifier reached no verdict, so the credential is not what is // wrong. Answering 401 here would challenge a caller holding a good // token and invite it to rotate one during an outage that is ours; // `service.unavailable` carries `Retry-After` instead. - AuthenticationError::Unavailable => HttpError(ProblemCode::ServiceUnavailable), + AuthenticationError::Unavailable => { + HttpError::unavailable(FailedCheck::KeySourceUnavailable) + } } } @@ -966,7 +980,7 @@ fn bounded_admission(request: &AdmissionRequest) -> Result<(), HttpError> { bounded_references(&request.capabilities)?; bounded_references(&request.prerequisites)?; if request.external_references.len() > MAXIMUM_COLLECTION_ENTRIES { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } let mut unique = BTreeSet::new(); for reference in &request.external_references { @@ -976,11 +990,11 @@ fn bounded_admission(request: &AdmissionRequest) -> Result<(), HttpError> { reference.record_type.as_str(), reference.identifier.as_str(), )) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } } if request.party_references.len() > registry_scheduling_core::MAXIMUM_PARTY_REFERENCES { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } let mut unique_parties = BTreeSet::new(); for party in &request.party_references { @@ -991,7 +1005,7 @@ fn bounded_admission(request: &AdmissionRequest) -> Result<(), HttpError> { party.reference.record_type.as_str(), party.reference.identifier.as_str(), )) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } } Ok(()) @@ -1007,20 +1021,20 @@ fn bounded_external_reference(reference: &ExternalReference) -> Result<(), HttpE fn bounded_identifier(value: &str) -> Result<(), HttpError> { valid_identifier(value) .then_some(()) - .ok_or(HttpError(ProblemCode::RequestInvalid)) + .ok_or(HttpError::plain(ProblemCode::RequestInvalid)) } /// One scoped reference as the authored grammar admits it. fn bounded_reference(value: &str) -> Result<(), HttpError> { valid_reference(value) .then_some(()) - .ok_or(HttpError(ProblemCode::RequestInvalid)) + .ok_or(HttpError::plain(ProblemCode::RequestInvalid)) } /// A list of scoped references, no longer than a policy collection may be. fn bounded_references(values: &[String]) -> Result<(), HttpError> { if values.len() > MAXIMUM_COLLECTION_ENTRIES { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } values.iter().try_for_each(|value| bounded_reference(value)) } @@ -1029,7 +1043,7 @@ fn bounded_references(values: &[String]) -> Result<(), HttpError> { fn bounded_reason(reason: Option<&str>) -> Result<(), HttpError> { match reason { Some(reason) if reason.len() > MAXIMUM_CANCELLATION_REASON_BYTES => { - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError::plain(ProblemCode::RequestInvalid)) } _ => Ok(()), } @@ -1042,33 +1056,118 @@ fn idempotency_key(headers: &HeaderMap) -> Result<&str, HttpError> { .get(IDEMPOTENCY_KEY_HEADER) .and_then(|value| value.to_str().ok()) .filter(|value| !value.is_empty()) - .ok_or(HttpError(ProblemCode::RequestInvalid))?; + .ok_or(HttpError::plain(ProblemCode::RequestInvalid))?; if value.len() > MAXIMUM_IDEMPOTENCY_KEY_BYTES || !value.bytes().all(|byte| byte.is_ascii_graphic()) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } Ok(value) } -/// One refusal from the closed vocabulary, as an HTTP answer: every product +/// One answer from the closed vocabulary, as an HTTP answer: every product /// decision and every request-edge rejection renders through the same pinned -/// document. +/// document. A refusal of authority also carries the check it failed, which +/// reaches the operator's counter and log line through the response +/// extensions and never the caller's body. #[derive(Debug)] -pub struct HttpError(pub ProblemCode); +pub struct HttpError { + problem: ProblemCode, + note: Option, +} + +impl HttpError { + /// An answer that is not a refusal of authority. A refusal code is built + /// with [`HttpError::refused`] so it names its check. + pub(crate) fn plain(problem: ProblemCode) -> Self { + if RefusalCode::of(problem).is_some() { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + code = problem.code(), + "a refusal was answered without its failed check" + ); + } + Self { + problem, + note: None, + } + } + + /// A refusal of authority, with the check it failed. + pub(crate) fn refused(code: RefusalCode, check: FailedCheck) -> Self { + Self { + problem: code.problem(), + note: Some(RefusalNote::new(check)), + } + } + + /// `service.unavailable`, counted under the check that could not be made. + pub(crate) fn unavailable(check: FailedCheck) -> Self { + Self { + problem: ProblemCode::ServiceUnavailable, + note: Some(RefusalNote::new(check)), + } + } + + /// Name the setting the operator checks when this is a scope refusal of + /// a read or explain route. + fn with_scope_remedy(mut self) -> Self { + self.note = self.note.map(|note| { + if note.check == FailedCheck::Scope { + note.with_remedy(SCOPE_REMEDY) + } else { + note + } + }); + self + } +} + +/// The fixed operator hint on a read or explain scope refusal. +const SCOPE_REMEDY: &str = "check authentication.oidc.scopeClaim and readsScope or explainScope"; impl From for HttpError { fn from(error: ServiceError) -> Self { match error { - ServiceError::Problem(problem) => Self(problem), + ServiceError::Problem(problem) => Self::plain(problem), + ServiceError::Refused { code, check } => Self::refused(code, check), } } } impl IntoResponse for HttpError { fn into_response(self) -> Response { - problem_response(self.0) + let mut response = problem_response(self.problem); + if let Some(note) = self.note { + response.extensions_mut().insert(note); + } + response + } +} + +/// Record the refusals the routes answer. The edge layers wrap this one, so +/// the request's trace is in scope when a refusal is recorded. +fn with_refusal_recording(routes: Router, recorder: Arc) -> Router +where + S: Clone + Send + Sync + 'static, +{ + routes.layer(middleware::from_fn_with_state(recorder, record_refusals)) +} + +/// Count and log every refusal an answer carries, once, after the route has +/// answered. The note rides in the response extensions, which are never +/// serialized, so recording cannot change a byte of the answer. +async fn record_refusals( + State(recorder): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::().copied() { + let trace = current_trace(); + record_refusal!(recorder, note, trace_id = &trace.trace_id); } + response } fn current_trace() -> TraceContext { @@ -1227,6 +1326,246 @@ mod tests { ) } + /// The refusals a request can meet, by case name, as the handlers build + /// them: one route that answers each one under the recording layer. + fn refusal_case(case: &str) -> HttpError { + match case { + "credential-missing" => bearer_token(&HeaderMap::new()).unwrap_err(), + "credential-malformed" => { + bearer_token(&headers_with(AUTHORIZATION, "Bearer a b")).unwrap_err() + } + "token-signature" => { + authentication_problem(AuthenticationError::Refused(FailedCheck::TokenSignature)) + } + "scope" => authentication_problem(AuthenticationError::Profile(FailedCheck::Scope)) + .with_scope_remedy(), + "operation" => { + HttpError::refused(RefusalCode::ProfileNotAuthorized, FailedCheck::Operation) + } + "task-grant-missing" => ServiceError::Refused { + code: RefusalCode::OperationNotAuthorized, + check: FailedCheck::TaskGrantMissing, + } + .into(), + "visibility" => ServiceError::Refused { + code: RefusalCode::OperationNotAuthorized, + check: FailedCheck::Visibility, + } + .into(), + "task-grant-lifetime" => HttpError::refused( + RefusalCode::GrantLifetimeTooLong, + FailedCheck::TaskGrantLifetime, + ), + "key-source-unavailable" => authentication_problem(AuthenticationError::Unavailable), + "plain" => HttpError::plain(ProblemCode::RequestInvalid), + other => unreachable!("no refusal case named {other}"), + } + } + + fn refusal_router(recorder: Arc) -> Router { + async fn refuse(Path(case): Path) -> HttpError { + refusal_case(&case) + } + http_edge(with_refusal_recording( + Router::new().route("/refuse/{case}", get(refuse)), + recorder, + )) + } + + fn refusal_exposition(recorder: &RefusalRecorder) -> String { + let mut out = registry_platform_metrics::Exposition::new(); + recorder + .counter() + .write(&mut out) + .expect("the counter writes"); + out.finish() + } + + fn refusal_lines(captured: ®istry_platform_testing::CapturedDiagnosticLogs) -> Vec { + captured + .text() + .lines() + .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) + .filter(|event| event["fields"]["message"] == "request refused") + .collect() + } + + const REFUSAL_CASES: [&str; 8] = [ + "credential-missing", + "credential-malformed", + "token-signature", + "scope", + "operation", + "task-grant-missing", + "visibility", + "task-grant-lifetime", + ]; + + /// Every refusal answer keeps its status, headers and body. The golden + /// file holds what each refusal answered before its check was recorded, + /// with the trace id removed. + #[tokio::test] + async fn refusal_answers_match_the_golden_bodies() { + use tracing::instrument::WithSubscriber as _; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let mut observed = serde_json::Map::new(); + for case in REFUSAL_CASES.into_iter().chain(["key-source-unavailable"]) { + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let response = refusal_router(Arc::clone(&recorder)) + .oneshot(traced_request("GET", &format!("/refuse/{case}"))) + .with_subscriber(captured.subscriber()) + .await + .expect("an in-process request always answers"); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("an ASCII header").to_owned()) + }; + let mut entry = serde_json::json!({ + "status": response.status().as_u16(), + "contentType": header("content-type"), + "wwwAuthenticate": header("www-authenticate"), + "retryAfter": header("retry-after"), + "cacheControl": header("cache-control"), + }); + let mut body = body_json(response).await; + assert_eq!(body["traceId"], TRACE_ID, "{case}"); + body.as_object_mut().unwrap().remove("traceId"); + entry["body"] = body; + observed.insert(case.to_owned(), entry); + } + let golden: Value = + serde_json::from_str(include_str!("../tests/golden/refusal-answers.json")) + .expect("the golden file is JSON"); + assert_eq!(Value::Object(observed), golden); + } + + #[tokio::test] + async fn each_refusal_is_counted_and_logged_once_under_its_check() { + use tracing::instrument::WithSubscriber as _; + for (case, check) in [ + ("credential-missing", "credential-missing"), + ("credential-malformed", "credential-malformed"), + ("token-signature", "token-signature"), + ("scope", "scope"), + ("operation", "operation"), + ("task-grant-missing", "task-grant-missing"), + ("visibility", "visibility"), + ("task-grant-lifetime", "task-grant-lifetime"), + ("key-source-unavailable", "key-source-unavailable"), + ] { + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let request = Request::builder() + .uri(format!("/refuse/{case}")) + .header("traceparent", TRACEPARENT) + .header("authorization", "Bearer canary-credential-value") + .header("x-canary", "canary-header-value") + .body(Body::empty()) + .unwrap(); + refusal_router(Arc::clone(&recorder)) + .oneshot(request) + .with_subscriber(captured.subscriber()) + .await + .expect("an in-process request always answers"); + let exposition = refusal_exposition(&recorder); + assert!( + exposition.contains(&format!( + "scheduling_request_refusals_total{{check=\"{check}\"}} 1" + )), + "{case}: {exposition}" + ); + assert_eq!( + exposition.matches("} 1\n").count(), + 1, + "{case} counted under one check only" + ); + let lines = refusal_lines(&captured); + assert_eq!(lines.len(), 1, "{case}"); + assert_eq!(lines[0]["fields"]["failed_check"], check, "{case}"); + assert_eq!(lines[0]["fields"]["decision"], "refused", "{case}"); + assert_eq!(lines[0]["fields"]["trace_id"], TRACE_ID, "{case}"); + let rendered = captured.text(); + assert!(!rendered.contains("canary"), "{case}: {rendered}"); + } + } + + #[tokio::test] + async fn a_scope_refusal_names_the_settings_to_check() { + use tracing::instrument::WithSubscriber as _; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + refusal_router(recorder) + .oneshot(traced_request("GET", "/refuse/scope")) + .with_subscriber(captured.subscriber()) + .await + .unwrap(); + let lines = refusal_lines(&captured); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["remedy"], SCOPE_REMEDY); + } + + #[tokio::test] + async fn an_answer_that_is_not_a_refusal_records_nothing() { + use tracing::instrument::WithSubscriber as _; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let response = refusal_router(Arc::clone(&recorder)) + .oneshot(traced_request("GET", "/refuse/plain")) + .with_subscriber(captured.subscriber()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(!refusal_exposition(&recorder).contains("} 1\n")); + assert!(refusal_lines(&captured).is_empty()); + } + + #[tokio::test] + async fn a_flood_of_one_refusal_is_counted_in_full_and_logged_in_part() { + use tracing::instrument::WithSubscriber as _; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let router = refusal_router(Arc::clone(&recorder)); + for _ in 0..50 { + router + .clone() + .oneshot(traced_request("GET", "/refuse/token-signature")) + .with_subscriber(captured.subscriber()) + .await + .unwrap(); + } + assert!(refusal_exposition(&recorder) + .contains("scheduling_request_refusals_total{check=\"token-signature\"} 50")); + assert_eq!( + refusal_lines(&captured).len(), + registry_platform_authcommon::REFUSAL_LOG_LINES_PER_WINDOW as usize + ); + } + + #[test] + fn a_problem_code_is_a_refusal_exactly_when_it_refuses_authority() { + let refusals: Vec<_> = ProblemCode::ALL + .iter() + .filter(|problem| RefusalCode::of(**problem).is_some()) + .map(|problem| problem.code()) + .collect(); + assert_eq!( + refusals, + [ + "authentication.refused", + "grant.lifetime-too-long", + "operation.not-authorized", + "profile.not-authorized" + ] + ); + for problem in ProblemCode::ALL { + if let Some(code) = RefusalCode::of(*problem) { + assert_eq!(code.problem(), *problem); + } + } + } + #[tokio::test] async fn an_unknown_route_answers_the_pinned_problem_under_the_callers_trace() { let response = send(edge_router(), traced_request("GET", "/v1/nothing")).await; @@ -1471,11 +1810,14 @@ mod tests { let problem = authentication_problem(AuthenticationError::Unavailable); assert!(matches!( problem, - HttpError(ProblemCode::ServiceUnavailable) + HttpError { + problem: ProblemCode::ServiceUnavailable, + .. + } )); let response = REQUEST_TRACE .scope(TraceContext::server_created(), async { - problem_response(problem.0) + problem_response(problem.problem) }) .await; assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); @@ -1487,15 +1829,24 @@ mod tests { #[test] fn a_refused_credential_still_answers_a_challenge() { - for refusal in [AuthenticationError::Refused, AuthenticationError::Claims] { + for refusal in [ + AuthenticationError::Refused(FailedCheck::TokenSignature), + AuthenticationError::Claims(FailedCheck::TokenClaims), + ] { assert!(matches!( authentication_problem(refusal), - HttpError(ProblemCode::AuthenticationRefused) + HttpError { + problem: ProblemCode::AuthenticationRefused, + .. + } )); } assert!(matches!( - authentication_problem(AuthenticationError::Profile), - HttpError(ProblemCode::ProfileNotAuthorized) + authentication_problem(AuthenticationError::Profile(FailedCheck::Scope)), + HttpError { + problem: ProblemCode::ProfileNotAuthorized, + .. + } )); } @@ -1656,7 +2007,10 @@ mod tests { assert!( matches!( bounded_admission(&request), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) ), "an unbounded caller string reached the store: {request:?}" ); @@ -1672,7 +2026,10 @@ mod tests { external_references: vec![duplicate.clone(), duplicate], ..admission() }), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); } @@ -1686,7 +2043,10 @@ mod tests { // the service is down for a request only the caller can fix. assert!(matches!( bounded_reason(Some(&"r".repeat(MAXIMUM_CANCELLATION_REASON_BYTES + 1))), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); } @@ -1695,7 +2055,10 @@ mod tests { bounded_identifier("registry-update-30").expect("an authored offering reads"); assert!(matches!( bounded_identifier(&"o".repeat(65)), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); } @@ -1712,7 +2075,10 @@ mod tests { Some(registry_scheduling_core::MAXIMUM_BOOKING_DURATION_MINUTES + 1), None ), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); } @@ -1726,20 +2092,32 @@ mod tests { fn the_idempotency_key_is_present_bounded_and_graphical() { assert!(matches!( idempotency_key(&HeaderMap::new()), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); assert!(matches!( idempotency_key(&headers_with(IDEMPOTENCY_KEY_HEADER, "")), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); assert!(matches!( idempotency_key(&headers_with(IDEMPOTENCY_KEY_HEADER, "a key with spaces")), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); let oversized = "k".repeat(MAXIMUM_IDEMPOTENCY_KEY_BYTES + 1); assert!(matches!( idempotency_key(&headers_with(IDEMPOTENCY_KEY_HEADER, &oversized)), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); assert_eq!( idempotency_key(&headers_with(IDEMPOTENCY_KEY_HEADER, "hold-7")).unwrap(), @@ -1764,11 +2142,17 @@ mod tests { ); assert!(matches!( bearer_token(&headers_with(AUTHORIZATION, "Basic dXNlcjpwYXNz")), - Err(HttpError(ProblemCode::AuthenticationRefused)) + Err(HttpError { + problem: ProblemCode::AuthenticationRefused, + .. + }) )); assert!(matches!( bearer_token(&HeaderMap::new()), - Err(HttpError(ProblemCode::AuthenticationRefused)) + Err(HttpError { + problem: ProblemCode::AuthenticationRefused, + .. + }) )); } } diff --git a/crates/registry-scheduling/src/metrics.rs b/crates/registry-scheduling/src/metrics.rs index f2d16bffd1..a3d5b17b78 100644 --- a/crates/registry-scheduling/src/metrics.rs +++ b/crates/registry-scheduling/src/metrics.rs @@ -13,6 +13,10 @@ //! runtime's own loops. Paths, appointment or hold identifiers, principals, //! and problem details never become labels. //! +//! The refusal counter, `scheduling_request_refusals_total`, is labelled by +//! the check a request failed. The check is a closed set of 45 names, never a +//! value a caller sent. +//! //! The outbox and hook-delivery series are gauges sampled from the store when //! the metrics are scraped. When a queue cannot be read its gauges have no //! samples for that scrape, so the series goes stale rather than reporting an @@ -36,6 +40,7 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{Method, Request, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -124,6 +129,9 @@ impl SampledQueue { pub struct Metrics { requests: CounterVec, sample_failures: CounterVec, + /// The recorder the HTTP edge reports each refusal to. Its counter is + /// written into the exposition when one is attached. + refusals: Option>, started: Instant, /// Seconds after `started` at which each worker last completed a pass. last_success: [AtomicU64; 2], @@ -156,6 +164,7 @@ impl Default for Metrics { LabelSpace::closed_zero_filled(&["queue"], &queues).expect(DECLARATION), ) .expect(DECLARATION), + refusals: None, started: Instant::now(), last_success: [AtomicU64::new(0), AtomicU64::new(0)], } @@ -171,6 +180,14 @@ pub struct Sampled { } impl Metrics { + /// Expose `scheduling_request_refusals_total`, the counter of `refusals`, + /// beside the other series. + #[must_use] + pub fn with_refusals(mut self, refusals: Arc) -> Self { + self.refusals = Some(refusals); + self + } + /// Count one answered request under its closed labels. pub fn record_request(&self, route: &str, method: &Method, status: StatusCode) { count( @@ -204,6 +221,9 @@ impl Metrics { let mut out = Exposition::new(); self.requests.write(&mut out).expect(DECLARATION); self.sample_failures.write(&mut out).expect(DECLARATION); + if let Some(refusals) = &self.refusals { + refusals.counter().write(&mut out).expect(DECLARATION); + } write_queue( &mut out, "scheduling_outbox_items", @@ -429,6 +449,30 @@ mod tests { )); } + #[test] + fn the_refusal_counter_is_exposed_for_every_check_once_attached() { + use registry_platform_authcommon::FailedCheck; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let unattached = Metrics::default().render(&Sampled::default()); + assert!(!unattached.contains("scheduling_request_refusals_total")); + + let metrics = Metrics::default().with_refusals(Arc::clone(&recorder)); + assert!(recorder.record(FailedCheck::Scope).is_some()); + let text = metrics.render(&Sampled::default()); + assert!(text.contains("# TYPE scheduling_request_refusals_total counter")); + assert!(text.contains("scheduling_request_refusals_total{check=\"scope\"} 1")); + for check in FailedCheck::ALL { + assert!( + text.contains(&format!( + "scheduling_request_refusals_total{{check=\"{}\"}}", + check.as_str() + )), + "{} has no series", + check.as_str() + ); + } + } + #[test] fn every_status_has_its_own_bounded_class() { let class = |code: u16| status_class(StatusCode::from_u16(code).unwrap()); diff --git a/crates/registry-scheduling/src/runtime.rs b/crates/registry-scheduling/src/runtime.rs index cebc632ba3..a6ddf19600 100644 --- a/crates/registry-scheduling/src/runtime.rs +++ b/crates/registry-scheduling/src/runtime.rs @@ -301,7 +301,7 @@ pub async fn serve_from_path(path: impl AsRef) -> Result<(), RuntimeError> let (worker_stopped, worker_stops) = mpsc::channel(WORKER_STOP_CAPACITY); let mut workers = Vec::new(); - let metrics = Arc::new(Metrics::default()); + let metrics = Arc::new(Metrics::default().with_refusals(Arc::clone(authenticator.refusals()))); let expiry_store = store.clone(); let expiry_metrics = Arc::clone(&metrics); diff --git a/crates/registry-scheduling/src/service.rs b/crates/registry-scheduling/src/service.rs index 18e37d28d5..6e0a2447cc 100644 --- a/crates/registry-scheduling/src/service.rs +++ b/crates/registry-scheduling/src/service.rs @@ -19,6 +19,7 @@ use chrono::{DateTime, TimeDelta, Utc}; use registry_platform_audit::{ AuditKeyHasher, AuditRequest, AuthorizationAuditEvent, AuthorizationOutcome, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_calendar::CalendarInterval; use registry_platform_canonical_json::canonicalize_json; use registry_platform_oidc::{ @@ -165,16 +166,78 @@ pub enum CommitmentAnswer { Replay { status_code: u16, receipt: Value }, } +/// The problem codes that refuse a caller's authority. A refusal is built +/// with the check it failed (`ServiceError::Refused`), never from the bare +/// code, so the operator's counter and log line can name the check. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RefusalCode { + AuthenticationRefused, + GrantLifetimeTooLong, + OperationNotAuthorized, + ProfileNotAuthorized, +} + +impl RefusalCode { + /// The problem this refusal answers with. + #[must_use] + pub const fn problem(self) -> ProblemCode { + match self { + Self::AuthenticationRefused => ProblemCode::AuthenticationRefused, + Self::GrantLifetimeTooLong => ProblemCode::GrantLifetimeTooLong, + Self::OperationNotAuthorized => ProblemCode::OperationNotAuthorized, + Self::ProfileNotAuthorized => ProblemCode::ProfileNotAuthorized, + } + } + + /// Sort a problem into a refusal or a plain answer. Every code outside the + /// four refusals is plain. The vocabulary test in `http.rs` pins the set, + /// so a code added to the vocabulary that refuses authority fails it until + /// it is listed here. + #[must_use] + pub const fn of(problem: ProblemCode) -> Option { + match problem { + ProblemCode::AuthenticationRefused => Some(Self::AuthenticationRefused), + ProblemCode::GrantLifetimeTooLong => Some(Self::GrantLifetimeTooLong), + ProblemCode::OperationNotAuthorized => Some(Self::OperationNotAuthorized), + ProblemCode::ProfileNotAuthorized => Some(Self::ProfileNotAuthorized), + _ => None, + } + } +} + #[derive(Debug, thiserror::Error)] pub enum ServiceError { - /// The refusal the caller sees, in its public projection. Every service - /// failure, internal bound, and cursor verdict lands here too: the edge - /// renders one problem shape. - #[error("the request was refused: {}", .0.code())] + /// The answer the caller sees, in its public projection, for every + /// service failure, internal bound, and cursor verdict that is not a + /// refusal of authority: the edge renders one problem shape. A code for + /// which `RefusalCode::of` answers `Some` is built as `Refused`. + #[error("the request was answered: {}", .0.code())] Problem(ProblemCode), + /// A refusal of authority, with the check it failed. + #[error("the request was refused: {}", .code.problem().code())] + Refused { + code: RefusalCode, + check: FailedCheck, + }, } impl ServiceError { + /// The refusal that conceals a target the caller may not see: the row is + /// absent or foreign, and the answer does not say which. + fn not_visible() -> Self { + Self::Refused { + code: RefusalCode::OperationNotAuthorized, + check: FailedCheck::Visibility, + } + } + + fn operation_refused(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::OperationNotAuthorized, + check, + } + } + fn internal(reason: &'static str) -> Self { tracing::error!(reason, "the Scheduling service hit an internal bound"); Self::Problem(ProblemCode::ServiceUnavailable) @@ -1103,7 +1166,7 @@ impl SchedulingService { let hold = self .hold(hold_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.claim_offering(&hold, now).await?; let grant = self .require_permission(caller, &offering, HOLD_RELEASE_ACTION) @@ -1193,7 +1256,7 @@ impl SchedulingService { let hold = self .hold(hold_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.policy.offering(&hold.offering).ok_or_else(|| { ServiceError::internal("a committed hold names no offering in the policy") })?; @@ -1566,7 +1629,7 @@ impl SchedulingService { let claim = self .booking(appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; match claim.source_manager.as_ref() { None if admission == DetailAdmission::ReadsScope && claim.is_owned_by(&caller.issuer, &caller.subject) => {} @@ -1578,7 +1641,7 @@ impl SchedulingService { self.require_current_task_grant(caller, &grant, APPOINTMENT_READ_ACTION, now, true) .await?; } - None => return Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)), + None => return Err(ServiceError::not_visible()), Some(expected) => { let offering = self.claim_offering(&claim, now).await?; let grant = self @@ -1784,7 +1847,7 @@ impl SchedulingService { let appointment = self .booking(appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.policy.offering(&appointment.offering).ok_or_else(|| { ServiceError::internal("a committed appointment names no offering in the policy") })?; @@ -1914,7 +1977,7 @@ impl SchedulingService { let appointment = self .booking(appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.claim_offering(&appointment, now).await?; let grant = self .require_permission(caller, &offering, ATTENDANCE_RECORD_ACTION) @@ -1992,7 +2055,7 @@ impl SchedulingService { let appointment = self .booking(appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.claim_offering(&appointment, now).await?; let grant = self .require_permission(caller, &offering, APPOINTMENT_CANCEL_ACTION) @@ -2079,7 +2142,7 @@ impl SchedulingService { let limit = page_limit(limit); self.owned_booking(caller, appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let context = format!("history:{appointment_id}"); let position = self.resolve_position(cursor, &context, now).await?; let before = match position { @@ -2307,7 +2370,9 @@ impl SchedulingService { grantless_refusal_record(&self.hasher, &self.scheduling_id, caller, action), ) .await?; - return Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)); + return Err(ServiceError::operation_refused( + FailedCheck::TaskGrantMissing, + )); }; let allowed = grant .bounds() @@ -2338,7 +2403,7 @@ impl SchedulingService { ), ) .await?; - Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)) + Err(ServiceError::operation_refused(FailedCheck::TaskGrantScope)) } } @@ -2380,7 +2445,7 @@ impl SchedulingService { ), ) .await?; - Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)) + Err(ServiceError::operation_refused(FailedCheck::Ownership)) } /// Write one refusal, or one commitment nothing decided, as the @@ -2448,13 +2513,24 @@ impl SchedulingService { ), ) .await?; - Err(ServiceError::Problem( - if refused == GrantVerdict::LifetimeTooLong { - ProblemCode::GrantLifetimeTooLong - } else { - ProblemCode::OperationNotAuthorized - }, - )) + Err(if refused == GrantVerdict::LifetimeTooLong { + ServiceError::Refused { + code: RefusalCode::GrantLifetimeTooLong, + check: FailedCheck::TaskGrantLifetime, + } + } else { + // A deployment that asks a status authority, or one that + // listed none for an operation that needs a current + // status, refuses on status. The offline path refuses an + // expired grant. + ServiceError::operation_refused( + if online_required || self.task_grant_status.is_some() { + FailedCheck::TaskGrantStatus + } else { + FailedCheck::TaskGrantExpired + }, + ) + }) } GrantVerdict::Unavailable => { tracing::warn!("the task-grant authority could not establish current status"); @@ -2936,7 +3012,24 @@ impl SchedulingService { .map(|record| unfinished_record(record, reason)), }; self.record_refusal(correlation, record).await?; - Err(ServiceError::Problem(problem)) + Err(match RefusalCode::of(problem) { + // `CommitError::Unauthorized` is the only commit failure + // that refuses authority: the transaction found the grant + // lapsed, or the target not managed by this caller. A + // grant still current at this request's time was not the + // cause. + Some(code) => ServiceError::Refused { + code, + check: if u64::try_from(now.timestamp()) + .map_or(true, |observed| observed >= grant.exp()) + { + FailedCheck::TaskGrantExpired + } else { + FailedCheck::Ownership + }, + }, + None => ServiceError::Problem(problem), + }) } } } diff --git a/crates/registry-scheduling/src/source_busy.rs b/crates/registry-scheduling/src/source_busy.rs index 0c68cc8e00..488ab9f85d 100644 --- a/crates/registry-scheduling/src/source_busy.rs +++ b/crates/registry-scheduling/src/source_busy.rs @@ -13,6 +13,7 @@ use std::collections::{BTreeMap, BTreeSet}; use chrono::{DateTime, TimeDelta, Utc}; use registry_platform_audit::AuditKeyHasher; +use registry_platform_authcommon::FailedCheck; use registry_platform_canonical_json::canonicalize_json; use registry_scheduling_core::{valid_identifier, MAXIMUM_HORIZON_DAYS}; pub use registry_scheduling_core::{ @@ -209,6 +210,21 @@ impl std::fmt::Debug for AuthorizedBusySource { pub enum BusyAuthorizationError { #[error("the busy import profile is invalid or not authorized")] Profile, + /// The caller is not admitted by the profile it selected, for the check + /// it carries. + #[error("the caller is not admitted by a busy import profile")] + NotAdmitted(FailedCheck), +} + +impl BusyAuthorizationError { + /// The check an operator sees when this refusal answers a request. + #[must_use] + pub fn failed_check(self) -> FailedCheck { + match self { + Self::Profile => FailedCheck::AccessProfile, + Self::NotAdmitted(check) => check, + } + } } /// Validate all source profiles together. Source ids are unique. Profiles may @@ -259,13 +275,21 @@ pub fn authorize_busy_source( identity: BusySourceIdentity, ) -> Result { let (profile_id, profile) = match profile_selector { - Some(profile_id) => profiles - .get_key_value(profile_id) - .ok_or(BusyAuthorizationError::Profile)?, - None => return Err(BusyAuthorizationError::Profile), + Some(profile_id) => { + profiles + .get_key_value(profile_id) + .ok_or(BusyAuthorizationError::NotAdmitted( + FailedCheck::AccessProfile, + ))? + } + None => { + return Err(BusyAuthorizationError::NotAdmitted( + FailedCheck::AccessProfile, + )) + } }; if !scopes.iter().any(|scope| scope == &profile.scope) { - return Err(BusyAuthorizationError::Profile); + return Err(BusyAuthorizationError::NotAdmitted(FailedCheck::Scope)); } let profile_value = serde_json::to_value((profile_id, profile)).map_err(|_| BusyAuthorizationError::Profile)?; @@ -520,7 +544,9 @@ mod tests { None, identity(), ), - Err(BusyAuthorizationError::Profile) + Err(BusyAuthorizationError::NotAdmitted( + FailedCheck::AccessProfile + )) ); let authorized = authorize_busy_source( &values, diff --git a/crates/registry-scheduling/tests/golden/refusal-answers.json b/crates/registry-scheduling/tests/golden/refusal-answers.json new file mode 100644 index 0000000000..09f1f9b31e --- /dev/null +++ b/crates/registry-scheduling/tests/golden/refusal-answers.json @@ -0,0 +1,128 @@ +{ + "credential-malformed": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-scheduling/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Bearer" + }, + "credential-missing": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-scheduling/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Bearer" + }, + "key-source-unavailable": { + "body": { + "code": "service.unavailable", + "detail": "Scheduling storage is unavailable. Try again after the service recovers.", + "status": 503, + "title": "Scheduling service unavailable", + "type": "https://id.registrystack.org/problems/registry-scheduling/service/unavailable" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": "5", + "status": 503, + "wwwAuthenticate": null + }, + "operation": { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Scheduling profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-scheduling/profile/not-authorized" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + }, + "scope": { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Scheduling profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-scheduling/profile/not-authorized" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + }, + "task-grant-lifetime": { + "body": { + "code": "grant.lifetime-too-long", + "detail": "The task grant has more than 900 seconds left before it expires. Present a task grant that expires within 900 seconds.", + "status": 403, + "title": "Task grant lifetime too long", + "type": "https://id.registrystack.org/problems/registry-scheduling/grant/lifetime-too-long" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + }, + "task-grant-missing": { + "body": { + "code": "operation.not-authorized", + "detail": "Your current Scheduling authority does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-scheduling/operation/not-authorized" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + }, + "token-signature": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-scheduling/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Bearer" + }, + "visibility": { + "body": { + "code": "operation.not-authorized", + "detail": "Your current Scheduling authority does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-scheduling/operation/not-authorized" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + } +} diff --git a/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs b/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs index 83e6c87a57..4f358fea0c 100644 --- a/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs +++ b/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs @@ -279,14 +279,153 @@ async fn header_refusals_on_detail_busy_and_operational_routes_log_one_value_fre .expect("an in-process request always answers"); assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{uri}"); let rendered = captured.text(); - let diagnostics = rendered - .lines() - .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) - .filter(|event| event["fields"]["message"] == "Scheduling authentication refused") - .collect::>(); + let diagnostics = refusal_lines(&rendered); assert_eq!(diagnostics.len(), 1, "{uri}"); - assert_eq!(diagnostics[0]["fields"]["stage"], "header", "{uri}"); + // Another scheme is a credential this route does not take. + assert_eq!( + diagnostics[0]["fields"]["failed_check"], "credential-missing", + "{uri}" + ); assert!(!rendered.contains("canary"), "{uri}"); assert!(!rendered.contains("Basic"), "{uri}"); } } + +/// The refusal lines of one captured run: the one fixed message the HTTP +/// edge writes for every refusal. +fn refusal_lines(rendered: &str) -> Vec { + rendered + .lines() + .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) + .filter(|event| event["fields"]["message"] == "request refused") + .collect() +} + +/// A refusal decided inside the service names the check that refused, in +/// the operator's log line and nowhere in the answer: the same 403 answers a +/// hold that does not exist and a hold the caller holds no task grant for. +#[tokio::test] +async fn service_refusals_log_the_check_that_refused_and_answer_alike() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let slot = first_slot(&fx, OFFERING, 300, 440).await; + let (status, hold) = fx + .post( + "/v1/holds", + &fx.agent, + "hold-for-refusal-checks", + admission(&fx, OFFERING, slot), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{hold}"); + let hold_id = hold["holdId"].as_str().unwrap().to_owned(); + + let mut answers = Vec::new(); + for (uri, expected) in [ + (format!("/v1/holds/{}", Uuid::new_v4()), "visibility"), + (format!("/v1/holds/{hold_id}"), "task-grant-missing"), + ] { + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .delete(&uri, &fx.reader) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{uri}"); + assert_eq!(answer["code"], "operation.not-authorized", "{uri}"); + let rendered = captured.text(); + let lines = refusal_lines(&rendered); + assert_eq!(lines.len(), 1, "{uri}: {rendered}"); + assert_eq!(lines[0]["fields"]["failed_check"], expected, "{uri}"); + assert!(!rendered.contains(&hold_id), "{uri}"); + let mut answer = answer; + answer + .as_object_mut() + .expect("a problem body") + .remove("traceId"); + answers.push(answer); + } + assert_eq!( + answers[0], answers[1], + "the check never reaches the caller: a missing and an unreachable hold answer alike" + ); +} + +/// The check a foreign caller's refusal names says why it was refused: a +/// reschedule, a cancellation, and a release of another caller's target are +/// ownership refusals, and a read it holds no grant action for is a grant +/// scope refusal. The answers are the same 403 `operation.not-authorized`. +#[tokio::test] +async fn a_foreign_callers_refusals_name_ownership_and_grant_scope() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let slot = first_slot(&fx, OFFERING, 300, 440).await; + let (status, created) = fx + .post( + "/v1/appointments", + &fx.agent, + "foreign-checks-appointment", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{created}"); + let appointment_id = created["appointmentId"].as_str().unwrap().to_owned(); + let held = first_slot(&fx, OFFERING, 480, 620).await; + let (status, hold) = fx + .post( + "/v1/holds", + &fx.agent, + "foreign-checks-hold", + admission(&fx, OFFERING, held), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{hold}"); + let hold_id = hold["holdId"].as_str().unwrap().to_owned(); + let stranger = agent_token_for("principal-stranger"); + let other = first_slot(&fx, OFFERING, 640, 700).await; + for (method, uri, key, body, expected) in [ + ( + "POST", + format!("/v1/appointments/{appointment_id}/reschedule"), + Some("foreign-checks-reschedule"), + Some(json!({"observedRevision": 0, "admission": admission(&fx, OFFERING, other)})), + "ownership", + ), + ( + "POST", + format!("/v1/appointments/{appointment_id}/cancel"), + Some("foreign-checks-cancel"), + Some(json!({"observedRevision": 0, "reason": null})), + "ownership", + ), + ( + "DELETE", + format!("/v1/holds/{hold_id}"), + None, + None, + "ownership", + ), + ( + "GET", + format!("/v1/appointments/{appointment_id}"), + None, + None, + "task-grant-scope", + ), + ] { + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .request(method, &uri, &stranger, key, body) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{method} {uri}"); + assert_eq!(answer["code"], "operation.not-authorized", "{method} {uri}"); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1, "{method} {uri}"); + assert_eq!( + lines[0]["fields"]["failed_check"], expected, + "{method} {uri}" + ); + } +} diff --git a/crates/registry-scheduling/tests/token_characterisation.rs b/crates/registry-scheduling/tests/token_characterisation.rs index 75491bcd74..9e1818d371 100644 --- a/crates/registry-scheduling/tests/token_characterisation.rs +++ b/crates/registry-scheduling/tests/token_characterisation.rs @@ -20,6 +20,7 @@ use std::fs; use std::os::unix::fs::PermissionsExt as _; use std::path::{Path, PathBuf}; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::write_package; use registry_platform_oidc::TokenVerifier; use registry_platform_testing::{ @@ -151,22 +152,43 @@ async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { let token = case.token.expose(); match authenticator.authenticate_read(token).await { Ok(caller) => Outcome::Admitted(Some(caller.actor_kind)), - Err(AuthenticationError::Claims) => refusal("claims"), + Err(AuthenticationError::Claims(_)) => refusal("claims"), Err(AuthenticationError::Unavailable) => refusal("unavailable"), - Err(error @ (AuthenticationError::Refused | AuthenticationError::Profile)) => { + Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { let reference = TokenVerifier::new(verifier, keys); match reference.verify(token).await { - Err(failure) => refusal(failure.authentication_stage().label()), - Ok(verified) if error == AuthenticationError::Profile => { + Err(failure) => { + // The refusal records the shared verifier's own check, or + // the malformed credential the compact-token admission + // refuses before the verifier runs. + assert!( + matches!( + error, + AuthenticationError::Refused(check) + if check == failure.failed_check() + || check == FailedCheck::CredentialMalformed + ), + "{error:?} does not carry the verifier check" + ); + refusal(failure.authentication_stage().label()) + } + Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { if verified.scopes.iter().any(|held| held == &scope) { refusal("profile") } else { + assert_eq!(error, AuthenticationError::Profile(FailedCheck::Scope)); refusal("scope") } } // The credential is not a compact access token, so the // verifier is never reached. - Ok(_) => refusal("header"), + Ok(_) => { + assert_eq!( + error, + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); + refusal("header") + } } } } diff --git a/docs/site/src/content/docs/operate/breg-monitor.mdx b/docs/site/src/content/docs/operate/breg-monitor.mdx index fd3fbc9f7e..fe3a18029f 100644 --- a/docs/site/src/content/docs/operate/breg-monitor.mdx +++ b/docs/site/src/content/docs/operate/breg-monitor.mdx @@ -343,7 +343,10 @@ with one of the `breg.external-refresh.*` codes in [Troubleshooting](#troublesho `breg_request_refusals_total{check}` counts every request BReg refused, by the check that refused it, since the process started. Every `check` value is published from the first scrape at zero, so a rate needs no `absent()` guard. A missing or refused credential, a refused token, an unreachable -key source and a refused review completion callback all count. +key source and a refused review completion callback all count. So does a request answered +`404 resource.not_found` because the caller may not see the target (a missing scope or purpose, a +row outside the caller's boundary, a refused task grant, a field beyond the profile), and a write +refused as outside the caller's boundary. Each refusal also writes one `request refused` line with `failed_check` and the request's trace id, at most five lines per check per minute across the process. The next line for that check carries @@ -360,6 +363,8 @@ keys; check the issuer before the callers. the_refusal_counter_declares_every_check_and_publishes_it_at_zero; crates/registry-breg/tests/authentication_refusals.rs, every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wire; + crates/registry-breg/tests/concealment_refusals.rs, + every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wire; crates/registry-platform-authcommon/src/refusal.rs, the recorder's per-check window. */} ## Read audit records diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index 965978a857..3cdce92c39 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -354,7 +354,8 @@ Dead-lettered and expired deliveries do not set it, because they stay counted un `casework_request_refusals_total` counts every request the API listener refused, by the check that refused it, since the process started: a missing or refused credential or token, an unreachable -key source, a refused delegated reviewer, and a review the caller may not act on or see. Each +key source, a refused delegated reviewer, and a review, directory, clock or task-grant request the +caller may not act on or see. Each refusal also writes one `request refused` line with `failed_check` and the request's trace id, at most five lines per check per minute across the process. The next line for that check carries `suppressed`, the number the minute counted but did not log, so alert on the counter, not the log. diff --git a/docs/site/src/content/docs/operate/documents.mdx b/docs/site/src/content/docs/operate/documents.mdx index 0b9edc31f8..23d221a11f 100644 --- a/docs/site/src/content/docs/operate/documents.mdx +++ b/docs/site/src/content/docs/operate/documents.mdx @@ -180,8 +180,11 @@ authentication: ``` The secret holds a JSON Web Key Set of RSA or EC public keys, and every key needs its own non-empty -`kid`: startup refuses a key without one, a repeated `kid`, and a symmetric key. The set is read -once at startup and never rotates, so to change keys, replace the secret and restart `serve`. +`kid`: startup refuses a key without one, a repeated `kid`, and a symmetric key. It also refuses a +key that carries a private member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth` or `k`) or a repeated +member name, and the startup error names the rule and the key's position, never a key value. Members +the runtime does not know, such as `x5c`, `x5t` or `ext`, are ignored. The set is read once at +startup and never rotates, so to change keys, replace the secret and restart `serve`. {/* Evidence: products/documents/generated/runtime/runtime.schema.json; crates/registry-documents/src/config.rs, verifier_profile and DOCUMENTS_ACCESS_TOKEN_TYPE; @@ -189,6 +192,10 @@ once at startup and never rotates, so to change keys, replace the secret and res crates/registry-documents-core/src/access.rs, AccessProfiles::resolve; crates/registry-platform-oidc/src/lib.rs, verify_access_token, match_client, and parse_static_jwks; + crates/registry-platform-oidc/src/static_jwks.rs, StaticJwksError, PrivateKeyMember; + crates/registry-documents/src/config.rs, parse_static_key_set, + a_static_key_set_that_holds_a_private_member_is_refused_by_rule_and_not_by_value, + a_static_key_set_with_unknown_public_members_loads; crates/registry-platform-oidc/src/authorization_claims.rs, ClaimNames (registry_actor_kind). */} ## Create the secret files @@ -608,6 +615,7 @@ answers the series below and nothing else. The document listener does not route | `documents_hook_oldest_overdue_age_seconds` | none | Gauge of how many seconds the oldest pending hook delivery is past its due time. Zero when none is overdue | | `documents_worker_last_success_age_seconds` | `worker`: `cleanup` | Gauge of seconds since the cleanup pass last finished without leaving an orphaned object unconfirmed | | `documents_metrics_sample_failures_total` | `sample`: `verification-jobs`, `erasure-jobs`, `hook-deliveries` | Scrapes in which that queue could not be read | +| `documents_request_refusals_total` | `check`: the closed set of 45 failed checks, every value published at zero | Requests refused, by the check that failed. Each refusal also writes one `request refused` log line with `failed_check`, at most five per check per minute, with `suppressed` counting what a window held back. Neither carries a token, claim, client, subject or identifier | Every state is listed, with a zero when no row is in it. Watch the `dead-lettered` state of each gauge, the work that gave up and needs a person. Replay a verification or erasure job as diff --git a/docs/site/src/content/docs/operate/registry-render.mdx b/docs/site/src/content/docs/operate/registry-render.mdx index f15d991b7e..aa17122b93 100644 --- a/docs/site/src/content/docs/operate/registry-render.mdx +++ b/docs/site/src/content/docs/operate/registry-render.mdx @@ -706,6 +706,7 @@ The metrics listener has no authentication, so keep it on a private network that | Series | Labels | Meaning | | --- | --- | --- | | `render_documents_total` | `operation`: `render`, `seal`. `result`: `ok`, `refused`, `failed` | Calls to the render and seal routes. `ok` is a 2xx answer, `refused` a 4xx answer, and `failed` a 5xx answer | +| `render_request_refusals_total` | `check`: one fixed check name per refusal reason, for example `credential-missing`, `token-audience`, `scope`, `requester-client` | Requests refused to a caller, by the check that failed. Every check starts at zero. Each refusal also writes one `request refused` log line with `failed_check`, at most five per check per minute | | `render_audit_write_failures_total` | none | Audit entries that could not be written | | `render_seal_certificate_expiry_seconds` | `seal`: each seal id from your `signing.seals` | Gauge of seconds until the seal's certificate stops being valid. Negative once it has | diff --git a/docs/site/src/content/docs/operate/stuck-work.mdx b/docs/site/src/content/docs/operate/stuck-work.mdx index f1f85a8b2c..56e2d9db50 100644 --- a/docs/site/src/content/docs/operate/stuck-work.mdx +++ b/docs/site/src/content/docs/operate/stuck-work.mdx @@ -122,6 +122,7 @@ The signals show a failing dependency instead. Outcomes other than `success` are failures, for example `timeout`, `transport`, `credential`, and `rate-limited`. - `evidence_signer_requests_total{signer,outcome}` does the same for the signer. - `evidence_source_shape_drift_total{source}` rises when a source starts answering in a shape the bundle does not describe. +- `evidence_request_refusals_total{check}` counts requests refused with `401`, `403` or `429`, by the check that failed. A rise under `key-source-unavailable` means the issuer's key set cannot be reached. - `evidence_rate_limiter_tracked_keys` rises toward its ceiling of 100,000 keys. - With OID4VCI enabled, `evidence_oid4vci_store_entries` approaches `evidence_oid4vci_store_capacity`, and `evidence_oid4vci_outcomes_total{outcome}` counts `store-saturated` and `store-fault`. - `evidencectl doctor --runtime-config` is a preflight of the runtime file and, with `--require-audit-under`, of the audit path. @@ -138,7 +139,7 @@ Use the metrics. **Read more.** [Preflight the audit path](../evidence-audit/), [OID4VCI metrics](../../configure/evidence-oid4vci/#metrics). {/* Evidence: crates/registry-evidence/src/observability/golden-scrape.txt; - crates/registry-evidence/src/observability.rs, evidence_source_shape_drift_total; + crates/registry-evidence/src/observability.rs, evidence_source_shape_drift_total and evidence_request_refusals_total; crates/registry-evidence-oid4vci/src/observability.rs, evidence_oid4vci_store_capacity; crates/registry-evidencectl/src/runtime.rs, DoctorArgs. */} @@ -340,6 +341,7 @@ Readiness also fails when the audit writer has stopped. Render can also publish metrics on an optional `metricsListener`, which is off by default and must bind a private address. - `render_documents_total{operation,result}` counts calls, with `operation` of `render` or `seal` and `result` of `ok`, `refused`, or `failed`. +- `render_request_refusals_total{check}` counts requests refused to a caller, by the check that failed. - `render_audit_write_failures_total` counts failed audit writes. - `render_seal_certificate_expiry_seconds{seal}` is the time until each seal certificate stops being valid, negative once it has. diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 4763acfe75..f360ff04c2 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -160,6 +160,19 @@ A request batch audits both items as not available, and the metric still counts declared_existence_disclosure_mode_governs_the_public_collapse, a_declared_unresolved_problem_logs_a_cause_only_when_a_404_does_not_match_it. */} +A request that BReg answers `404 resource.not_found` because the caller may not see the target reads the same to the caller whatever the reason. +The operator can tell the reasons apart. +`breg_request_refusals_total{check}` counts the request under the rule that refused it, for example `scope`, `purpose`, `requester-client`, `row-boundary`, `task-grant-binding`, `disclosure` or `visibility`, and one `request refused` line names the same `failed_check`. +A refused write the engine answers with `write.outside-boundary` counts under `row-boundary`, and a Proposal outside the caller's scope counts under `ownership`. +The counter and the line carry only that fixed name, never a token, claim, client, subject, route parameter or record identifier, and they change nothing the caller receives. +A `visibility` count is a record that is absent or outside the boundary, and BReg does not say which, so it also counts a caller probing for identifiers. +The audit journal's `refusalReason` stays the three values it lists below. + +{/* Evidence: crates/registry-breg/tests/concealment_refusals.rs, + every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wire; + crates/registry-breg/src/api/mod.rs, concealed(), refusal_check_tests; + crates/registry-breg/src/mutation.rs, MutationError::failed_check. */} + ### Public check export `bregctl generate evidence-source --public-check` exports the Source of an Evidence [public check](../evidence/#the-public-certificate-check). diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index ece9cc49f1..70832cf93b 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -162,6 +162,20 @@ grants in [Registry Casework task grants](../../reference/casework-task-grants/) separate_human_source_credentials_bind_before_empty_inbox_and_guard_mutations; crates/registry-casework/src/http/source_credentials.rs, verified_provider_handles_do_not_forward_casework_or_mix_invocations. */} +- Refusals the caller cannot tell apart are told apart in the operator's counter. A review or + administration request refused for its role, its profile's stage eligibility, an earlier + decision by the same person (separation of duties), a task the caller does not hold, a task + grant that is expired, invalidated or bound to another client, or a source that declines to + disclose, counts once under its own check in `casework_request_refusals_total` + ([metrics](../../operate/casework/#scrape-metrics-and-the-running-version)). + A target concealed as not found counts under `visibility`, or under the check that hid it. + The caller's answer is the same `operation.not-authorized` or `request.not-found` body as + before, so the counter is for the operator and tells the caller nothing. + {/* Evidence: crates/registry-casework/src/http.rs, impl From for HttpError; + crates/registry-casework/src/review.rs, + a_reviewer_who_already_acted_is_refused_for_separation_of_duties, + only_staff_and_supervisors_pass_the_human_reviewer_check; + crates/registry-casework/tests/refusal_golden.rs. */} ## Operator obligations diff --git a/docs/site/src/content/docs/security/documents.mdx b/docs/site/src/content/docs/security/documents.mdx index 6723290175..30e11a01c9 100644 --- a/docs/site/src/content/docs/security/documents.mdx +++ b/docs/site/src/content/docs/security/documents.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -31,6 +31,27 @@ and the restore drill is in An unreachable key set answers 503, never 401. The deployment trusts one issuer; `allowedClients: unrestricted` is refused. Declared issuer and key addresses are trusted on the operator's word (DOCUMENTS-RES-17). + A static key set (`jwksSource: static`) holds public keys only. + The runtime refuses to start on a set that carries a private member (`d`, `p`, `q`, `dp`, `dq`, + `qi`, `oth` or `k`), a symmetric key, a repeated member name, or a key without a unique `kid`. + The startup error names the rule and the key's position, never a key value. + Members it does not know, such as `x5c` or `ext`, are ignored. +- The operator's view of a refusal: the answer to the caller names a problem code and no cause, so + an operator tells the causes apart from the private metrics listener and the log. + Every refused request is counted in `documents_request_refusals_total{check}`. + The `check` label is a closed set of 45 names such as `credential-missing`, `token-signature`, + `scope`, `actor-kind`, `access-profile`, `operation`, `ownership` and `visibility`, every one + published at zero, and no caller value becomes a label. + The counter covers a missing or refused credential, a token that resolves to no access profile, a + refused custody placement, a caller that sees a document but may not act on it, a document or + upload the caller may not see, and a verifier that cannot reach its key source + (`key-source-unavailable`). + Each refusal also writes one `request refused` log line that names the check. + The runtime writes at most five such lines per check per minute and reports how many it held back + in `suppressed`. + A scope refusal carries a fixed remedy that names `authentication.oidc.scopeClaim`. + Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and + recording a refusal changes nothing the caller receives. - The custodian alone removes a document and issues, lists and revokes its grants. Under citizen delivery the citizen is the custodian and the reserving system keeps metadata and status only. @@ -67,7 +88,13 @@ Findings name the member and rule, never the value. DOCUMENTS-SEC-03, DOCUMENTS-SEC-04, DOCUMENTS-SEC-05, DOCUMENTS-SEC-06, DOCUMENTS-SEC-08, DOCUMENTS-SEC-10, DOCUMENTS-SEC-11, DOCUMENTS-SEC-21, DOCUMENTS-SEC-24, DOCUMENTS-SEC-26, DOCUMENTS-SEC-32, DOCUMENTS-SEC-34, DOCUMENTS-SEC-48; - crates/registry-documents/src/http.rs ready, readiness_router; + crates/registry-documents/src/http.rs ready, readiness_router, refusal_response; + crates/registry-documents/src/metrics.rs, Metrics, count_requests, + the_refusal_counter_lists_every_check_from_zero_and_counts_by_check; + crates/registry-documents/tests/refusal_golden.rs, + every_refusal_is_counted_and_logged_under_the_check_it_failed, + every_refusal_answers_the_bytes_the_golden_file_holds; + crates/registry-platform-oidc/src/static_jwks.rs, StaticJwksError; crates/registry-documents/src/config.rs check_secret_providers, unrestricted_clients_are_refused, plaintext_database_is_refused_outside_test_builds, disabled_content_verification_requires_development_loopback, diff --git a/docs/site/src/content/docs/security/evidence.mdx b/docs/site/src/content/docs/security/evidence.mdx index d30bdfc7d0..f3c20a4592 100644 --- a/docs/site/src/content/docs/security/evidence.mdx +++ b/docs/site/src/content/docs/security/evidence.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-20" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -41,6 +41,41 @@ A failed authentication, a malformed request, an invalid selector, and a rate limit write no native audit entry, even when Evidence decides them after authorisation. Watch for them in operational logs and metrics instead. +Evidence counts every `401`, `403` and `429` answer by the check that failed, in +`evidence_request_refusals_total{check}` on the private metrics listener. The `check` label is a +closed set of 45 names such as `credential-missing`, `token-signature`, `scope`, `access-profile`, +`purpose`, `revision-pin` and `rate-limit`, and no caller value becomes a label. Each refusal also +writes one `request refused` log line that names the check and the request's trace id. The runtime +writes at most five such lines per check per minute and reports how many it held back in +`suppressed`. The counter and the line carry only a fixed check name, never a token, claim, client, +selector value or requirement. The check is operator-side only: the response a caller receives is +the same closed `401`, `403` or `429` it always was. An issuer key set that cannot be reached +still answers `401`, and counts under `key-source-unavailable`. + +{/* Evidence: crates/registry-evidence/src/observability.rs, record_refusal and Metrics::render; + crates/registry-evidence/src/refusal_recording_tests.rs, + every_refusal_is_counted_logged_once_by_its_check_and_answered_as_before; + crates/registry-evidence/tests/golden/refusal_answers.json. */} + +The wallet-facing services record every refused request the same way. Evidence OID4VCI counts each +one in `evidence_oid4vci_request_refusals_total{check}` and Evidence OID4VP in +`evidence_oid4vp_request_refusals_total{check}`, and each writes one bounded `request refused` log +line that carries only the check name. The checks cover a missing or malformed bearer credential, a +token that fails verification, a missing scope or client, an unusable single-use code or access +token, an Evidence refusal, a session read that belongs to another principal, an unknown or foreign +session status, and a spent request budget. Capacity answers, unknown routes and malformed requests +are not recorded. The answers a caller receives are unchanged. + +{/* Evidence: crates/registry-evidence-oid4vci/src/observability.rs, observe and record_refusal; + crates/registry-evidence-oid4vci/src/service.rs, unauthorized, store_response, + issuance_response and limiter_refusal; + crates/registry-evidence-oid4vci/src/authorizer.rs, AuthorizationError::Refused; + crates/registry-evidence-oid4vp/src/service.rs, record_refusals, unauthorized and admit; + crates/registry-evidence-oid4vp/src/auth.rs; + registry-evidence-oid4vci service::tests::refusal_answers_match_the_golden and + each_refusal_is_counted_and_logged_under_its_check; + crates/registry-evidence-oid4vp/tests/refusal_golden.rs and tests/refusal_recording.rs. */} + An agent acts only inside its task grant. For an institutional agent task, Evidence consumes a complete signed grant context issued by an external task authority, and accepts it only on a configured authority path whose subjects diff --git a/docs/site/src/content/docs/security/messaging.mdx b/docs/site/src/content/docs/security/messaging.mdx index 6336782308..df72d51486 100644 --- a/docs/site/src/content/docs/security/messaging.mdx +++ b/docs/site/src/content/docs/security/messaging.mdx @@ -42,8 +42,21 @@ when `assertionIssuers` declares no authority) is `403 profile.not-authorized`. A verifier that cannot reach a verdict, because the issuer's discovery document or key set cannot be fetched, read or used, is `503 service.unavailable` with `Retry-After: 5`; the credential is not what is wrong, so a caller should retry rather than rotate it. -Causes inside each status are told apart only by value-free metric reasons and rate-limited log -stage labels. +Causes inside each status are told apart only by operator-side signals, never in the response. +Every refused request is counted in `messaging_request_refusals_total{check}` on the private metrics +listener. The `check` label is a closed set of 45 names such as `token-signature`, `scope`, +`actor-kind`, `access-profile`, `delivery-signature` and `visibility`, and no caller value becomes a +label. Each refusal also writes one `request refused` log line that names the check and the +request's trace id. The runtime writes at most five such lines per check per minute and reports how +many it held back in `suppressed`. Where an operator can fix the cause in configuration, the line +carries a fixed remedy that names the setting, for example `accessProfiles` for `access-profile` or +`authentication.oidc.scopeClaim` for `scope`. A verifier that cannot reach its key source counts +under `key-source-unavailable`. +A static key set (`jwksSource: static`) holds public keys only. The runtime refuses to start on a +set that carries a private member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth` or `k`), a symmetric key, +a repeated member name, or a key without a unique `kid`, and the startup error names the rule and +the key's position, never a key value. Members it does not know, such as `x5c` or `ext`, are +ignored. A client listed in two access profiles is refused when the package loads, and a profile must state its scopes or write `unrestricted`. (MESSAGING-SEC-01, MESSAGING-SEC-04) @@ -51,7 +64,12 @@ its scopes or write `unrestricted`. {/* Evidence: products/messaging/contracts/security-invariant-matrix.yaml MESSAGING-SEC-01, MESSAGING-SEC-04; crates/registry-messaging/src/http.rs - only_the_sender_role_submits_and_only_through_what_its_profile_lists; + only_the_sender_role_submits_and_only_through_what_its_profile_lists, + each_refusal_is_counted_and_logged_under_the_check_that_failed, + each_callback_refusal_is_counted_and_logged_under_the_check_that_failed, + refusal_answers_match_the_golden_file; + crates/registry-messaging/src/config.rs + a_static_key_set_that_holds_a_private_member_is_refused_with_the_rule; crates/registry-messaging/tests/postgres_messages.rs a_message_is_visible_to_its_submitter_and_an_operator_only. */} @@ -82,6 +100,9 @@ Each is authenticated by the verifier its provider's runtime configuration names Every cause of refusal answers `403 callback.unverified`, so the route does not reveal which providers receive callbacks. It is 403 rather than 401 because a provider cannot answer a challenge. +The runtime tells the causes apart for the operator only: `delivery-binding` (a path that names no +receiving provider, or a token on the wrong route), `delivery-signature` (a missing, malformed or +wrong signature) and `shared-secret` (a missing or wrong path token). A callback changes a message only forward, and only for the message whose provider reference the accepting attempt stored, scoped to that provider. (MESSAGING-SEC-07) @@ -102,8 +123,11 @@ no `import`, `eval`, `print` or `debug`. SMTP requires `STARTTLS` or implicit TLS, verifies the certificate against the configured host name, sends no credential to a relay that does not offer `STARTTLS`, and cannot have a header line opened from template data. -Plain `http` and `development-loopback` SMTP are limited to loopback; a production listener posture -refuses plaintext SMTP at `messagingctl check` and at startup. +Plain `http` and `development-loopback` SMTP are limited to loopback, which means an address in +`127.0.0.0/8`, `::1`, an IPv4-mapped form of a `127.0.0.0/8` address, or the exact name `localhost`. +No other name is loopback, so `localhost.` and `gateway.localhost` are refused. SMTP connects only +to the loopback address it checked. +A production listener posture refuses plaintext SMTP at `messagingctl check` and at startup. (MESSAGING-SEC-03) {/* Evidence: products/messaging/contracts/security-invariant-matrix.yaml MESSAGING-SEC-03; @@ -157,6 +181,8 @@ Metric labels are closed sets fixed in code, and `MESSAGING_LOG` accepts only `e Authentication and access-profile refusals, duplicate or no-op callbacks and reads (the status route, `messagingctl messages list` and `show`) are not journaled: a refusal is counted on the private metrics listener, and a message view releases no contact, part or data. +The refusal counters and log lines carry the failed check only, so they hold no principal, client, +scope, route parameter or address. (MESSAGING-SEC-08) {/* Evidence: products/messaging/contracts/security-invariant-matrix.yaml MESSAGING-SEC-08; @@ -277,8 +303,9 @@ The boundaries hold only if your deployment does the following. it observes an original receipt. Other profiles keep the configured principal ownership rule. 9. Name `scopeClaim` explicitly if your issuer puts different scopes in `scope` and another claim. - Messaging reads exactly one claim, `scope` by default, and a scope refusal logs the configured - claim, the first missing scope and the access profile, never token contents. + Messaging reads exactly one claim, `scope` by default, and a scope refusal logs + `failed_check="scope"` with a fixed remedy that names `authentication.oidc.scopeClaim` and + `accessProfiles` `requiredScopes`, never a claim, scope or profile value. 10. Set `allowedPrivateCidrs` only for relays and providers you run, and treat `allowInsecureHttp: true` as a loopback or test setting; startup warns when it is set. With it, an attacker on the network path to the issuer can substitute keys. diff --git a/docs/site/src/content/docs/security/render.mdx b/docs/site/src/content/docs/security/render.mdx index b436c813f2..db50ddb0da 100644 --- a/docs/site/src/content/docs/security/render.mdx +++ b/docs/site/src/content/docs/security/render.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -211,6 +211,24 @@ rules only. crates/registry-render/src/pdf_signature.rs sealable_holds_pdf_a_1_2_and_3_to_their_string_length_limits. */} +## How refusals are recorded + +Render counts every refusal of a caller by the check that failed, in +`render_request_refusals_total{check}` on the private metrics listener. +It writes one `request refused` log line with `failed_check` and the request's trace id, and at +most five lines per check per minute, with `suppressed` counting what a window held back. +The counter and the line carry only a fixed check name, never a token, claim, client, scope or +route value. +The counter covers a missing or malformed credential, a legacy API key mismatch, a token the +verifier refuses, an unreachable key source, a missing scope, the legacy key presented to the seal +route, and a client that the seal's `allowedClients` does not list. +The answer a caller receives does not change. + +{/* Evidence: crates/registry-render/src/server.rs + each_refusal_is_counted_and_logged_under_its_check, + refusal_answers_match_the_golden; + crates/registry-render/tests/golden/authentication_refusals.json. */} + ## Report a vulnerability Report a suspected vulnerability through the process in diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 55aaa45563..bf8b1e882e 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -7,7 +7,17 @@ the first scrape. Each refusal writes one `request refused` line with `failed_check` and the request's trace id, at most five lines per check per minute. That line replaces the authentication refusal line that carried a - `stage` field. Refusal statuses, headers and bodies are unchanged. + `stage` field. A request answered `404 resource.not_found` because the caller + may not see the target counts under the rule that hid it, and so does a write + refused as outside the caller's boundary. Refusal statuses, headers and bodies + are unchanged. + +- The BReg MCP gateway and the review page read loopback the way every + other service does. Under `development-loopback`, plain HTTP to + `127.0.0.2`, `[::1]` or `[::ffff:127.0.0.1]` is accepted as well as + `127.0.0.1` and `localhost`. `localhost.` and `*.localhost` stay refused. A + static key set the BReg MCP gateway refuses is logged with the reason, and + its startup code is unchanged. - The Rust BReg client decodes `/health` and `/ready` answers that carry members besides `status`, and ignores them. `status` is still required and diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index 0a446dedc5..a353b475d6 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -7,7 +7,9 @@ at zero for every check. Each refusal writes one `request refused` line with `failed_check` and the request's trace id, at most five lines per check per minute. That line replaces the authentication refusal line that carried a - `stage` field. Refusal statuses, headers and bodies are unchanged. + `stage` field. The count covers review, directory, clock and task-grant + refusals, each under the check its producer names. Refusal statuses, headers + and bodies are unchanged. - A static key set with a private key member or a repeated member name is refused at startup under `casework.runtime.unreadable-jwks-secret`, with the rule it broke and the key's position, in place of diff --git a/products/documents/CHANGELOG.md b/products/documents/CHANGELOG.md index c3171fe278..3df75b2bea 100644 --- a/products/documents/CHANGELOG.md +++ b/products/documents/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- The Document Store counts every refused request by the check that refused + it, in `documents_request_refusals_total{check}` on the metrics listener, + published at zero for every check. Each refusal writes one `request refused` + line with `failed_check`, at most five lines per check per minute. That line + replaces the scope refusal line, which named the claim, the scope and the + access profile; a scope refusal now carries a fixed remedy that names + `authentication.oidc.scopeClaim`. Refusal statuses, headers and bodies are + unchanged. +- A static key set with a private key member or a repeated member name is + refused at startup, and the error names the rule it broke and the key's + position, never a key value. + - The Rust Documents client accepts a `/health` answer with an empty body or a JSON object body of at most 4096 bytes, and ignores the object's members. A larger body, or a body that is not a JSON object, is still a body protocol diff --git a/products/evidence/CHANGELOG.md b/products/evidence/CHANGELOG.md index 504ca27ea9..b803d92145 100644 --- a/products/evidence/CHANGELOG.md +++ b/products/evidence/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +- Evidence counts every `401`, `403` and `429` answer by the check that failed + in `evidence_request_refusals_total{check}` on the private metrics listener, + and writes one `request refused` log line with the check and the request's + trace id, at most five per check per minute. No response status, header or + body changes. +- Evidence OID4VCI and Evidence OID4VP count each refused request in + `evidence_oid4vci_request_refusals_total{check}` and + `evidence_oid4vp_request_refusals_total{check}`, published at zero for every + check, and log it once as `request refused` with the failed check, at most + five lines per check per minute. This bounded `INFO` line replaces the + key-source `WARN` line of both services: alert on the counter under + `key-source-unavailable` instead. Responses are unchanged. + - BREAKING (experimental surface): `evidencectl check` and `evidencectl package` refuse a `publicCheck` definition whose Source facts schema states more than types (`public-check-facts-content`). A bound, a pattern, a vocabulary or a diff --git a/products/messaging/CHANGELOG.md b/products/messaging/CHANGELOG.md index 47ba454259..ddf897035e 100644 --- a/products/messaging/CHANGELOG.md +++ b/products/messaging/CHANGELOG.md @@ -2,6 +2,25 @@ ## Unreleased +- Messaging counts every refused request by the check that refused it, in + `messaging_request_refusals_total{check}` on the metrics listener, published + at zero for every check. Each refusal writes one `request refused` line with + `failed_check` and the request's trace id, at most five lines per check per + minute. That line replaces the authentication refusal line that carried a + `stage` field, and the three callback refusal lines. The count covers + authentication, message, rate limit and callback refusals, each under the + check its producer names, and a key endpoint outage under + `key-source-unavailable`. `messaging_authentication_refusals_total{reason}` + is unchanged. Refusal statuses, headers and bodies are unchanged. +- A static key set with a private key member or a repeated member name is + refused at startup under `messaging.runtime.unreadable-jwks-secret`, with + the rule it broke, and `messagingctl` names the rule when it refuses a + borrowed owner's key set. A public member the service does not know loads. +- A plain `http` provider base URL and an SMTP relay in development use the + same loopback rule: `127.0.0.0/8`, `::1`, or an IPv4-mapped form of + `127.0.0.0/8`. The name `localhost` is accepted for a provider base URL as + before, and a name such as `relay.localhost` stays refused for SMTP. + - `authentication.oidc.allowedClients` accepts the keyword `from-package`, which admits the requester clients of the package's access profiles, so the clients are written once, in the package. The member stays required, and an diff --git a/products/messaging/contracts/security-test-traceability.yaml b/products/messaging/contracts/security-test-traceability.yaml index 51374377fc..cee5b9c9f1 100644 --- a/products/messaging/contracts/security-test-traceability.yaml +++ b/products/messaging/contracts/security-test-traceability.yaml @@ -172,7 +172,7 @@ entries: - {path: crates/registry-messaging/tests/postgres_dispatch.rs, name: no_contact_content_data_or_credential_reaches_the_dispatch_journal_or_log} - {path: crates/registry-messaging/tests/postgres_retention.rs, name: a_retention_run_is_journaled_with_its_counts_only} - {path: crates/registry-messaging/src/http.rs, name: a_preview_answers_the_bytes_the_cli_prints_and_journals_metadata_only} - - {path: crates/registry-messaging/src/auth.rs, name: compact_token_admission_logs_one_value_free_header_diagnostic} + - {path: crates/registry-messaging/src/http.rs, name: malformed_credentials_log_a_bounded_value_free_line} - {path: crates/registry-messaging/src/auth.rs, name: only_a_verifier_that_reached_no_verdict_is_unavailable} - {path: crates/registry-platform-oidc/src/lib.rs, name: oidc_max_token_lifetime_rejects_missing_or_invalid_time_bounds} - id: MESSAGING-SEC-09 diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 0d2beba581..3e6f2790cb 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -114,6 +114,17 @@ the new `OidcError::SubjectMismatch` (`token-claims`). Each of these was `InvalidToken` (`credential-malformed`) before. +- The MCP edge counts every refusal by the check that refused it and writes + one `request refused` line with `failed_check`, at most five lines per check + per minute. The edge has no metrics listener, so the line is the operator's + signal there. Refusal statuses, headers and bodies are unchanged. Gateways + built on the edge (`registry-mcp`, `registry-breg-mcp`) and the BReg review + page accept the loopback spellings of the shared definition under + `development-loopback` (for example `127.0.0.2` and `[::ffff:127.0.0.1]`), + and still refuse `localhost.` and `*.localhost`. A refused static key set + now says why: `registry-mcp` names the refusal in its startup message, and + `registry-breg-mcp` logs it, with its startup code unchanged. + ## 0.48.0 - 2026-11-23 - No user-visible product changes in this release. diff --git a/products/render/CHANGELOG.md b/products/render/CHANGELOG.md index 744c4fac1f..993402d465 100644 --- a/products/render/CHANGELOG.md +++ b/products/render/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- Render counts every refusal of a caller in `render_request_refusals_total{check}` + on the metrics listener and writes one `request refused` log line with + `failed_check` and the trace id, at most five per check per minute. The + counter and the line carry a fixed check name only. Responses are unchanged. +- A test timestamp authority may use an IPv4-mapped loopback literal in plain + `http`, such as `http://[::ffff:127.0.0.1]/tsr`, the same as `127.0.0.1`. + An IPv4-mapped address off the host, such as `[::ffff:10.0.0.5]`, stays + refused. - `registry-render test-seal` creates a test-signed PDF and its public test CA certificate from a bundle and an example record. Each run uses a fresh local development signer. diff --git a/products/scheduling/CHANGELOG.md b/products/scheduling/CHANGELOG.md index 8031d4182c..8a6f0e785d 100644 --- a/products/scheduling/CHANGELOG.md +++ b/products/scheduling/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +- Scheduling counts every refused request by the check that refused it, in + `scheduling_request_refusals_total{check}` on the metrics listener, + published at zero for every check. Each refusal writes one + `request refused` line with `failed_check` and the request's trace id, at + most five lines per check per minute. That line replaces the + authentication refusal line that carried a `stage` field. Refusal statuses, + headers and bodies are unchanged. +- A static key set with a private key member or a repeated member name is + refused at startup under `scheduling.runtime.unreadable-jwks-secret`, with + the rule it broke, in place of `scheduling.runtime-dependency.unavailable`. +- A reminder or hook destination in plain `http` accepts any loopback host by + the shared rule: an address of `127.0.0.0/8`, `::1`, an IPv4-mapped form of + `127.0.0.0/8`, or `localhost` in any case. `localhost.` and `*.localhost` + stay refused. + - Add `GET /health` and `GET /ready`, answering `{"status":"ok"}` and `{"status":"ready"}` as `application/json` with no token, as the other services do. `/healthz` and `/readyz` keep answering an empty 200. diff --git a/products/scheduling/scripts/generate_openapi.py b/products/scheduling/scripts/generate_openapi.py index e32f118c72..74368a7876 100644 --- a/products/scheduling/scripts/generate_openapi.py +++ b/products/scheduling/scripts/generate_openapi.py @@ -1866,7 +1866,7 @@ def verify_source(repository_root: Path) -> None: "pub async fn authenticate_explain", "pub async fn authenticate_mutate", "grant_claims(&verified.claims", - "Err(AuthenticationError::Profile)", + "Err(AuthenticationError::Profile(FailedCheck::Scope))", ): marker(auth_source, text, "auth") for text in ( From 389deba9ef3ae42204121bdcce0256ed8311a2f3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 06:14:07 +0100 Subject: [PATCH 035/136] feat(documents): admit the package's requester clients with allowedClients: from-package authentication.oidc.allowedClients accepts the keyword from-package, which admits exactly the requester clients of the package's access profiles, so the clients are written once, in the package. The member stays required; an omitted member, an empty list and unrestricted are still refused. An explicit list must now include every client a profile names, or startup is refused with documents.runtime.profile-client-not-allowed, where before the runtime started and that client failed at run time. A client under assertionIssuers must be an admitted client, or startup is refused with documents.runtime.assertion-issuer-client-not-allowed. Signed-off-by: Jeremi Joslin --- crates/registry-documents/src/auth.rs | 2 +- crates/registry-documents/src/config.rs | 316 +++++++++++++++++- crates/registry-documents/src/runtime.rs | 5 +- crates/registry-documents/src/schema.rs | 38 ++- .../tests/postgres_startup.rs | 42 ++- .../registry-documents/tests/support/mod.rs | 14 +- .../tests/token_characterisation.rs | 7 +- .../reference/documents-configuration.mdx | 3 +- .../src/content/docs/security/documents.mdx | 7 +- products/documents/CHANGELOG.md | 10 + .../contracts/security-invariant-matrix.yaml | 5 +- .../generated/runtime/runtime.schema.json | 24 +- .../scripts/check-config-conformance.py | 2 +- 13 files changed, 429 insertions(+), 46 deletions(-) diff --git a/crates/registry-documents/src/auth.rs b/crates/registry-documents/src/auth.rs index f62856f78a..394b7973c9 100644 --- a/crates/registry-documents/src/auth.rs +++ b/crates/registry-documents/src/auth.rs @@ -240,7 +240,7 @@ pub(crate) mod tests { .value } - fn keys() -> Arc { + pub(crate) fn keys() -> Arc { Arc::new(JwksFetcher::new_static( serde_json::from_value(json!({"keys": [{ "kty": "oct", diff --git a/crates/registry-documents/src/config.rs b/crates/registry-documents/src/config.rs index 8363b9b863..487e1b004a 100644 --- a/crates/registry-documents/src/config.rs +++ b/crates/registry-documents/src/config.rs @@ -21,10 +21,10 @@ use registry_platform_audit::{ }; use registry_platform_config::JwksSource; pub use registry_platform_config::{ - AttachmentVerifierConfig, AuditKeyConfig, DatabaseConfig, MetricsListenerConfig, - ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, PackageConfig, - PrivateListenerConfig as ListenerConfig, SecretProvidersConfig, TlsTermination, - UrlHookDestinationConfig, + AdmittedClients, AttachmentVerifierConfig, AuditKeyConfig, DatabaseConfig, + MetricsListenerConfig, ObjectStorageConfig, OidcIssuerConfig, OidcPackageClientsConfig, + PackageClients, PackageClientsError, PackageConfig, PrivateListenerConfig as ListenerConfig, + SecretProvidersConfig, TlsTermination, UrlHookDestinationConfig, }; use registry_platform_config::{ ConfigBlockError, RuntimeConfigLoader, RuntimeEnvelope, RuntimeFileCheck, SecretResolver, @@ -83,6 +83,11 @@ pub const MAXIMUM_HOOK_PAYLOAD_RETENTION_DAYS: u32 = 30; /// The largest `audit.rotateBytes`. pub const MAXIMUM_AUDIT_ROTATE_BYTES: u64 = u32::MAX as u64; +const ALLOWED_CLIENTS_REQUIRED_CODE: &str = "documents.runtime.allowed-clients-required"; +const PROFILE_CLIENT_NOT_ALLOWED_CODE: &str = "documents.runtime.profile-client-not-allowed"; +const ASSERTION_ISSUER_CLIENT_NOT_ALLOWED_CODE: &str = + "documents.runtime.assertion-issuer-client-not-allowed"; + /// The code of the refusal a runtime document earns when `destinations.hooks` /// leaves unbound a destination the project's hooks name. `documentsctl /// check` reports it at `/destinations/hooks`, and the runtime's startup @@ -156,11 +161,13 @@ pub struct OidcConfig { #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-issuer"))] #[cfg_attr(feature = "schema", schemars(flatten))] pub provider: OidcIssuerConfig, - /// The OAuth clients this runtime admits. Every access profile resolves - /// its caller from the matched client, so the list is never empty. - #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-clients"))] + /// The OAuth clients this runtime admits: `from-package` for the + /// requester clients of the project's access profiles, or a list that + /// covers every client a profile names. Every access profile resolves its + /// caller from the matched client, so the admitted set is never empty. + #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-package-clients"))] #[cfg_attr(feature = "schema", schemars(flatten))] - pub clients: OidcClientsConfig, + pub clients: OidcPackageClientsConfig, #[serde(default = "default_scope_claim")] pub scope_claim: ExternalId, } @@ -620,7 +627,7 @@ impl RuntimeConfig { /// describe: RFC 9068 access tokens only, from the configured issuer, /// for the configured audience, from an admitted client. #[must_use] - pub fn verifier_profile(&self) -> TokenVerifierConfig { + pub fn verifier_profile(&self, admitted: &AdmittedClients) -> TokenVerifierConfig { let oidc = &self.authentication.oidc; TokenVerifierConfig::access_token_profile( oidc.provider.issuer.to_string(), @@ -632,7 +639,7 @@ impl RuntimeConfig { access_token_typ_set(DOCUMENTS_ACCESS_TOKEN_TYPE), ) .with_scope_claim(oidc.scope_claim.as_str().to_owned()) - .with_allowed_clients(oidc.clients.allowed_clients.clone()) + .with_allowed_clients(admitted.as_slice().to_vec()) .with_assertion_issuers(oidc.clients.assertion_issuers.clone()) } @@ -781,13 +788,8 @@ impl RuntimeConfig { if let Err(error) = oidc.clients.check("authentication.oidc") { findings.push(Finding::block("/authentication/oidc", &error)); } - if oidc.clients.allowed_clients.is_empty() { - findings.push(Finding::new( - "documents.runtime.allowed-clients-required", - "/authentication/oidc/allowedClients", - "authentication.oidc.allowedClients must list the clients this runtime admits; `unrestricted` is refused", - "List every OAuth client an access profile names under allowedClients.", - )); + if oidc.clients.allowed_clients == PackageClients::Unrestricted { + findings.push(allowed_clients_required()); } } @@ -880,6 +882,79 @@ impl RuntimeConfig { /// `destinations.hooks`. #[must_use] pub fn project_findings(&self, project: &DocumentsProject) -> Vec { + let mut findings = self.client_findings(project); + findings.extend(self.hook_findings(project)); + findings + } + + /// The clients the token verifier admits, given the project this runtime + /// serves. `from-package` is the sorted union of the access profiles' + /// requester clients, and a list must cover every one of them, or the + /// profile naming the missing client could never be reached. The verifier + /// is never handed an empty list, which it reads as "every client". + pub fn admitted_clients(&self, project: &DocumentsProject) -> Result { + self.authentication + .oidc + .clients + .allowed_clients + .resolve(&requester_clients(project)) + .map_err(|error| match error { + PackageClientsError::Unrestricted | PackageClientsError::Empty => { + allowed_clients_required() + } + PackageClientsError::Missing(client) => { + let profile = project + .access_profiles + .iter() + .find(|(_, profile)| { + profile + .requester_clients + .as_slice() + .iter() + .any(|listed| listed.as_str() == client) + }) + .map_or("", |(id, _)| id.as_str()); + Finding::new( + PROFILE_CLIENT_NOT_ALLOWED_CODE, + "/authentication/oidc/allowedClients", + format!( + "authentication.oidc.allowedClients does not list {client}, a requester client of access profile {profile}" + ), + "Add the client to allowedClients, or write allowedClients: from-package to admit every requester client the project names.", + ) + } + }) + } + + /// What the admitted clients leave wrong against the project. An + /// `unrestricted` value is reported by [`Self::findings`] alone. + fn client_findings(&self, project: &DocumentsProject) -> Vec { + let oidc = &self.authentication.oidc; + if oidc.clients.allowed_clients == PackageClients::Unrestricted { + return Vec::new(); + } + let admitted = match self.admitted_clients(project) { + Ok(admitted) => admitted, + Err(finding) => return vec![finding], + }; + oidc.clients + .assertion_issuers + .keys() + .filter(|client| !admitted.as_slice().contains(client)) + .map(|client| { + Finding::new( + ASSERTION_ISSUER_CLIENT_NOT_ALLOWED_CODE, + &dotted_pointer(&format!("authentication.oidc.assertionIssuers.{client}")), + format!( + "authentication.oidc.assertionIssuers names {client}, which no access profile of the project lists as a requester client" + ), + "Name a requester client of an access profile, or remove the entry.", + ) + }) + .collect() + } + + fn hook_findings(&self, project: &DocumentsProject) -> Vec { let unbound = project.hooks.iter().any(|hook| { let HookHandler::Url { destination_id } = &hook.handler; !self @@ -912,6 +987,29 @@ fn dotted_pointer(field: &str) -> String { .collect() } +/// The requester clients of every access profile of `project`, sorted and +/// distinct. +fn requester_clients(project: &DocumentsProject) -> Vec { + let mut clients: Vec = project + .access_profiles + .values() + .flat_map(|profile| profile.requester_clients.as_slice()) + .map(|client| client.as_str().to_owned()) + .collect(); + clients.sort(); + clients.dedup(); + clients +} + +fn allowed_clients_required() -> Finding { + Finding::new( + ALLOWED_CLIENTS_REQUIRED_CODE, + "/authentication/oidc/allowedClients", + "authentication.oidc.allowedClients must be `from-package` or list the clients this runtime admits; `unrestricted` is refused", + "Write allowedClients: from-package, or list every OAuth client an access profile names.", + ) +} + /// What an offline check of one runtime document found (CFG-CHECK-1). #[derive(Debug)] pub struct RuntimeCheck { @@ -1295,6 +1393,190 @@ pub(crate) mod tests { ); } + const STARTER_CLIENTS: &str = + "allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal]"; + + fn from_package_runtime() -> String { + let text = STARTER_RUNTIME.replace(STARTER_CLIENTS, "allowedClients: from-package"); + assert_ne!(text, STARTER_RUNTIME); + text + } + + fn starter_project() -> DocumentsProject { + DocumentsProject::decode( + "documents.yaml", + include_bytes!("../../../products/documents/examples/starter/documents.yaml"), + ) + .expect("the starter project decodes") + .value + } + + fn project_finding_codes(config: &RuntimeConfig, project: &DocumentsProject) -> Vec { + config + .project_findings(project) + .iter() + .map(|finding| format!("{} {}", finding.code, finding.pointer)) + .collect() + } + + #[test] + fn from_package_is_accepted_and_names_no_second_list() { + let config = parse(&from_package_runtime()).expect("from-package loads"); + assert_eq!( + config.authentication.oidc.clients.allowed_clients, + PackageClients::FromPackage + ); + assert_eq!( + project_finding_codes(&config, &starter_project()), + [] as [String; 0] + ); + } + + #[test] + fn an_omitted_allowed_clients_member_is_refused() { + let text = STARTER_RUNTIME.replace(STARTER_CLIENTS, ""); + assert_ne!(text, STARTER_RUNTIME); + let found = codes(parse(&text).unwrap_err()); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].starts_with("config."), "{found:?}"); + } + + #[test] + fn an_empty_list_and_an_unknown_keyword_are_refused() { + for written in ["allowedClients: []", "allowedClients: any"] { + let text = STARTER_RUNTIME.replace(STARTER_CLIENTS, written); + assert!(parse(&text).is_err(), "{written}"); + } + } + + #[test] + fn explicit_list_missing_a_package_client_is_refused() { + let text = STARTER_RUNTIME.replace( + STARTER_CLIENTS, + "allowedClients: [civil-registry-app, citizen-portal, case-portal]", + ); + let config = parse(&text).expect("a list is a valid file on its own"); + assert_eq!( + project_finding_codes(&config, &starter_project()), + ["documents.runtime.profile-client-not-allowed /authentication/oidc/allowedClients"] + ); + } + + #[test] + fn an_explicit_list_with_a_client_the_package_does_not_name_is_accepted() { + let text = STARTER_RUNTIME.replace( + STARTER_CLIENTS, + "allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal, extra-app]", + ); + let config = parse(&text).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + [] as [String; 0] + ); + } + + #[test] + fn assertion_issuer_client_outside_the_package_is_refused_under_from_package() { + let with_issuers = |client: &str| { + from_package_runtime().replace( + "allowedClients: from-package\n", + &format!( + "allowedClients: from-package\n assertionIssuers:\n {client}: [https://assertions.example.test]\n" + ), + ) + }; + let config = parse(&with_issuers("unknown-client")).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + ["documents.runtime.assertion-issuer-client-not-allowed /authentication/oidc/assertionIssuers/unknown-client"] + ); + let config = parse(&with_issuers("citizen-portal")).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + [] as [String; 0] + ); + } + + #[test] + fn assertion_issuer_client_outside_an_explicit_list_is_refused() { + let text = STARTER_RUNTIME.replace( + "allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal]\n", + "allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal]\n assertionIssuers:\n unknown-client: [https://assertions.example.test]\n", + ); + assert_ne!(text, STARTER_RUNTIME); + let config = parse(&text).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + ["documents.runtime.assertion-issuer-client-not-allowed /authentication/oidc/assertionIssuers/unknown-client"] + ); + } + + #[tokio::test] + async fn from_package_admits_exactly_the_package_clients() { + use crate::auth::tests::{keys, token}; + use registry_platform_oidc::TokenVerifier; + + let project = DocumentsProject::decode( + "documents.yaml", + include_str!("../../../products/documents/examples/starter/documents.yaml") + .replacen( + "requesterClients: [civil-registry-app]", + "requesterClients: [civil-registry-app, second-app]", + 1, + ) + .as_bytes(), + ) + .expect("the project decodes") + .value; + let config = parse(&from_package_runtime()).unwrap(); + let admitted = config.admitted_clients(&project).unwrap(); + assert_eq!( + admitted.as_slice(), + [ + "case-portal", + "citizen-portal", + "civil-registry-app", + "partner-portal", + "second-app" + ] + ); + let mut profile = config.verifier_profile(&admitted); + profile.allowed_algorithms = vec![jsonwebtoken::Algorithm::HS256]; + let verifier = TokenVerifier::new(profile, keys()); + let signed = |client: &str| { + token(serde_json::json!({ + "iss": "https://identity.example.test/realms/registry", + "aud": "urn:example:documents", + "sub": "principal", + "azp": client, + "scope": "documents:read", + })) + }; + for client in admitted.as_slice() { + verifier + .verify(&signed(client)) + .await + .unwrap_or_else(|error| panic!("{client} is admitted: {error}")); + } + let refused = verifier.verify(&signed("stranger-app")).await; + assert!( + matches!( + refused, + Err(registry_platform_oidc::OidcError::ClientNotAllowed) + ), + "{refused:?}" + ); + } + + #[test] + fn from_package_never_reaches_the_verifier_as_an_empty_list() { + let config = parse(&from_package_runtime()).unwrap(); + let mut project = starter_project(); + project.access_profiles.clear(); + let finding = config.admitted_clients(&project).unwrap_err(); + assert_eq!(finding.code, "documents.runtime.allowed-clients-required"); + } + #[test] fn disabled_content_verification_requires_development_loopback() { let disabled = STARTER_RUNTIME.replace(HTTP_VERIFIER, " type: disabled\n"); diff --git a/crates/registry-documents/src/runtime.rs b/crates/registry-documents/src/runtime.rs index 456cde783c..24077f3be5 100644 --- a/crates/registry-documents/src/runtime.rs +++ b/crates/registry-documents/src/runtime.rs @@ -411,8 +411,11 @@ async fn prepare_with( "versions verified under another verifier binding were suspended for verification again" ); } + let admitted = config + .admitted_clients(&project) + .map_err(|finding| RuntimeConfigError::Refused(vec![finding]))?; let authenticator = Arc::new(DocumentsAuthenticator::new( - config.verifier_profile(), + config.verifier_profile(&admitted), keys, AccessProfiles::new(&project), config.binds_assertion_issuers(), diff --git a/crates/registry-documents/src/schema.rs b/crates/registry-documents/src/schema.rs index c8703c1fe1..425c6a0782 100644 --- a/crates/registry-documents/src/schema.rs +++ b/crates/registry-documents/src/schema.rs @@ -803,21 +803,32 @@ fn install_runtime_constraints(schema: &mut Value) { set_definition_property(schema, definition, property, "pattern", json!("^/")); } // Every access profile resolves its caller from the matched client, so - // a Document Store deployment always lists the clients it admits. The + // a Document Store deployment always states the clients it admits. The // shared block also admits the keyword `unrestricted`, which this - // runtime refuses in every mode, so the member is restated as the list - // alone and the shared definition is dropped. + // runtime refuses in every mode, so the member is restated as + // `from-package` or the list and the shared definition is dropped. if let Some(clients) = schema.pointer_mut("/$defs/OidcConfig/properties/allowedClients") { *clients = json!({ - "description": "Client identifiers whose access tokens are admitted. Required in every\nfile; an omitted or empty list, an empty or repeated client, and\n`unrestricted` are refused.", - "type": "array", - "items": {"type": "string", "minLength": 1}, - "minItems": 1, - "uniqueItems": true, + "description": "The clients whose access tokens are admitted. Required in every\nfile: `from-package` admits the requester clients of the package's access\nprofiles, and a list of at least one distinct client must cover them. An\nomitted or empty list, an empty or repeated client, and `unrestricted` are\nrefused.", + "oneOf": [ + {"type": "string", "const": "from-package"}, + { + "type": "array", + "items": {"type": "string", "minLength": 1}, + "minItems": 1, + "uniqueItems": true, + }, + ], }); } + if let Some(issuers) = + schema.pointer_mut("/$defs/OidcConfig/properties/assertionIssuers/description") + { + *issuers = json!("Assertion authorities each client may exchange a subject token from,\nkeyed by client identifier. Omitted, no assertion-issuer rule applies;\nwritten, it lists at least one client, each with at least one\nauthority. Once a client is listed, a token it exchanged is accepted\nonly for one of that client's declared authorities, and a client that\nis not listed may exchange from no authority."); + } if let Some(definitions) = schema.pointer_mut("/$defs").and_then(Value::as_object_mut) { definitions.remove("OidcAllowedClients"); + definitions.remove("OidcPackageAllowedClients"); } if let Some(providers) = schema .pointer_mut("/$defs/SecretProvidersConfig") @@ -923,9 +934,16 @@ mod tests { ); } let clients = &document["$defs"]["OidcConfig"]["properties"]["allowedClients"]; - assert_eq!(clients["type"], "array"); - assert_eq!(clients["minItems"], 1); + let forms = clients["oneOf"].as_array().expect("two written forms"); + assert_eq!(forms.len(), 2, "{clients}"); + assert_eq!(forms[0], json!({"type": "string", "const": "from-package"})); + assert_eq!(forms[1]["type"], "array"); + assert_eq!(forms[1]["minItems"], 1); + assert_eq!(forms[1]["uniqueItems"], true); + assert_eq!(forms[1]["items"]["minLength"], 1); + assert!(clients.get("$ref").is_none(), "{clients}"); assert!(document["$defs"].get("OidcAllowedClients").is_none()); + assert!(document["$defs"].get("OidcPackageAllowedClients").is_none()); } #[test] diff --git a/crates/registry-documents/tests/postgres_startup.rs b/crates/registry-documents/tests/postgres_startup.rs index 6f2f668407..5c2f5057a5 100644 --- a/crates/registry-documents/tests/postgres_startup.rs +++ b/crates/registry-documents/tests/postgres_startup.rs @@ -17,7 +17,7 @@ use registry_documents::runtime::{prepare, RuntimeError}; use registry_documents_client::{DocumentsClient, DocumentsClientConfig, ProblemCode}; use support::{ database_url, pdf, reservation_body, sha256, token, Deployment, APP, CITIZEN, DATABASE_STORAGE, - DISABLED_VERIFIER, + DISABLED_VERIFIER, PARTNER_SERVICE, READER, STAFF, }; use url::Url; @@ -129,6 +129,46 @@ async fn a_prepared_runtime_serves_documents_only_to_a_verified_caller() { server.await.unwrap().unwrap(); } +/// The runtime file says `allowedClients: from-package` and lists no client. +/// Each requester client of the package reaches its profile, and a client the +/// package does not name is refused. +#[tokio::test] +async fn a_runtime_that_admits_the_package_clients_serves_a_call_from_each() { + let mut deployment = Deployment::new(DATABASE_STORAGE, DISABLED_VERIFIER).await; + deployment.admit_package_clients(); + let text = std::fs::read_to_string(&deployment.runtime).unwrap(); + assert!(text.contains("allowedClients: from-package"), "{text}"); + deployment.migrate().await; + let prepared = prepare(&deployment.runtime) + .await + .expect("the runtime prepares"); + let address = prepared.local_addr().unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(prepared.serve_until(async { + stopped.await.ok(); + })); + let http = reqwest::Client::new(); + let policies = format!("http://{address}/v1/document-policies"); + for principal in [APP, CITIZEN, READER, STAFF] { + let response = http + .get(&policies) + .bearer_auth(token(principal)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::OK, "{principal:?}"); + } + let response = http + .get(&policies) + .bearer_auth(token(PARTNER_SERVICE)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED); + stop.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + #[tokio::test] async fn a_runtime_whose_database_refuses_the_credential_does_not_start() { let mut refused = Url::parse(&database_url()).unwrap(); diff --git a/crates/registry-documents/tests/support/mod.rs b/crates/registry-documents/tests/support/mod.rs index b06e474577..39411d1594 100644 --- a/crates/registry-documents/tests/support/mod.rs +++ b/crates/registry-documents/tests/support/mod.rs @@ -66,6 +66,7 @@ pub struct Deployment { erasure: &'static str, extra: String, hooks_url: String, + allowed_clients: String, } impl Deployment { @@ -122,6 +123,9 @@ impl Deployment { erasure: "active", extra: String::new(), hooks_url: UNREACHABLE_HOOKS_URL.to_owned(), + allowed_clients: + "[civil-registry-app, citizen-portal, case-portal, partner-portal, partner-service]" + .to_owned(), }; deployment.secret("runtime-database-url", runtime_url.unwrap_or(&scoped_url)); deployment.secret("migration-database-url", &scoped_url); @@ -180,6 +184,13 @@ impl Deployment { self.write_runtime(); } + /// Write `allowedClients: from-package`, so the runtime admits exactly the + /// requester clients the package names and the file lists none. + pub fn admit_package_clients(&mut self) { + self.allowed_clients = "from-package".to_owned(); + self.write_runtime(); + } + /// Append `block`, top-level runtime keys, to the runtime document. pub fn configure(&mut self, block: &str) { self.extra = block.to_owned(); @@ -211,7 +222,7 @@ authentication: issuer: https://identity.example.test/realms/registry audience: urn:example:documents scopeClaim: scope - allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal, partner-service] + allowedClients: {allowed_clients} jwksSource: type: static documentRef: secret:file/jwks.json @@ -237,6 +248,7 @@ destinations: erasure = self.erasure, extra = self.extra, hooks_url = self.hooks_url, + allowed_clients = self.allowed_clients, ); std::fs::write(&self.runtime, document).unwrap(); } diff --git a/crates/registry-documents/tests/token_characterisation.rs b/crates/registry-documents/tests/token_characterisation.rs index 44d7e6ded4..e3d49ecdee 100644 --- a/crates/registry-documents/tests/token_characterisation.rs +++ b/crates/registry-documents/tests/token_characterisation.rs @@ -243,8 +243,11 @@ destinations: .expect("the rewritten project decodes") .value; + let admitted = config + .admitted_clients(&decoded) + .expect("the listed clients cover the project"); let authenticator = DocumentsAuthenticator::new( - config.verifier_profile(), + config.verifier_profile(&admitted), keys.clone(), AccessProfiles::new(&decoded), config.binds_assertion_issuers(), @@ -255,7 +258,7 @@ destinations: Err(AuthenticationError::Claims(_)) => refusal("claims"), Err(AuthenticationError::Unavailable) => refusal("unavailable"), Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { - let reference = TokenVerifier::new(config.verifier_profile(), keys); + let reference = TokenVerifier::new(config.verifier_profile(&admitted), keys); match reference.verify(token).await { Err(failure) => refusal(failure.authentication_stage().label()), Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { diff --git a/docs/site/src/content/docs/reference/documents-configuration.mdx b/docs/site/src/content/docs/reference/documents-configuration.mdx index 3fb714e553..08b162c292 100644 --- a/docs/site/src/content/docs/reference/documents-configuration.mdx +++ b/docs/site/src/content/docs/reference/documents-configuration.mdx @@ -132,7 +132,8 @@ The other blocks are checked, so a deployment written now keeps its meaning when - `database.testOnlyPlaintext` is accepted only by builds with the `postgres-test` feature, for the PostgreSQL test suites. An operator build refuses it with `documents.runtime.plaintext-database`, so a local run needs a database that serves TLS too. - `authentication.oidc` is the shared OIDC issuer block (`issuer`, `audience`, `jwksSource`), with `allowedClients` and `scopeClaim` (default `scope`). - `allowedClients` must list clients, and `unrestricted` is refused. + `allowedClients` is required. Write `from-package` to admit exactly the `requesterClients` of the package's access profiles, so the clients are written once, in `documents.yaml`. A list is also accepted, and it must include every client an access profile names, or the runtime refuses to start with `documents.runtime.profile-client-not-allowed`. Clients in the list that no profile names are admitted by the verifier but reach no profile. `unrestricted` and an empty list are refused. + Each client named under `assertionIssuers` must be one of the admitted clients, or the runtime refuses to start with `documents.runtime.assertion-issuer-client-not-allowed`. `jwksSource` defaults to the key set that the issuer's discovery document names. [Access tokens](../../operate/documents/#access-tokens) states what a token must carry and describes the other key sources. - `audit` takes `destination` (`file`, the default, or `stdout`), `path` for a file journal, and `hashKeyRef`. diff --git a/docs/site/src/content/docs/security/documents.mdx b/docs/site/src/content/docs/security/documents.mdx index 30e11a01c9..ae070d7b41 100644 --- a/docs/site/src/content/docs/security/documents.mdx +++ b/docs/site/src/content/docs/security/documents.mdx @@ -29,7 +29,12 @@ and the restore drill is in clients, signature from the configured key set) and resolves exactly one access profile before it reads a body or the store. An unreachable key set answers 503, never 401. - The deployment trusts one issuer; `allowedClients: unrestricted` is refused. + The deployment trusts one issuer. + `allowedClients` is required in every runtime file. `allowedClients: from-package` admits the sorted + union of the access profiles' `requesterClients` and nothing more, so the package and the runtime + file cannot disagree. An explicit list must include every client an access profile names, or the + runtime refuses to start with `documents.runtime.profile-client-not-allowed`. + `allowedClients: unrestricted` and an empty list are refused in every mode. Declared issuer and key addresses are trusted on the operator's word (DOCUMENTS-RES-17). A static key set (`jwksSource: static`) holds public keys only. The runtime refuses to start on a set that carries a private member (`d`, `p`, `q`, `dp`, `dq`, diff --git a/products/documents/CHANGELOG.md b/products/documents/CHANGELOG.md index 3df75b2bea..baf1869a9f 100644 --- a/products/documents/CHANGELOG.md +++ b/products/documents/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- `authentication.oidc.allowedClients` accepts the keyword `from-package`, + which admits the requester clients of the package's access profiles, so the + clients are written once, in the package. The member stays required, and an + omitted member, an empty list and `unrestricted` are still refused. A list + must now include every client a profile names, or startup is refused with + `documents.runtime.profile-client-not-allowed`, where before the runtime + started and the missing client failed at run time. A client named under + `assertionIssuers` must be an admitted client, or startup is refused with + `documents.runtime.assertion-issuer-client-not-allowed`. + - The Document Store counts every refused request by the check that refused it, in `documents_request_refusals_total{check}` on the metrics listener, published at zero for every check. Each refusal writes one `request refused` diff --git a/products/documents/contracts/security-invariant-matrix.yaml b/products/documents/contracts/security-invariant-matrix.yaml index 5ed921579c..ebd5ec9acc 100644 --- a/products/documents/contracts/security-invariant-matrix.yaml +++ b/products/documents/contracts/security-invariant-matrix.yaml @@ -80,8 +80,9 @@ invariants: Any client the issuer knows can call the Document Store because the operator never named the clients the deployment serves. enforcementPoint: >- - The runtime configuration requires an explicit allowedClients list; the - unrestricted form is refused. + The runtime configuration requires allowedClients: an explicit list that + covers every requester client the package names, or from-package, which + admits exactly those clients. The unrestricted form is refused. refusal: >- Refuse with documents.runtime.allowed-clients-required at /authentication/oidc/allowedClients. diff --git a/products/documents/generated/runtime/runtime.schema.json b/products/documents/generated/runtime/runtime.schema.json index 36d5237ca3..c4e2131757 100644 --- a/products/documents/generated/runtime/runtime.schema.json +++ b/products/documents/generated/runtime/runtime.schema.json @@ -324,14 +324,22 @@ "type": "boolean" }, "allowedClients": { - "description": "Client identifiers whose access tokens are admitted. Required in every\nfile; an omitted or empty list, an empty or repeated client, and\n`unrestricted` are refused.", - "items": { - "minLength": 1, - "type": "string" - }, - "minItems": 1, - "type": "array", - "uniqueItems": true + "description": "The clients whose access tokens are admitted. Required in every\nfile: `from-package` admits the requester clients of the package's access\nprofiles, and a list of at least one distinct client must cover them. An\nomitted or empty list, an empty or repeated client, and `unrestricted` are\nrefused.", + "oneOf": [ + { + "const": "from-package", + "type": "string" + }, + { + "items": { + "minLength": 1, + "type": "string" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + } + ] }, "assertionIssuers": { "additionalProperties": { diff --git a/products/platform/scripts/check-config-conformance.py b/products/platform/scripts/check-config-conformance.py index 6c19214fe2..b814d3d623 100755 --- a/products/platform/scripts/check-config-conformance.py +++ b/products/platform/scripts/check-config-conformance.py @@ -496,7 +496,7 @@ class Row: "crates/registry-documents/src/config.rs", "OidcConfig", "clients", - "OidcClientsConfig", + "OidcPackageClientsConfig", ), RustBlock( "crates/registry-documents/src/config.rs", From 437c6e62ae3aae3a3344c5e5862b377d98fafaf9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 06:49:20 +0100 Subject: [PATCH 036/136] feat(adapter): count refused requests and align the security pages docs: describe refused-request counting and loopback the same way on every security page The security overview gains a section on refused requests: each runtime counts every refusal by the check that refused it, logs one bounded line with no caller value, and an operator alerts on the counter. The hardening checklist names the loopback rule and the rule that an empty or omitted allowedPrivateCidrs admits no private address. The eight product security pages describe the counter, the log line and loopback in the same terms, and the operate and reference pages list each product's _request_refusals_total series. feat(adapter): count and log every refused request under the check that refused it The facade and the payment routes count each refused caller in adapter_request_refusals_total{check}, with the 45 shared check labels all present at zero, and write one request refused line carrying failed_check and no caller value, at most five lines per check per minute. It replaces the per-stage authentication line. The job host's hook ingress does the same in adapter_job_request_refusals_total{check}. No answer changes: golden tests pin the facade and payment refusal answers. Loopback is one definition wherever the Adapter decides it: the rest of 127.0.0.0/8, ::1 and the IPv4-mapped forms count beside 127.0.0.1, the name localhost is pinned to loopback addresses, and a.localhost and localhost. stay named hosts. The payment provider base URL and the simulator connection still take address literals only. BREAKING: a plain http:// endpoint named by host name with an empty or omitted allowedPrivateCidrs now fails the runtime check with adapter.runtime.insecure-origin. For an Adapter job this replaces an empty list that admitted every private address. To migrate, list the smallest range that holds the endpoint, serve it over https, or bind it on loopback. Signed-off-by: Jeremi Joslin --- Cargo.lock | 2 + crates/registry-adapter-core/src/checks.rs | 52 ++- crates/registry-adapter-engine/src/egress.rs | 32 +- crates/registry-adapter-job/Cargo.toml | 3 + .../registry-adapter-job/src/destination.rs | 5 +- .../registry-adapter-job/src/hook_ingress.rs | 151 +++++-- crates/registry-adapter-job/src/metrics.rs | 14 + .../src/postgres_source.rs | 7 +- .../src/rabbitmq_source.rs | 7 +- .../tests/job_file_host.rs | 38 ++ crates/registry-adapter/Cargo.toml | 2 +- crates/registry-adapter/src/facade.rs | 261 ++++++++++-- crates/registry-adapter/src/metrics.rs | 49 ++- .../src/payments/g2p_model.rs | 30 +- crates/registry-adapter/src/payments/http.rs | 206 ++++++--- .../src/payments/http/refusal_tests.rs | 393 ++++++++++++++++++ .../registry-adapter/src/payments/service.rs | 128 ++++-- crates/registry-adapter/src/serve.rs | 86 ++-- .../src/serve/token_characterisation.rs | 13 +- .../registry-adapter/tests/facade_refusals.rs | 342 +++++++++++++++ .../tests/golden/facade_refusals.json | 171 ++++++++ .../tests/golden/payment_refusals.json | 182 ++++++++ .../tests/records_get_served.rs | 10 +- crates/registry-adapterctl/src/verify/mod.rs | 11 +- .../src/lib.rs | 6 +- .../tests/profile.rs | 17 + .../src/content/docs/configure/adapter.mdx | 24 +- .../docs/configure/evidence-oid4vci.mdx | 3 +- .../site/src/content/docs/operate/adapter.mdx | 2 + .../src/content/docs/operate/coordinator.mdx | 3 +- .../src/content/docs/operate/messaging.mdx | 3 +- .../src/content/docs/operate/scheduling.mdx | 3 +- .../src/content/docs/operate/stuck-work.mdx | 10 +- .../reference/messaging-configuration.mdx | 3 +- docs/site/src/content/docs/security/breg.mdx | 13 +- .../src/content/docs/security/casework.mdx | 24 +- .../src/content/docs/security/coordinator.mdx | 22 +- .../src/content/docs/security/documents.mdx | 10 +- .../src/content/docs/security/evidence.mdx | 16 +- .../docs/security/hardening-checklist.mdx | 12 +- docs/site/src/content/docs/security/index.mdx | 32 +- .../src/content/docs/security/messaging.mdx | 30 +- .../site/src/content/docs/security/render.mdx | 14 +- .../src/content/docs/security/scheduling.mdx | 14 +- products/adapter/CHANGELOG.md | 29 ++ 45 files changed, 2147 insertions(+), 338 deletions(-) create mode 100644 crates/registry-adapter/src/payments/http/refusal_tests.rs create mode 100644 crates/registry-adapter/tests/facade_refusals.rs create mode 100644 crates/registry-adapter/tests/golden/facade_refusals.json create mode 100644 crates/registry-adapter/tests/golden/payment_refusals.json diff --git a/Cargo.lock b/Cargo.lock index edb30821d6..d560df0364 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6109,11 +6109,13 @@ dependencies = [ "registry-adapter-connectors", "registry-adapter-core", "registry-adapter-engine", + "registry-platform-authcommon", "registry-platform-buildinfo", "registry-platform-config", "registry-platform-crypto", "registry-platform-hooks", "registry-platform-httputil", + "registry-platform-loopback", "registry-platform-metrics", "registry-platform-ratelimit", "registry-platform-testing", diff --git a/crates/registry-adapter-core/src/checks.rs b/crates/registry-adapter-core/src/checks.rs index 9ad56c0bdc..4d27c302b4 100644 --- a/crates/registry-adapter-core/src/checks.rs +++ b/crates/registry-adapter-core/src/checks.rs @@ -6995,7 +6995,7 @@ fn check_token_endpoint( /// address, so the parse below would read every IPv6 loopback as /// non-loopback. fn is_loopback_origin(url: ®istry_platform_yaml::Url) -> bool { - literal_origin_address(url).is_some_and(|address| address.is_loopback()) + literal_origin_address(url).is_some_and(registry_platform_httputil::loopback::loopback_address) } /// The address literal a bound origin's host carries, when it carries @@ -7016,14 +7016,9 @@ fn literal_origin_address(url: ®istry_platform_yaml::Url) -> Option bool { - let parsed = url.to_url(); - if parsed + url.to_url() .host_str() - .is_some_and(|host| host.eq_ignore_ascii_case("localhost")) - { - return true; - } - literal_origin_address(url).is_some_and(|address| address.is_loopback()) + .is_some_and(|host| registry_platform_httputil::loopback::loopback_host(host).is_some()) } /// The one plain-HTTP rule: @@ -7048,9 +7043,9 @@ pub fn plain_http_origin_admitted( // A named host resolves at send, where the same containment rule // runs on the answers; the check cannot resolve, so it defers to the // send. With an empty `allowedPrivateCidrs` the send admits no - // private address, and the destination policy refuses the origin - // when the runtime freezes it, naming the missing range. - None => true, + // private address, so the check refuses the origin and names the + // missing range. + None => !allowed_private_cidrs.is_empty(), } } @@ -13978,6 +13973,41 @@ mod tests { assert!( !codes(&check_runtime(&ws, &named)).contains(&CheckCode::RuntimeInsecureOrigin.code()) ); + // With no declared CIDR the send admits no private address, so the + // check refuses the named host and names the missing range. + let undeclared = runtime_builder(vec![oauth_binding("http://internal-api:8080")]); + let mut ws = workspace(&profile, &pack, &project); + ws.runtime = Some(&undeclared); + assert_has( + &check_runtime(&ws, &undeclared), + CheckCode::RuntimeInsecureOrigin, + ); + // Every loopback spelling is the loopback exception; a name that only + // looks like it is a named host. + for origin in [ + "http://localhost:8081", + "http://127.0.0.2:8081", + "http://[::1]:8081", + "http://[::ffff:127.0.0.1]:8081", + ] { + let spelled = runtime_builder(vec![oauth_binding(origin)]); + let mut ws = workspace(&profile, &pack, &project); + ws.runtime = Some(&spelled); + assert!( + !codes(&check_runtime(&ws, &spelled)) + .contains(&CheckCode::RuntimeInsecureOrigin.code()), + "{origin}" + ); + } + for origin in ["http://a.localhost:8081", "http://localhost.:8081"] { + let spelled = runtime_builder(vec![oauth_binding(origin)]); + let mut ws = workspace(&profile, &pack, &project); + ws.runtime = Some(&spelled); + assert_has( + &check_runtime(&ws, &spelled), + CheckCode::RuntimeInsecureOrigin, + ); + } } #[test] diff --git a/crates/registry-adapter-engine/src/egress.rs b/crates/registry-adapter-engine/src/egress.rs index 0532cc5b6e..8545d5e78b 100644 --- a/crates/registry-adapter-engine/src/egress.rs +++ b/crates/registry-adapter-engine/src/egress.rs @@ -2144,14 +2144,12 @@ pub(crate) fn destination_profile(parsed_base: &url::Url) -> DestinationProfile /// Whether the origin's host explicitly denotes loopback: the name /// `localhost` or a loopback address literal, the platform's own -/// admission rule for the development profile. +/// admission rule for the development profile. The destination policy pins +/// the name to loopback addresses when it connects. pub(crate) fn denotes_loopback(origin: &url::Url) -> bool { - match origin.host() { - Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), - Some(url::Host::Ipv4(address)) => address.is_loopback(), - Some(url::Host::Ipv6(address)) => address.is_loopback(), - None => false, - } + origin + .host_str() + .is_some_and(|host| registry_platform_httputil::loopback::loopback_host(host).is_some()) } /// Whether a destination profile admits a token endpoint: the same @@ -3716,6 +3714,26 @@ mod tests { destination_profile(&public_name), DestinationProfile::PrivateServiceHttp ); + for spelled in [ + "http://127.0.0.2:8080/", + "http://[::1]:8080/", + "http://[::ffff:127.0.0.1]:8080/", + ] { + let origin = url::Url::parse(spelled).expect("parsed"); + assert_eq!( + destination_profile(&origin), + DestinationProfile::LoopbackDevelopmentHttp, + "{spelled}" + ); + } + for spelled in ["http://a.localhost:8080/", "http://localhost.:8080/"] { + let origin = url::Url::parse(spelled).expect("parsed"); + assert_eq!( + destination_profile(&origin), + DestinationProfile::PrivateServiceHttp, + "{spelled}" + ); + } } /// Under the postgres-test feature an https loopback origin takes diff --git a/crates/registry-adapter-job/Cargo.toml b/crates/registry-adapter-job/Cargo.toml index b3f705b5ea..c417931ef4 100644 --- a/crates/registry-adapter-job/Cargo.toml +++ b/crates/registry-adapter-job/Cargo.toml @@ -21,6 +21,7 @@ default = [] # wake the interval pass loop early. The facade never enables or links it. job-hook = [ "dep:base64", + "dep:registry-platform-authcommon", "dep:futures", "dep:registry-platform-crypto", "dep:registry-platform-ratelimit", @@ -90,10 +91,12 @@ required-features = ["job-hook", "postgres-test"] registry-adapter-engine.workspace = true registry-adapter-core.workspace = true registry-adapter-connectors = { workspace = true, optional = true } +registry-platform-authcommon = { workspace = true, optional = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto = { workspace = true, optional = true } registry-platform-httputil = { workspace = true, optional = true } +registry-platform-loopback.workspace = true registry-platform-metrics.workspace = true registry-platform-ratelimit = { workspace = true, optional = true } registry-platform-yaml.workspace = true diff --git a/crates/registry-adapter-job/src/destination.rs b/crates/registry-adapter-job/src/destination.rs index 459aa1d73d..84557ced66 100644 --- a/crates/registry-adapter-job/src/destination.rs +++ b/crates/registry-adapter-job/src/destination.rs @@ -275,8 +275,9 @@ impl FixtureDestination { .rsplit_once(':') .map(|(host, _)| host) .unwrap_or(authority); - let loopback = matches!(host, "127.0.0.1" | "::1" | "[::1]" | "localhost"); - if !loopback { + // The fixture receiver is never a real hop, so the name `localhost` + // is accepted without pinning the connection. + if registry_platform_loopback::loopback_host(host).is_none() { return Err(format!( "the fixture url host {host} is not a loopback address; the fixture receiver runs on this machine" )); diff --git a/crates/registry-adapter-job/src/hook_ingress.rs b/crates/registry-adapter-job/src/hook_ingress.rs index 0774d3bd57..2bfd6a8cb2 100644 --- a/crates/registry-adapter-job/src/hook_ingress.rs +++ b/crates/registry-adapter-job/src/hook_ingress.rs @@ -18,6 +18,7 @@ use base64::{engine::general_purpose::STANDARD, Engine as _}; use futures::StreamExt as _; use registry_adapter_core::AdapterJob; use registry_adapter_engine::job_sources::{HookSourceConfig, JobRuntimeConfig}; +use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote}; use registry_platform_config::{ProtectedSecret, SecretError, SecretResolver}; use registry_platform_crypto::mac::constant_time_eq; use registry_platform_ratelimit::token_bucket::{ @@ -365,35 +366,43 @@ impl BasicCredential { Ok(Self { username, password }) } - fn authenticates(&self, authorization: &[u8]) -> bool { + /// `Ok` for the exact canonical pair, else the check that refused it. + fn authenticates(&self, authorization: &[u8]) -> Result<(), FailedCheck> { + let malformed = FailedCheck::CredentialMalformed; if authorization.len() > MAX_BASIC_PAYLOAD_BYTES + 6 { - return false; + return Err(malformed); } let Some((scheme, payload)) = split_once(authorization, b' ') else { - return false; + return Err(malformed); }; - if !scheme.eq_ignore_ascii_case(b"Basic") - || payload.is_empty() + if !scheme.eq_ignore_ascii_case(b"Basic") { + return Err(FailedCheck::CredentialMissing); + } + if payload.is_empty() || payload.iter().any(u8::is_ascii_whitespace) || payload.len() > MAX_BASIC_PAYLOAD_BYTES { - return false; + return Err(malformed); } let Ok(mut decoded) = STANDARD.decode(payload).map(Zeroizing::new) else { - return false; + return Err(malformed); }; let canonical = Zeroizing::new(STANDARD.encode(decoded.as_slice())); if canonical.as_bytes() != payload { - return false; + return Err(malformed); } let Some(colon) = decoded.iter().position(|byte| *byte == b':') else { - return false; + return Err(malformed); }; let password = Zeroizing::new(decoded.split_off(colon + 1)); decoded.truncate(colon); let username_matches = constant_time_eq(decoded.as_slice(), self.username.expose_secret()); let password_matches = constant_time_eq(password.as_slice(), self.password.expose_secret()); - username_matches & password_matches + if username_matches & password_matches { + Ok(()) + } else { + Err(FailedCheck::SharedSecret) + } } } @@ -434,6 +443,9 @@ async fn receive_hook_until( if let Some(reason) = refusal_reason(answer.status()) { metrics.record_hook_refusal(reason); } + if let Some(note) = answer.extensions().get::() { + record_refusal!(metrics.refusals(), *note); + } answer } @@ -468,11 +480,14 @@ async fn answer_hook( None, ); } - if !authenticated(request.headers(), &source.credential) { - return response( - StatusCode::UNAUTHORIZED, - "adapter.job.hook-unauthenticated", - None, + if let Err(check) = authenticated(request.headers(), &source.credential) { + return noted( + response( + StatusCode::UNAUTHORIZED, + "adapter.job.hook-unauthenticated", + None, + ), + check, ); } let retry_after = match source.limiter.check("source", 1).await { @@ -491,10 +506,13 @@ async fn answer_hook( } }; if let Some(retry_after) = retry_after { - return response( - StatusCode::TOO_MANY_REQUESTS, - "adapter.job.hook-rate-limited", - Some(retry_after.as_secs_f64().ceil().max(1.0) as u64), + return noted( + response( + StatusCode::TOO_MANY_REQUESTS, + "adapter.job.hook-rate-limited", + Some(retry_after.as_secs_f64().ceil().max(1.0) as u64), + ), + FailedCheck::RateLimit, ); } let discarded = tokio::select! { @@ -532,17 +550,23 @@ async fn answer_hook( } } -fn authenticated(headers: &HeaderMap, credential: &BasicCredential) -> bool { +fn authenticated(headers: &HeaderMap, credential: &BasicCredential) -> Result<(), FailedCheck> { let mut values = headers.get_all(AUTHORIZATION).iter(); let Some(value) = values.next() else { - return false; + return Err(FailedCheck::CredentialMissing); }; if values.next().is_some() { - return false; + return Err(FailedCheck::CredentialMalformed); } credential.authenticates(value.as_bytes()) } +/// Mark a response as the refusal of `check`, for the ingress to record. +fn noted(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum HookRefusal { BodyTooLarge, @@ -801,7 +825,7 @@ mod tests { "Basic {}", STANDARD.encode(b"kobo-webhook:correct horse battery staple") ); - assert!(credential.authenticates(exact.as_bytes())); + assert_eq!(credential.authenticates(exact.as_bytes()), Ok(())); for refused in [ String::new(), "Bearer token".to_string(), @@ -812,7 +836,10 @@ mod tests { STANDARD.encode(b"wrong:correct horse battery staple") ), ] { - assert!(!credential.authenticates(refused.as_bytes()), "{refused:?}"); + assert!( + credential.authenticates(refused.as_bytes()).is_err(), + "{refused:?}" + ); } assert_eq!(format!("{credential:?}"), "BasicCredential([REDACTED])"); } @@ -1104,6 +1131,82 @@ mod tests { ); } + #[tokio::test] + async fn each_refused_credential_is_counted_under_its_check_with_an_unchanged_answer() { + let (root, resolver) = secret_resolver(); + let source = Arc::new(HookSource { + credential: BasicCredential::resolve("kobo-submissions", &source_config(), &resolver) + .expect("the credential resolves"), + limiter: TokenBucketLimiter::new(TokenBucketConfig { + requests_per_minute: 60, + burst: 1, + }) + .expect("a bounded rate limit"), + }); + let metrics = Arc::new(JobMetrics::default()); + let state = IngressState { + sources: Arc::new(BTreeMap::from([("/hooks/kobo".to_string(), source)])), + gate: Arc::new(HookPassGate::default()), + metrics: Arc::clone(&metrics), + }; + let send = |headers: Vec| { + let mut request = Request::builder().method(Method::POST).uri("/hooks/kobo"); + for value in headers { + request = request.header(AUTHORIZATION, value); + } + receive_hook_until( + State(state.clone()), + request.body(Body::empty()).expect("a hook request"), + std::future::pending(), + ) + }; + let password = + std::fs::read_to_string(root.path().join("password")).expect("the synthetic password"); + let good = basic_header(&password); + let wrong = basic_header(&uuid::Uuid::new_v4().to_string()); + let unauthenticated = [ + (vec![], "credential-missing"), + (vec!["Bearer token".to_string()], "credential-missing"), + (vec![good.clone(), good.clone()], "credential-malformed"), + (vec!["Basic !!!".to_string()], "credential-malformed"), + (vec![wrong], "shared-secret"), + ]; + for (headers, check) in &unauthenticated { + let answer = send(headers.clone()).await; + assert_eq!(answer.status(), StatusCode::UNAUTHORIZED, "{check}"); + assert_eq!( + answer.headers().get(WWW_AUTHENTICATE), + Some(&HeaderValue::from_static( + "Basic realm=\"adapter-job-hook\", charset=\"UTF-8\"" + )) + ); + let body = axum::body::to_bytes(answer.into_body(), 1024) + .await + .expect("a static body"); + assert_eq!(&body[..], br#"{"code":"adapter.job.hook-unauthenticated"}"#); + } + assert_eq!( + send(vec![good.clone()]).await.status(), + StatusCode::ACCEPTED + ); + let limited = send(vec![good]).await; + assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS); + assert!(limited.headers().contains_key(RETRY_AFTER)); + let text = metrics.render(None); + let counted = |check: &str| { + let line = format!("adapter_job_request_refusals_total{{check=\"{check}\"}}"); + text.lines() + .find_map(|found| found.strip_prefix(&format!("{line} "))) + .unwrap_or_else(|| panic!("{check} is declared: {text}")) + .to_owned() + }; + assert_eq!(counted("credential-missing"), "2"); + assert_eq!(counted("credential-malformed"), "2"); + assert_eq!(counted("shared-secret"), "1"); + assert_eq!(counted("rate-limit"), "1"); + assert_eq!(counted("scope"), "0"); + } + #[test] fn every_refusal_status_maps_to_its_own_counted_reason() { let table = [ diff --git a/crates/registry-adapter-job/src/metrics.rs b/crates/registry-adapter-job/src/metrics.rs index d4e6d054ad..d5569c5122 100644 --- a/crates/registry-adapter-job/src/metrics.rs +++ b/crates/registry-adapter-job/src/metrics.rs @@ -74,6 +74,8 @@ pub const HOOK_REFUSALS: [&str; 8] = [ ]; pub struct JobMetrics { + #[cfg(feature = "job-hook")] + refusals: registry_platform_authcommon::RefusalRecorder, pass_failures: CounterVec, hook_refusals: CounterVec, sample_failures: CounterVec, @@ -99,6 +101,9 @@ impl Default for JobMetrics { let failures = singles(&PASS_FAILURES); let refusals = singles(&HOOK_REFUSALS); Self { + #[cfg(feature = "job-hook")] + refusals: registry_platform_authcommon::RefusalRecorder::new("adapter_job") + .expect(DECLARATION), pass_failures: CounterVec::new( "adapter_job_pass_failures_total", "Loop passes that did not settle their page, by reason.", @@ -158,6 +163,13 @@ impl JobMetrics { count(&self.hook_refusals, &[reason]); } + /// The recorder behind `adapter_job_request_refusals_total` and the + /// `request refused` log line of the hook ingress. + #[cfg(feature = "job-hook")] + pub(crate) fn refusals(&self) -> ®istry_platform_authcommon::RefusalRecorder { + &self.refusals + } + /// Count one scrape whose item counts could not be read. pub fn record_sample_failure(&self) { count(&self.sample_failures, &[]); @@ -176,6 +188,8 @@ impl JobMetrics { ] { counter.write(&mut out).expect(DECLARATION); } + #[cfg(feature = "job-hook")] + self.refusals.counter().write(&mut out).expect(DECLARATION); out.header( "adapter_job_items", Some("Items in the job store by state, sampled at scrape. Absent when the store could not be read."), diff --git a/crates/registry-adapter-job/src/postgres_source.rs b/crates/registry-adapter-job/src/postgres_source.rs index 998b94e0d1..86f73109b0 100644 --- a/crates/registry-adapter-job/src/postgres_source.rs +++ b/crates/registry-adapter-job/src/postgres_source.rs @@ -9,7 +9,6 @@ use std::collections::BTreeMap; use std::fmt; #[cfg(feature = "postgres-test")] -use std::net::IpAddr; use std::sync::Arc; use std::time::Duration; @@ -228,10 +227,8 @@ impl PooledPostgresSource { } #[cfg(feature = "postgres-test")] PostgresSourceTls::Plaintext => { - let loopback = binding - .host - .parse::() - .is_ok_and(|address| address.is_loopback()); + let loopback = + registry_platform_loopback::loopback_literal(&binding.host).is_some(); if !loopback { return Err(format!( "the plaintext PostgreSQL test source {endpoint} is not numeric loopback; correct {}", diff --git a/crates/registry-adapter-job/src/rabbitmq_source.rs b/crates/registry-adapter-job/src/rabbitmq_source.rs index 25c1eb8c21..afec2f649c 100644 --- a/crates/registry-adapter-job/src/rabbitmq_source.rs +++ b/crates/registry-adapter-job/src/rabbitmq_source.rs @@ -44,8 +44,6 @@ use std::fmt; use std::future::Future; -#[cfg(feature = "rabbitmq-test-plaintext")] -use std::net::IpAddr; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; @@ -320,10 +318,7 @@ impl LapinRabbitMqSource { } #[cfg(feature = "rabbitmq-test-plaintext")] if matches!(config.tls, RabbitMqTls::PlaintextTest) - && !config - .host - .parse::() - .is_ok_and(|address| address.is_loopback()) + && registry_platform_loopback::loopback_literal(&config.host).is_none() { return Err(RabbitMqReadFault::InvalidBounds); } diff --git a/crates/registry-adapter-job/tests/job_file_host.rs b/crates/registry-adapter-job/tests/job_file_host.rs index f0040f11ee..e38ffc8cc9 100644 --- a/crates/registry-adapter-job/tests/job_file_host.rs +++ b/crates/registry-adapter-job/tests/job_file_host.rs @@ -249,6 +249,44 @@ fn the_actual_check_accepts_a_file_source_when_the_host_feature_is_present() { assert_eq!(report["source"]["route"], "kobo-submissions"); } +/// The check's findings: standard output and error together. +fn check_findings(fixture: &FileFixture) -> String { + let output = run_check(fixture); + format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) +} + +#[cfg(feature = "signed-coordinator-event")] +#[test] +fn a_named_plain_http_endpoint_needs_a_declared_private_range() { + let fixture = FileFixture::new("csv", "file", 1_048_576); + let declared = std::fs::read_to_string(&fixture.runtime).expect("the runtime config"); + let named = declared.replace( + "https://cases.example.invalid", + "http://cases.internal.example", + ); + assert_ne!(named, declared, "the fixture names an https endpoint"); + let empty = named.replace( + "\"allowedPrivateCidrs\": [\n \"10.0.0.0/8\"\n ]", + "\"allowedPrivateCidrs\": []", + ); + assert_ne!(empty, named, "the fixture declares one private range"); + + std::fs::write(&fixture.runtime, &empty).expect("the runtime config"); + assert!( + check_findings(&fixture).contains("adapter.runtime.insecure-origin"), + "an empty list admits no private address" + ); + std::fs::write(&fixture.runtime, &named).expect("the runtime config"); + assert!( + !check_findings(&fixture).contains("adapter.runtime.insecure-origin"), + "a declared range admits the named host" + ); +} + #[tokio::test] async fn csv_and_jsonl_values_cross_the_existing_destination_seam() { let cases = [ diff --git a/crates/registry-adapter/Cargo.toml b/crates/registry-adapter/Cargo.toml index 539dfdfdb8..798c1b2166 100644 --- a/crates/registry-adapter/Cargo.toml +++ b/crates/registry-adapter/Cargo.toml @@ -81,7 +81,7 @@ registry-platform-yaml.workspace = true axum.workspace = true clap.workspace = true jsonwebtoken.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } rustls.workspace = true rhai.workspace = true serde.workspace = true diff --git a/crates/registry-adapter/src/facade.rs b/crates/registry-adapter/src/facade.rs index 637023a52e..4072562fca 100644 --- a/crates/registry-adapter/src/facade.rs +++ b/crates/registry-adapter/src/facade.rs @@ -68,6 +68,7 @@ use crate::idempotent::{ }; use crate::journal::{self, JournalEvent}; use crate::serve::{Authenticator, Caller, CallerRefusal}; +use registry_platform_authcommon::{FailedCheck, RefusalNote}; const REQUEST_ID_HEADER: &str = "x-registry-request-id"; const WRITE_REQUEST_DIGEST_DOMAIN: &[u8] = b"registry-adapter:write-request:v2\0"; @@ -353,6 +354,7 @@ pub fn router(state: Arc) -> Router { ); let unmatched = Arc::clone(&state); let metrics = Arc::clone(&state.metrics); + let refusals = state.metrics.refusals(); router .fallback(move |correlation: Option>| { let shared = Arc::clone(&unmatched); @@ -369,6 +371,10 @@ pub fn router(state: Arc) -> Router { ) } }) + .layer(middleware::from_fn_with_state( + refusals, + crate::metrics::record_refusals, + )) .layer(middleware::from_fn_with_state( metrics, crate::metrics::count_requests, @@ -519,6 +525,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeNotAcceptable, StatusCode::NOT_ACCEPTABLE, + None, ) .await; } @@ -545,6 +552,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeNotFound, StatusCode::NOT_FOUND, + None, ) .await; }; @@ -608,6 +616,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeNotFound, StatusCode::NOT_FOUND, + Some(FailedCheck::Visibility), ) .await; } @@ -632,7 +641,7 @@ async fn answer_async_status( &physical_request_id, ); }; - if !admits_stored( + if let Err(check) = admitted( &state.loaded.project, &caller, metadata.profile_operation(), @@ -646,6 +655,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeForbidden, StatusCode::FORBIDDEN, + Some(check), ) .await; } @@ -790,6 +800,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeNotFound, StatusCode::NOT_FOUND, + Some(FailedCheck::Visibility), ) .await; } @@ -1210,6 +1221,7 @@ async fn answer( &request_id, ErrorClass::FacadeNotAcceptable, StatusCode::NOT_ACCEPTABLE, + None, ) .await; } @@ -1222,10 +1234,16 @@ async fn answer( &request_id, ErrorClass::FacadeNotFound, StatusCode::NOT_FOUND, + None, ) .await; } - if !admits(&state.loaded.project, &caller, operation) { + if let Err(check) = admitted( + &state.loaded.project, + &caller, + operation.operation.as_str(), + operation.record_type.as_str(), + ) { return refuse_call( state, operation, @@ -1234,6 +1252,7 @@ async fn answer( &request_id, ErrorClass::FacadeForbidden, StatusCode::FORBIDDEN, + Some(check), ) .await; } @@ -1311,6 +1330,7 @@ async fn answer( &request_id, ErrorClass::FacadeUnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE, + None, ) .await; } @@ -1325,6 +1345,7 @@ async fn answer( &request_id, ErrorClass::FacadePayloadTooLarge, StatusCode::PAYLOAD_TOO_LARGE, + None, ) .await; } @@ -1495,6 +1516,7 @@ async fn answer( &request_id, ErrorClass::OutcomeNotFound, StatusCode::NOT_FOUND, + None, ) .await; } @@ -3429,71 +3451,100 @@ fn journal_fault(error: &tokio_postgres::Error) -> String { } async fn authenticate(state: &FacadeState, headers: &HeaderMap) -> Result { - let Some(token) = bearer_token(headers) else { - state.authenticator.log_header_refusal(); - return Err(CallerRefusal::Unauthenticated); - }; + let token = bearer_token(headers).map_err(CallerRefusal::Unauthenticated)?; state.authenticator.authenticate(token).await } -/// The bearer credential of the `Authorization` header, if it carries one. -fn bearer_token(headers: &HeaderMap) -> Option<&str> { - let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?; - let (scheme, token) = value.split_once(' ')?; - (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token) +/// The bearer credential of the `Authorization` header, or the check its +/// header failed: absent or another scheme is a missing credential, an +/// unreadable or empty one is a malformed credential. +fn bearer_token(headers: &HeaderMap) -> Result<&str, FailedCheck> { + let value = headers + .get(header::AUTHORIZATION) + .ok_or(FailedCheck::CredentialMissing)? + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + let Some((scheme, token)) = value.split_once(' ') else { + return Err(if value.eq_ignore_ascii_case("bearer") { + FailedCheck::CredentialMalformed + } else { + FailedCheck::CredentialMissing + }); + }; + if !scheme.eq_ignore_ascii_case("bearer") { + return Err(FailedCheck::CredentialMissing); + } + if token.is_empty() { + return Err(FailedCheck::CredentialMalformed); + } + Ok(token) +} + +/// Mark a response as the refusal of `check`, for the recording layer. +fn noted(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response } /// Whether some access profile the caller's scopes satisfy admits the /// operation on the record type. A profile that names no scope admits /// nobody: an empty requirement is not a satisfied one. fn admits(project: &AdapterProject, caller: &Caller, operation: &ServedOperation) -> bool { - project.access_profiles.iter().any(|profile| { - !profile.scopes.is_empty() - && profile - .scopes - .iter() - .all(|scope| caller.scopes.iter().any(|held| held == scope.as_str())) - && profile - .operations - .iter() - .any(|id| id.as_str() == operation.operation) - && profile - .record_types - .iter() - .any(|name| name.as_str() == operation.record_type) - }) + admitted( + project, + caller, + operation.operation.as_str(), + operation.record_type.as_str(), + ) + .is_ok() } -fn admits_stored( +/// The check a refused call failed: `Scope` when no profile's scopes are all +/// held, `Operation` when some profile is held and none names the operation +/// on the record type. +fn admitted( project: &AdapterProject, caller: &Caller, profile_operation: &str, record_type: &str, -) -> bool { - project.access_profiles.iter().any(|profile| { - !profile.scopes.is_empty() - && profile +) -> Result<(), FailedCheck> { + let mut scoped = false; + for profile in &project.access_profiles { + if profile.scopes.is_empty() + || !profile .scopes .iter() .all(|scope| caller.scopes.iter().any(|held| held == scope.as_str())) - && profile - .operations - .iter() - .any(|id| id.as_str() == profile_operation) + { + continue; + } + scoped = true; + if profile + .operations + .iter() + .any(|id| id.as_str() == profile_operation) && profile .record_types .iter() .any(|name| name.as_str() == record_type) + { + return Ok(()); + } + } + Err(if scoped { + FailedCheck::Operation + } else { + FailedCheck::Scope }) } fn refusal_response(profile: Problems<'_>, refusal: CallerRefusal, request_id: &str) -> Response { let (class, status) = match refusal { - CallerRefusal::Unauthenticated => { + CallerRefusal::Unauthenticated(_) => { (ErrorClass::FacadeUnauthenticated, StatusCode::UNAUTHORIZED) } CallerRefusal::Unavailable if profile.profile.is_govstack_consultation() => { - return consultation_unavailable(request_id); + return noted(consultation_unavailable(request_id), refusal.failed_check()); } CallerRefusal::Unavailable => (ErrorClass::Facade, StatusCode::SERVICE_UNAVAILABLE), }; @@ -3503,7 +3554,7 @@ fn refusal_response(profile: Problems<'_>, refusal: CallerRefusal, request_id: & .headers_mut() .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); } - response + noted(response, refusal.failed_check()) } /// The members of a record a route may wrap its domain fields in, beside the @@ -3775,6 +3826,9 @@ pub(crate) struct Refusal { /// maps to the fixed request member holding it. validation_pointers: Vec, detail: Option<&'static str>, + /// The check a caller refusal failed, for the operator-side counter and + /// log. `None` for a request that is merely invalid. + check: Option, } trait LoadedProblems { @@ -3816,6 +3870,7 @@ impl Refusal { write_problem: Some(code), validation_pointers: Vec::new(), detail: None, + check: None, } } @@ -3827,6 +3882,7 @@ impl Refusal { write_problem: None, validation_pointers: Vec::new(), detail: None, + check: None, } } @@ -3838,6 +3894,19 @@ impl Refusal { write_problem: None, validation_pointers: Vec::new(), detail: None, + check: None, + } + } + + /// The refusal of a cursor the codec would not open. A cursor that fails + /// authentication was tampered with or minted for another caller, + /// binding or client, and the two are one by construction, so the check + /// is `Ownership`. + fn from_cursor(refusal: CursorRefusal) -> Self { + Self { + check: matches!(refusal, CursorRefusal::Unauthenticated) + .then_some(FailedCheck::Ownership), + ..Self::invalid_cursor(refusal.reason()) } } @@ -3849,6 +3918,7 @@ impl Refusal { write_problem: None, validation_pointers: Vec::new(), detail: None, + check: None, } } } @@ -3957,7 +4027,7 @@ fn open_search( let binding = cursor_binding(state, operation, caller, filters); let sealed = codec .open(cursor, &binding, SystemTime::now()) - .map_err(|refusal: CursorRefusal| Refusal::invalid_cursor(refusal.reason()))?; + .map_err(Refusal::from_cursor)?; let (size, continuation) = unwrap_continuation(sealed).ok_or_else(|| Refusal::invalid_cursor("malformed"))?; (Some(continuation), Some(size)) @@ -4572,7 +4642,11 @@ fn seal_next( /// Answer a verified caller's refused call (403, or a record type the /// operation does not serve) after journaling it as `callRefused` with the /// class and status only. The refusal is also logged, so an operator sees it -/// without reading the journal. +/// without reading the journal. `check` names the check a caller refusal (403, +/// or a concealing 404) failed, for the operator-side counter and log; it is +/// `None` for an answer that is not a refusal of the caller, such as an +/// unsupported media type. +#[allow(clippy::too_many_arguments)] async fn refuse_call( state: &FacadeState, operation: &ServedOperation, @@ -4581,6 +4655,7 @@ async fn refuse_call( request_id: &str, class: ErrorClass, status: StatusCode, + check: Option, ) -> Response { let profile = state.loaded.problems(); tracing::warn!( @@ -4606,7 +4681,11 @@ async fn refuse_call( request_id, ); } - facade_problem(profile, class, status, record_type, request_id) + let response = facade_problem(profile, class, status, record_type, request_id); + match check { + Some(check) => noted(response, check), + None => response, + } } /// Refuse a verified and admitted call whose supplied whole-contract pin is @@ -4807,7 +4886,7 @@ async fn refuse_request( ) }; let mut failure = exchange_failure_detail(profile, refusal.class); - failure["reason"] = Value::String(refusal.reason); + failure["reason"] = Value::String(refusal.reason.clone()); if operation.write_support.is_some() { let code = refusal.write_problem.or_else(|| { (refusal.status == StatusCode::UNPROCESSABLE_ENTITY).then_some("invalid-content") @@ -4834,6 +4913,22 @@ async fn refuse_request( ); } warn_exchange_failed(refusal.class, refusal.status); + let check = refusal.check; + let response = refusal_answer(profile, operation, record_type, request_id, &refusal); + match check { + Some(check) => noted(response, check), + None => response, + } +} + +/// The answer a refused request gets, rendered from its class and status. +fn refusal_answer( + profile: Problems<'_>, + operation: &ServedOperation, + record_type: &str, + request_id: &str, + refusal: &Refusal, +) -> Response { if let Some(code) = refusal.write_problem { return govstack_problem(code, refusal.status, request_id); } @@ -5761,6 +5856,88 @@ mod tests { assert!(!admits(&example_project(json!([])), &caller, &operation)); } + #[test] + fn a_refused_call_names_the_check_it_failed() { + let caller = Caller { + reference: "caller".to_owned(), + issuer: "https://issuer.example.invalid".to_owned(), + client_id: "case-portal".to_owned(), + scopes: vec!["records.read".to_owned()], + }; + let project = example_project(json!(["records.read"])); + assert_eq!(admitted(&project, &caller, "records-get", "person"), Ok(())); + // The caller holds the profile's scope but the profile names no such + // operation or record type. + assert_eq!( + admitted(&project, &caller, "records-purge", "person"), + Err(FailedCheck::Operation) + ); + assert_eq!( + admitted(&project, &caller, "records-get", "household"), + Err(FailedCheck::Operation) + ); + // No profile's scopes are all held, and a profile with no scope + // admits nobody. + let stranger = Caller { + scopes: vec!["other.scope".to_owned()], + ..caller + }; + assert_eq!( + admitted(&project, &stranger, "records-get", "person"), + Err(FailedCheck::Scope) + ); + assert_eq!( + admitted( + &example_project(json!([])), + &stranger, + "records-get", + "person" + ), + Err(FailedCheck::Scope) + ); + } + + #[test] + fn a_bearer_header_names_the_check_it_failed() { + let with = |value: Option<&str>| { + let mut headers = HeaderMap::new(); + if let Some(value) = value { + headers.insert( + header::AUTHORIZATION, + HeaderValue::from_str(value).expect("a header value"), + ); + } + headers + }; + assert_eq!(bearer_token(&with(Some("Bearer abc"))), Ok("abc")); + assert_eq!(bearer_token(&with(Some("bearer abc"))), Ok("abc")); + assert_eq!( + bearer_token(&with(None)), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + bearer_token(&with(Some("Basic YWJj"))), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + bearer_token(&with(Some("Bearer"))), + Err(FailedCheck::CredentialMalformed) + ); + assert_eq!( + bearer_token(&with(Some("Bearer "))), + Err(FailedCheck::CredentialMalformed) + ); + let mut unreadable = HeaderMap::new(); + unreadable.insert( + header::AUTHORIZATION, + HeaderValue::from_bytes(b"Bearer \xff").expect("opaque bytes"), + ); + assert_eq!( + bearer_token(&unreadable), + Err(FailedCheck::CredentialMalformed) + ); + } + fn person_schema() -> Value { json!({ "type": "object", diff --git a/crates/registry-adapter/src/metrics.rs b/crates/registry-adapter/src/metrics.rs index 2eba64ebf6..24269f5d15 100644 --- a/crates/registry-adapter/src/metrics.rs +++ b/crates/registry-adapter/src/metrics.rs @@ -21,7 +21,7 @@ use std::fmt; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use axum::extract::{MatchedPath, State}; use axum::http::header::CONTENT_TYPE; @@ -31,6 +31,7 @@ use axum::response::{IntoResponse, Response}; use axum::routing::get; use axum::Router; use registry_adapter_core::ErrorClass; +use registry_platform_authcommon::{RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, CONTENT_TYPE as METRICS_CONTENT_TYPE, }; @@ -68,7 +69,20 @@ const UPSTREAM_CLASSES: [ErrorClass; 11] = [ /// `adapter_retention_sweep_failures_total`. const SWEEP_STORES: [&str; 3] = ["journal", "idempotency", "other"]; +/// The process's refusal recorder: one counter and one log budget for every +/// listener of this process, the facade and the payment routes alike. +static REFUSALS: OnceLock> = OnceLock::new(); + +/// The recorder behind `adapter_request_refusals_total` and the +/// `request refused` log line. +pub fn refusal_recorder() -> Arc { + Arc::clone( + REFUSALS.get_or_init(|| Arc::new(RefusalRecorder::new("adapter").expect(DECLARATION))), + ) +} + pub struct Metrics { + refusals: Arc, requests: CounterVec, upstream_failures: CounterVec, journal_write_failures: CounterVec, @@ -88,6 +102,7 @@ impl Default for Metrics { let sweep: Vec<[&str; 1]> = SWEEP_STORES.iter().map(|s| [*s]).collect(); let sweep: Vec<&[&str]> = sweep.iter().map(|s| s.as_slice()).collect(); Self { + refusals: refusal_recorder(), requests: CounterVec::new( "adapter_http_requests_total", "Answered facade HTTP requests, by route template, method, and status class.", @@ -118,6 +133,12 @@ impl Default for Metrics { } impl Metrics { + /// The recorder that counts and logs every refused request. + #[must_use] + pub fn refusals(&self) -> Arc { + Arc::clone(&self.refusals) + } + /// Count one answered request under its closed labels. pub fn record_request(&self, route: &str, method: &Method, status: StatusCode) { count( @@ -158,6 +179,7 @@ impl Metrics { &self.upstream_failures, &self.journal_write_failures, &self.sweep_failures, + self.refusals.counter(), ] { counter.write(&mut out).expect(DECLARATION); } @@ -222,6 +244,21 @@ pub async fn count_requests( response } +/// Count and log every refused request once, under the check its answer +/// carries in the response extensions. The extension is not serialized, so +/// no byte of the answer depends on it. +pub async fn record_refusals( + State(recorder): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::() { + registry_platform_authcommon::record_refusal!(recorder, *note); + } + response +} + /// The router the metrics listener serves: the counters and nothing else. pub fn metrics_router(metrics: Arc) -> Router { Router::new() @@ -353,6 +390,16 @@ mod tests { )); } + #[test] + fn the_refusal_counter_declares_every_check_and_publishes_it_at_zero() { + let text = Metrics::default().render(); + let declared = text + .lines() + .filter(|line| line.starts_with("adapter_request_refusals_total{check=\"")) + .count(); + assert_eq!(declared, registry_platform_authcommon::FailedCheck::COUNT); + } + fn text_has(metrics: &Metrics, line: &str) -> bool { metrics.render().lines().any(|found| found == line) } diff --git a/crates/registry-adapter/src/payments/g2p_model.rs b/crates/registry-adapter/src/payments/g2p_model.rs index d78c7d15ee..5afb0df99f 100644 --- a/crates/registry-adapter/src/payments/g2p_model.rs +++ b/crates/registry-adapter/src/payments/g2p_model.rs @@ -14,6 +14,7 @@ use super::{ }, }; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use registry_platform_httputil::loopback::loopback_address; use registry_platform_yaml::SecretReference; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; @@ -1070,9 +1071,11 @@ fn provider_base_url(value: &str) -> bool { if url.scheme() != "http" { return false; } + // An address literal only: the name `localhost` is refused here, where + // no resolved address is available to pin it. match url.host() { - Some(url::Host::Ipv4(address)) => address.is_loopback(), - Some(url::Host::Ipv6(address)) => address.is_loopback(), + Some(url::Host::Ipv4(address)) => loopback_address(address.into()), + Some(url::Host::Ipv6(address)) => loopback_address(address.into()), Some(url::Host::Domain(_)) | None => false, } } @@ -1156,3 +1159,26 @@ fn currency_scale<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result::deserialize(deserializer) .map(|value| u8::try_from(value.get()).expect("the bounded scale fits in u8")) } + +#[cfg(test)] +mod tests { + use super::provider_base_url; + + #[test] + fn a_plain_http_provider_must_be_a_loopback_address_literal() { + for accepted in [ + "http://127.0.0.1/", + "http://[::1]/", + "https://provider.example/", + ] { + assert!(provider_base_url(accepted), "{accepted}"); + } + for refused in [ + "http://localhost/", + "http://10.0.0.1/", + "http://provider.example/", + ] { + assert!(!provider_base_url(refused), "{refused}"); + } + } +} diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index e8e11c1a6e..88e2baff34 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -14,7 +14,7 @@ use super::{ }, provider_mapping::{PaymentMappingProgram, PaymentMappingRegistry}, registry::BregBridge, - service::{PaymentService, SyntheticProvider}, + service::{PaymentFailure, PaymentService, SyntheticProvider}, store::{migrate, PaymentStore}, }; use crate::serve::{Authenticator, Caller, CallerRefusal, ServeError}; @@ -22,6 +22,7 @@ use axum::{ body::Bytes, extract::{DefaultBodyLimit, Path as RoutePath, State}, http::{HeaderMap, HeaderValue, StatusCode, Uri}, + middleware, response::{IntoResponse, Response}, routing::{get, post}, Json, Router, @@ -32,6 +33,7 @@ use registry_payment_protocol::{ PaymentProblem, PaymentProblemCode as Error, ProviderConfirmation, RecordProviderConfirmation, RecordReceipt, RequestCollection, RequestDisbursement, }; +use registry_platform_authcommon::{FailedCheck, RefusalNote}; use registry_platform_config::{ RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, SecretResolver, }; @@ -411,7 +413,13 @@ impl PreparedPayments { g2p, disbursements, }); - Ok(Router::new() + Ok(payment_router(state)) + } +} + +/// The payment routes over `state`, with the refusal recording layer. +fn payment_router(state: Arc) -> Router { + Router::new() .route("/v1/payments/{connection}/collections", post(request)) .route( "/v1/payments/{connection}/collections/receipt", @@ -442,8 +450,11 @@ impl PreparedPayments { post(record_provider_confirmation), ) .layer(DefaultBodyLimit::max(MAX_PAYMENT_BODY_BYTES)) - .with_state(state)) - } + .layer(middleware::from_fn_with_state( + crate::metrics::refusal_recorder(), + crate::metrics::record_refusals, + )) + .with_state(state) } pub async fn run_only( @@ -488,28 +499,46 @@ pub async fn run_only( } 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))?; + let mut values = headers.get_all("authorization").iter(); + let value = match (values.next(), values.next()) { + (Some(value), None) => value.to_str().ok(), + (None, _) => { + return Err(HttpError::refused( + Error::Unauthenticated, + FailedCheck::CredentialMissing, + )) + } + _ => None, + } + .ok_or(HttpError::refused( + Error::Unauthenticated, + FailedCheck::CredentialMalformed, + ))?; + let bearer = value.strip_prefix("Bearer ").ok_or(HttpError::refused( + Error::Unauthenticated, + FailedCheck::CredentialMissing, + ))?; state .authenticator .authenticate(bearer) .await - .map_err(|error| { - HttpError(match error { - CallerRefusal::Unauthenticated => Error::Unauthenticated, - CallerRefusal::Unavailable => Error::Unavailable, - }) + .map_err(|error| match error { + CallerRefusal::Unauthenticated(_) => { + HttpError::refused(Error::Unauthenticated, error.failed_check()) + } + CallerRefusal::Unavailable => { + HttpError::refused(Error::Unavailable, FailedCheck::KeySourceUnavailable) + } }) } 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)), + (Some(value), None) => value + .to_str() + .map_err(|_| HttpError::plain(Error::InvalidRequest)), + _ => Err(HttpError::plain(Error::InvalidRequest)), } } fn body(headers: &HeaderMap, uri: &Uri, bytes: &[u8]) -> Result { @@ -517,24 +546,25 @@ fn body(headers: &HeaderMap, uri: &Uri, bytes: &[u8]) -> Re || uri.query().is_some() || single_header(headers, "content-type")? != "application/json" { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(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)); + return Err(HttpError::plain(Error::InvalidRequest)); } let mut decoder = serde_json::Deserializer::from_slice(bytes); - let request = T::deserialize(&mut decoder).map_err(|_| HttpError(Error::InvalidRequest))?; + let request = + T::deserialize(&mut decoder).map_err(|_| HttpError::plain(Error::InvalidRequest))?; decoder .end() - .map_err(|_| HttpError(Error::InvalidRequest))?; + .map_err(|_| HttpError::plain(Error::InvalidRequest))?; Ok(request) } fn collection(value: &str) -> Result { Uuid::parse_str(value) .ok() .filter(|id| !id.is_nil()) - .ok_or(HttpError(Error::InvalidRequest)) + .ok_or(HttpError::plain(Error::InvalidRequest)) } async fn request( @@ -596,7 +626,7 @@ async fn read( ) -> Result { let caller = caller(&state, &headers).await?; if uri.query().is_some() || !bytes.is_empty() { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } let id = collection(&id)?; let result = state.service.read(&connection, &caller, id).await; @@ -622,7 +652,7 @@ async fn record_receipt( let id = collection(&id)?; let request: RecordReceipt = body(&headers, &uri, &bytes)?; if request.collection_id != id { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } let key = single_header(&headers, "idempotency-key")?; let result = state @@ -651,39 +681,45 @@ async fn g2p_connection<'a>( .disbursements .iter() .find(|entry| entry.id == id) - .ok_or(Error::NotFound) + .ok_or(PaymentFailure::concealing(Error::NotFound)) .and_then(|connection| { - if !connection.allowed_clients.contains(&caller.client_id) - || !caller.scopes.contains(&connection.required_scope) - { - Err(Error::Forbidden) + if !connection.allowed_clients.contains(&caller.client_id) { + Err(PaymentFailure::refused( + Error::Forbidden, + FailedCheck::RequesterClient, + )) + } else if !caller.scopes.contains(&connection.required_scope) { + Err(PaymentFailure::refused( + Error::Forbidden, + FailedCheck::Scope, + )) } else { Ok(connection) } }); - if let Err(error) = selected { + if let Err(failure) = &selected { state .service - .audit_access(caller, operation, None, Some(error)) + .audit_access(caller, operation, None, Some(failure.code)) .await - .map_err(|_| HttpError(Error::Unavailable))?; + .map_err(|_| HttpError::plain(Error::Unavailable))?; } - selected.map_err(HttpError) + selected.map_err(HttpError::from) } fn g2p_principal(caller: &Caller) -> Result { super::model::digest(&[&caller.issuer, &caller.client_id, &caller.reference]) } -fn g2p_error(error: G2pError) -> Error { - match error { +fn g2p_error(error: G2pError) -> PaymentFailure { + PaymentFailure::concealing(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 { @@ -754,17 +790,17 @@ async fn request_disbursement( let request: RequestDisbursement = body(&headers, &uri, &bytes)?; request .validate() - .map_err(|_| HttpError(Error::InvalidRequest))?; + .map_err(|_| HttpError::plain(Error::InvalidRequest))?; let key = single_header(&headers, "idempotency-key")?; if !super::config::text(key, 128) { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(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)?, + &g2p_principal(&caller).map_err(HttpError::plain)?, key, request.instruction_record_id, request.instruction_version, @@ -773,7 +809,7 @@ async fn request_disbursement( ) .await .map_err(g2p_error) - .and_then(|attempt| disbursement_accepted(&attempt)); + .and_then(|attempt| disbursement_accepted(&attempt).map_err(PaymentFailure::from)); finish( &state, &caller, @@ -797,24 +833,24 @@ async fn disbursement_receipt( let request: RequestDisbursement = body(&headers, &uri, &bytes)?; request .validate() - .map_err(|_| HttpError(Error::InvalidRequest))?; + .map_err(|_| HttpError::plain(Error::InvalidRequest))?; let key = single_header(&headers, "idempotency-key")?; if !super::config::text(key, 128) { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } g2p_connection(&state, &connection, &caller, "request-disbursement-receipt").await?; let result = state .g2p .request_receipt( &connection, - &g2p_principal(&caller).map_err(HttpError)?, + &g2p_principal(&caller).map_err(HttpError::plain)?, key, request.instruction_record_id, request.instruction_version, ) .await .map_err(g2p_error) - .and_then(|attempt| disbursement_accepted(&attempt)); + .and_then(|attempt| disbursement_accepted(&attempt).map_err(PaymentFailure::from)); finish( &state, &caller, @@ -836,16 +872,20 @@ async fn read_disbursement( ) -> Result { let caller = caller(&state, &headers).await?; if uri.query().is_some() || !bytes.is_empty() { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(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) + .disbursement_status( + &connection, + &g2p_principal(&caller).map_err(HttpError::plain)?, + id, + ) .await .map_err(g2p_error) - .and_then(|attempt| disbursement_status(&attempt)); + .and_then(|attempt| disbursement_status(&attempt).map_err(PaymentFailure::from)); finish( &state, &caller, @@ -869,26 +909,26 @@ async fn record_provider_confirmation( let id = collection(&id)?; let request: RecordProviderConfirmation = body(&headers, &uri, &bytes)?; if request.disbursement_id != id { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } let key = single_header(&headers, "idempotency-key")?; if !super::config::text(key, 128) { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(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)?, + &g2p_principal(&caller).map_err(HttpError::plain)?, key, id, ) .await .map_err(g2p_error) - .and_then(|attempt| { + .and_then(|attempt| -> Result<_, PaymentFailure> { if attempt.state != G2pAttemptState::ConfirmationRecorded { - return Err(Error::RecoveryHeld); + return Err(Error::RecoveryHeld.into()); } let status = disbursement_status(&attempt)?; let confirmation = ProviderConfirmation { @@ -925,14 +965,19 @@ async fn finish( id: Option, mutation: bool, status: StatusCode, - result: Result, + result: Result, ) -> Result { state .service - .audit_access(caller, operation, id, result.as_ref().err().copied()) + .audit_access( + caller, + operation, + id, + result.as_ref().err().map(|failure| failure.code), + ) .await .map_err(|_| { - HttpError(if mutation { + HttpError::plain(if mutation { Error::OutcomeUnknown } else { Error::Unavailable @@ -940,7 +985,7 @@ async fn finish( })?; result .map(|value| headers((status, Json(value)).into_response())) - .map_err(HttpError) + .map_err(HttpError::from) } /// The attempt an accepted request names, recorded in its audit event. @@ -957,14 +1002,37 @@ impl AuditedAttempt for DisbursementAccepted { self.disbursement_id } } -fn audited_attempt(result: &Result) -> Option { +fn audited_attempt(result: &Result) -> Option { result.as_ref().ok().map(AuditedAttempt::attempt_id) } -struct HttpError(Error); +/// A payment error with, for a refused caller, the check it failed. +struct HttpError { + code: Error, + check: Option, +} +impl HttpError { + fn plain(code: Error) -> Self { + Self { code, check: None } + } + fn refused(code: Error, check: FailedCheck) -> Self { + Self { + code, + check: Some(check), + } + } +} +impl From for HttpError { + fn from(failure: PaymentFailure) -> Self { + Self { + code: failure.code, + check: failure.check, + } + } +} impl IntoResponse for HttpError { fn into_response(self) -> Response { - let problem = PaymentProblem::from(self.0); + let problem = PaymentProblem::from(self.code); let status = StatusCode::from_u16(problem.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); let mut response = (status, Json(problem)).into_response(); @@ -972,6 +1040,9 @@ impl IntoResponse for HttpError { "content-type", HeaderValue::from_static("application/problem+json"), ); + if let Some(check) = self.check { + response.extensions_mut().insert(RefusalNote::new(check)); + } headers(response) } } @@ -998,6 +1069,9 @@ fn refused(message: &str) -> ServeError { ServeError::Configuration(format!("adapter.payment.configuration: {message}")) } +#[cfg(all(test, feature = "postgres-test"))] +mod refusal_tests; + #[cfg(test)] mod tests { use super::*; @@ -1030,7 +1104,10 @@ mod tests { assert!( matches!( body::(&headers, &uri, invalid.as_bytes()), - Err(HttpError(Error::InvalidRequest)) + Err(HttpError { + code: Error::InvalidRequest, + .. + }) ), "unexpected result for {invalid}" ); @@ -1042,7 +1119,10 @@ mod tests { at_limit.push(b' '); assert!(matches!( body::(&headers, &uri, &at_limit), - Err(HttpError(Error::InvalidRequest)) + Err(HttpError { + code: Error::InvalidRequest, + .. + }) )); } @@ -1064,15 +1144,15 @@ mod tests { simulation: false, }; assert_eq!( - audited_attempt(&Ok(collection.clone())), + audited_attempt::<_, Error>(&Ok(collection.clone())), Some(collection.collection_id) ); assert_eq!( - audited_attempt(&Ok(disbursement.clone())), + audited_attempt::<_, Error>(&Ok(disbursement.clone())), Some(disbursement.disbursement_id) ); assert_eq!( - audited_attempt::(&Err(Error::OutcomeUnknown)), + audited_attempt::(&Err(Error::OutcomeUnknown)), None ); } diff --git a/crates/registry-adapter/src/payments/http/refusal_tests.rs b/crates/registry-adapter/src/payments/http/refusal_tests.rs new file mode 100644 index 0000000000..0bbde657ba --- /dev/null +++ b/crates/registry-adapter/src/payments/http/refusal_tests.rs @@ -0,0 +1,393 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Every refusal of a payment caller, through the real routes over a real +//! journal: the answer is frozen against a checked-in golden file (status, +//! the fixed headers and the body), and the refusal counter rises by one under +//! the check that refused. +//! +//! `ADAPTER_WRITE_GOLDEN=1` rewrites the golden file. Without it the answers +//! are compared to the file. Needs `ADAPTER_TEST_DATABASE_URL`; without it the +//! test fails on the spot. +use super::*; +use registry_platform_config::SecretProvider; +use registry_platform_testing::{ + access_token_test_key, jwks_from_private_jwk, sign_compact_jwt_with_key, +}; +use serde_json::{json, Value}; +use std::time::{SystemTime, UNIX_EPOCH}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "registry-adapter-test"; +const GOLDEN: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/golden/payment_refusals.json" +); + +fn runtime() -> AdapterRuntimeConfig { + serde_json::from_value(json!({ + "id": "payment-refusals", + "endpoints": [{"endpoint": "tracker", "baseUrl": "https://tracker.example.invalid"}], + "listener": {"bind": "127.0.0.1:8080"}, + "database": { + "runtimeUrlRef": "secret:file/database-runtime", + "migrationUrlRef": "secret:file/database-migration" + }, + "oidc": { + "issuer": ISSUER, + "audience": AUDIENCE, + "jwksSource": {"type": "static", "documentRef": "secret:file/issuer-keys.json"} + }, + "allowedClients": ["coordinator", "other"], + "allowedPrivateCidrs": ["10.0.0.0/8"], + "audit": {"retentionDays": 90} + })) + .expect("the runtime configuration parses") +} + +fn payments() -> 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":{"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"} + }}]})) + .expect("the payment configuration parses") +} + +fn token( + key: ®istry_platform_crypto::PrivateJwk, + client: &str, + scope: &str, + exp: u64, +) -> String { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("epoch") + .as_secs(); + sign_compact_jwt_with_key( + key, + "at+jwt", + "canary-resource-key", + json!({ + "iss": ISSUER, "aud": AUDIENCE, "sub": "workflow-service", "client_id": client, + "scope": scope, "iat": now, "nbf": now, "exp": exp, + "jti": Uuid::new_v4().to_string(), + }), + ) +} + +/// One request over a fresh connection: status, head, JSON body. +async fn send( + port: u16, + method: &str, + path: &str, + authorization: &[&str], + body: Option<&Value>, +) -> (u16, String, Value) { + let mut request = + format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"); + for value in authorization { + request.push_str(&format!("Authorization: {value}\r\n")); + } + let payload = body.map(Value::to_string).unwrap_or_default(); + if body.is_some() { + request.push_str(&format!( + "Content-Type: application/json\r\nIdempotency-Key: key-1\r\nContent-Length: {}\r\n", + payload.len() + )); + } + request.push_str("\r\n"); + request.push_str(&payload); + let mut stream = TcpStream::connect(("127.0.0.1", port)) + .await + .expect("connect the payment router"); + stream + .write_all(request.as_bytes()) + .await + .expect("write the request"); + let mut raw = String::new(); + stream + .read_to_string(&mut raw) + .await + .expect("read the answer"); + let (head, body) = raw.split_once("\r\n\r\n").expect("a header block"); + let status = head + .split_whitespace() + .nth(1) + .and_then(|code| code.parse().ok()) + .expect("a status line"); + ( + status, + head.to_owned(), + serde_json::from_str(body).unwrap_or(Value::Null), + ) +} + +/// A case: name, check, method, path, authorization headers, body. +type Case<'a> = ( + &'a str, + &'a str, + &'a str, + String, + Vec, + Option<&'a Value>, +); + +fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> { + head.lines().skip(1).find_map(|line| { + let (candidate, value) = line.split_once(':')?; + candidate.eq_ignore_ascii_case(name).then(|| value.trim()) + }) +} + +fn frozen(status: u16, head: &str, body: &Value) -> Value { + let mut body = body.clone(); + if let Some(object) = body.as_object_mut() { + for member in ["traceId", "requestId"] { + if object.contains_key(member) { + object.insert(member.to_owned(), json!("")); + } + } + } + json!({ + "status": status, + "content-type": header(head, "content-type"), + "www-authenticate": header(head, "www-authenticate"), + "retry-after": header(head, "retry-after"), + "cache-control": header(head, "cache-control"), + "x-content-type-options": header(head, "x-content-type-options"), + "traceparent-present": header(head, "traceparent").is_some(), + "body": body, + }) +} + +#[tokio::test] +async fn every_payment_refusal_keeps_its_answer_and_is_counted_under_its_check() { + let signing_key = access_token_test_key(jsonwebtoken::Algorithm::ES256); + let directory = tempfile::tempdir().expect("a scratch directory"); + let root = directory.path().canonicalize().expect("physical directory"); + let key_file = root.join("issuer-keys.json"); + std::fs::write(&key_file, jwks_from_private_jwk(&signing_key).to_string()) + .expect("write the key set"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + } + let resolver = Arc::new(SecretResolver::new([SecretProvider::File], root).expect("resolver")); + let authenticator = crate::serve::authenticator(&runtime(), &resolver) + .await + .expect("the authenticator builds over the static key set"); + + 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().expect("a database url"), + tokio_postgres::NoTls, + ); + let pool = deadpool_postgres::Pool::builder(manager) + .max_size(8) + .build() + .expect("a pool"); + { + let mut client = pool.get().await.expect("a connection"); + migrate(&mut client).await.expect("the payment tables"); + } + let deployment = format!("payment-refusals-{}", Uuid::new_v4()); + let service = PaymentService::new( + payments(), + PaymentStore::new(pool.clone(), deployment.clone()), + Arc::new(BregBridge::new(resolver.clone())), + Arc::new(SyntheticProvider::new(resolver.clone(), None)), + ) + .expect("the payment service"); + let g2p = G2pService::new( + G2pStore::new(pool, deployment), + Arc::new(BregG2pBridge::new(resolver.clone())), + Arc::new(HttpG2pProvider::new(resolver)), + ); + let state = Arc::new(HttpState { + authenticator, + service, + g2p, + disbursements: Vec::new(), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind a probe port"); + let port = listener.local_addr().expect("the probe port").port(); + tokio::spawn(async move { + axum::serve(listener, payment_router(state)) + .await + .expect("the payment router serves"); + }); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("epoch") + .as_secs(); + let good = |client: &str, scope: &str| { + format!("Bearer {}", token(&signing_key, client, scope, now + 300)) + }; + let expired = format!( + "Bearer {}", + token( + &signing_key, + "coordinator", + "payments:collections", + now - 3_600 + ) + ); + let stranger = good("stranger", "payments:collections"); + let forged = { + let other = access_token_test_key(jsonwebtoken::Algorithm::ES256); + format!( + "Bearer {}", + token(&other, "coordinator", "payments:collections", now + 300) + ) + }; + let member = good("coordinator", "payments:collections"); + let other_client = good("other", "payments:collections"); + let no_scope = good("coordinator", "other.scope"); + let collection = json!({"billId": Uuid::new_v4(), "billVersion": 1}); + let disbursement = json!({"instructionRecordId": Uuid::new_v4(), "instructionVersion": 1}); + let known = "/v1/payments/fees/collections"; + let missing_attempt = format!("{known}/{}", Uuid::new_v4()); + + let counter = |check: &str| { + crate::metrics::refusal_recorder() + .counter() + .get(&[check]) + .expect("every check is declared") + }; + let mut answers = serde_json::Map::new(); + // Each case: name, check, method, path, authorization headers, body. + let cases: Vec = vec![ + ( + "no-authorization", + "credential-missing", + "POST", + known.into(), + vec![], + Some(&collection), + ), + ( + "basic-scheme", + "credential-missing", + "POST", + known.into(), + vec!["Basic YWJjOmRlZg==".into()], + Some(&collection), + ), + ( + "two-authorization-headers", + "credential-malformed", + "POST", + known.into(), + vec![member.clone(), member.clone()], + Some(&collection), + ), + ( + "not-a-compact-token", + "credential-malformed", + "POST", + known.into(), + vec!["Bearer not-a-token".into()], + Some(&collection), + ), + ( + "unknown-signer", + "token-signature", + "POST", + known.into(), + vec![forged], + Some(&collection), + ), + ( + "expired", + "token-time", + "POST", + known.into(), + vec![expired], + Some(&collection), + ), + ( + "unlisted-client", + "token-client", + "POST", + known.into(), + vec![stranger], + Some(&collection), + ), + ( + "unknown-connection", + "visibility", + "POST", + "/v1/payments/nowhere/collections".into(), + vec![member.clone()], + Some(&collection), + ), + ( + "client-not-allowed", + "requester-client", + "POST", + known.into(), + vec![other_client], + Some(&collection), + ), + ( + "scope-not-held", + "scope", + "POST", + known.into(), + vec![no_scope], + Some(&collection), + ), + ( + "unknown-attempt", + "visibility", + "GET", + missing_attempt, + vec![member.clone()], + None, + ), + ( + "unknown-disbursement-connection", + "visibility", + "POST", + "/v1/payments/nowhere/disbursements".into(), + vec![member.clone()], + Some(&disbursement), + ), + ]; + let mut deltas: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new(); + for (name, check, method, path, authorization, body) in &cases { + let before = counter(check); + let headers: Vec<&str> = authorization.iter().map(String::as_str).collect(); + let (status, head, answer) = send(port, method, path, &headers, *body).await; + answers.insert((*name).to_owned(), frozen(status, &head, &answer)); + *deltas.entry(check).or_default() += counter(check) - before; + } + let answers = Value::Object(answers); + if std::env::var_os("ADAPTER_WRITE_GOLDEN").is_some() { + std::fs::write( + GOLDEN, + serde_json::to_string_pretty(&answers).expect("serialize the golden") + "\n", + ) + .expect("write the golden file"); + } + let golden: Value = serde_json::from_str( + &std::fs::read_to_string(GOLDEN).expect("the golden file is checked in"), + ) + .expect("the golden file is JSON"); + assert_eq!(answers, golden, "a payment refusal answer changed"); + let mut wanted: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new(); + for (_, check, ..) in &cases { + *wanted.entry(check).or_default() += 1; + } + assert_eq!( + deltas, wanted, + "each refusal is counted once under its check" + ); +} diff --git a/crates/registry-adapter/src/payments/service.rs b/crates/registry-adapter/src/payments/service.rs index 25a5348bc8..d6a8b9515c 100644 --- a/crates/registry-adapter/src/payments/service.rs +++ b/crates/registry-adapter/src/payments/service.rs @@ -25,6 +25,7 @@ use registry_payment_protocol::{ RegistryReceipt, RequestCollection, }; use registry_payment_simulator_connector::{ConnectorError, Observation, SimulatorClient}; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::SecretResolver; use registry_platform_httputil::client::BearerToken; use registry_platform_httputil::{read_bounded, validate_response_headers, ServiceBaseUrl}; @@ -623,17 +624,27 @@ impl PaymentService { .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); + fn connection(&self, id: &str, caller: &Caller) -> Result<&PaymentConnection, PaymentFailure> { + let connection = + self.config + .connections + .iter() + .find(|c| c.id == id) + .ok_or(PaymentFailure::refused( + Error::NotFound, + FailedCheck::Visibility, + ))?; + if !connection.allowed_clients.contains(&caller.client_id) { + return Err(PaymentFailure::refused( + Error::Forbidden, + FailedCheck::RequesterClient, + )); + } + if !caller.scopes.contains(&connection.required_scope) { + return Err(PaymentFailure::refused( + Error::Forbidden, + FailedCheck::Scope, + )); } Ok(connection) } @@ -642,13 +653,16 @@ impl PaymentService { attempt: &Attempt, connection: &PaymentConnection, principal: &str, - ) -> Result<(), Error> { + ) -> Result<(), PaymentFailure> { 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); + return Err(PaymentFailure::refused( + Error::NotFound, + FailedCheck::Ownership, + )); } Ok(()) } @@ -659,7 +673,7 @@ impl PaymentService { caller: &Caller, key: &str, request: &RequestCollection, - ) -> Result { + ) -> Result { let connection = self.connection(id, caller)?; validate_key(key)?; request.validate().map_err(|_| Error::InvalidRequest)?; @@ -701,7 +715,7 @@ impl PaymentService { || view.state != BillState::DueUnbound || view.attempt_id.is_some() { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } let provider_command = self .provider @@ -761,7 +775,7 @@ impl PaymentService { .read_bill(&attempt.binding, attempt.bill.bill_id) .await?; if !bill.matches_binding(&attempt) || bill.state != BillState::AttemptBound { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } let preflight = self .provider @@ -789,7 +803,7 @@ impl PaymentService { .save(&attempt, "provider.unknown") .await .map_err(|_| Error::OutcomeUnknown)?; - return Err(Error::OutcomeUnknown); + return Err(Error::OutcomeUnknown.into()); } }; attempt.transfer_id = Some(submission.transfer_id); @@ -863,7 +877,7 @@ impl PaymentService { caller: &Caller, key: &str, request: &RequestCollection, - ) -> Result { + ) -> Result { let connection = self.connection(id, caller)?; validate_key(key)?; request.validate().map_err(|_| Error::InvalidRequest)?; @@ -873,10 +887,14 @@ impl PaymentService { .lookup_command(id, &principal, "request", key, &digest(request)?) .await? .ok_or(Error::ReceiptUnresolved)?; - let attempt = self.store.get(saved).await?; + let attempt = self + .store + .get(saved) + .await + .map_err(PaymentFailure::concealing)?; Self::authorize(&attempt, connection, &principal)?; if attempt.transfer_id.is_none() { - return Err(Error::ReceiptUnresolved); + return Err(Error::ReceiptUnresolved.into()); } Ok(attempt.acceptance()) } @@ -886,7 +904,7 @@ impl PaymentService { id: &str, caller: &Caller, collection: Uuid, - ) -> Result { + ) -> Result { let connection = self.connection(id, caller)?; let principal = principal(caller)?; let _permit = self @@ -894,7 +912,11 @@ impl PaymentService { .clone() .try_acquire_owned() .map_err(|_| Error::Unavailable)?; - let initial = self.store.get(collection).await?; + let initial = self + .store + .get(collection) + .await + .map_err(PaymentFailure::concealing)?; Self::authorize(&initial, connection, &principal)?; let mut lock_client = self .store @@ -938,7 +960,7 @@ impl PaymentService { .as_ref() .is_some_and(|old| observation.observed_at < old.observed_at) { - return Err(Error::ProviderProtocol); + return Err(Error::ProviderProtocol.into()); } attempt.observation = Some(observation); self.store.save(&attempt, "provider.observed").await?; @@ -951,7 +973,7 @@ impl PaymentService { caller: &Caller, key: &str, collection: Uuid, - ) -> Result { + ) -> Result { let connection = self.connection(id, caller)?; validate_key(key)?; let principal = principal(caller)?; @@ -960,7 +982,11 @@ impl PaymentService { .clone() .try_acquire_owned() .map_err(|_| Error::Unavailable)?; - let initial = self.store.get(collection).await?; + let initial = self + .store + .get(collection) + .await + .map_err(PaymentFailure::concealing)?; Self::authorize(&initial, connection, &principal)?; self.store .claim_command( @@ -991,7 +1017,7 @@ impl PaymentService { } let status = attempt.status(); if status.state != CollectionState::Confirmed { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } let reference = status.provider_reference.ok_or(Error::Conflict)?; match &attempt.binding.provider { @@ -1001,15 +1027,15 @@ impl PaymentService { // 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); + return Err(Error::RecoveryHeld.into()); } CollectionProvider::Http { .. } if !status.simulation => { - return Err(Error::RecoveryHeld); + return Err(Error::RecoveryHeld.into()); } CollectionProvider::Simulator { .. } | CollectionProvider::Mifos { .. } | CollectionProvider::Http { .. } => { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } } let receipt = RegistryReceipt { @@ -1038,7 +1064,7 @@ impl PaymentService { return Ok(receipt); } if !view.matches_binding(&attempt) || view.state != BillState::AttemptBound { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } if attempt.report_action.is_none() { let mut inputs = binding_inputs(&attempt)?; @@ -1065,7 +1091,7 @@ impl PaymentService { self.store.save(&attempt, "receipt.prepared").await?; } if attempt.receipt_digest.as_ref() != Some(&receipt_digest) { - return Err(Error::RecoveryHeld); + return Err(Error::RecoveryHeld.into()); } let result = self .registry @@ -1081,7 +1107,7 @@ impl PaymentService { .await .map_err(|_| Error::OutcomeUnknown)?; if !observed.matches_receipt(&attempt, &receipt, &receipt_digest) { - return Err(result.err().unwrap_or(Error::OutcomeUnknown)); + return Err(result.err().unwrap_or(Error::OutcomeUnknown).into()); } attempt.receipt = Some(receipt.clone()); self.store @@ -1123,6 +1149,44 @@ fn validate_key(key: &str) -> Result<(), Error> { } } +/// A payment error and, when the caller was refused, the check it failed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PaymentFailure { + pub code: Error, + pub check: Option, +} + +impl PaymentFailure { + pub(crate) fn refused(code: Error, check: FailedCheck) -> Self { + Self { + code, + check: Some(check), + } + } + + /// A lookup that found nothing is a refusal for the check that conceals + /// existence; any other error carries no check. + pub(crate) fn concealing(code: Error) -> Self { + if code == Error::NotFound { + Self::refused(code, FailedCheck::Visibility) + } else { + code.into() + } + } +} + +impl From for PaymentFailure { + fn from(code: Error) -> Self { + Self { code, check: None } + } +} + +impl PartialEq for PaymentFailure { + fn eq(&self, other: &Error) -> bool { + self.code == *other + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 612c2d5ef1..32d9d54b47 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -12,14 +12,14 @@ use std::time::{Duration, SystemTime}; use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime}; use registry_adapter_core::AdapterRuntimeConfig; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; use registry_platform_config::{ DatabaseConfig, JwksSource, SecretReference as ConfigSecretReference, SecretResolver, }; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - AuthenticationStage, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, - OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, }; use registry_platform_yaml::SecretReference; use thiserror::Error; @@ -76,12 +76,23 @@ pub struct Caller { /// Why a request has no caller. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CallerRefusal { - /// The credential is absent or was refused. - Unauthenticated, + /// The credential is absent or was refused, at the named check. + Unauthenticated(FailedCheck), /// The verifier could not reach a verdict (issuer or key set outage). Unavailable, } +impl CallerRefusal { + /// The check the request failed, for the operator-side counter and log. + #[must_use] + pub const fn failed_check(self) -> FailedCheck { + match self { + Self::Unauthenticated(check) => check, + Self::Unavailable => FailedCheck::KeySourceUnavailable, + } + } +} + /// The longest subject the journal's caller reference column holds. const MAXIMUM_SUBJECT_BYTES: usize = 256; @@ -90,32 +101,11 @@ pub struct Authenticator { } impl Authenticator { - /// Log the refusal of a request whose `Authorization` header is absent, - /// not text, or not a bearer credential, so every 401 leaves the same - /// value-free, rate-limited trace as a refused token. - pub fn log_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Header, - "Adapter authentication refused" - ); - } - pub async fn authenticate(&self, token: &str) -> Result { - validate_compact_access_token(token).map_err(|_| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Header, - "Adapter authentication refused" - ); - CallerRefusal::Unauthenticated - })?; + validate_compact_access_token(token) + .map_err(|_| CallerRefusal::Unauthenticated(FailedCheck::CredentialMalformed))?; let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Adapter authentication refused" - ); + let check = error.failed_check(); match error { OidcError::Transport(_) | OidcError::BoundedRead(_) @@ -127,19 +117,16 @@ impl Authenticator { | OidcError::EmptyKeySet | OidcError::MissingIssuer | OidcError::ConflictingEndpointConfiguration => CallerRefusal::Unavailable, - _ => CallerRefusal::Unauthenticated, + _ => CallerRefusal::Unauthenticated(check), } })?; // An exchanged token names the authority whose assertion produced // it. This runtime declares no assertion authority, so it admits // no exchanged token. if verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Client, - "Adapter authentication refused: an exchanged credential arrived at a deployment that declares no assertion authority" - ); - return Err(CallerRefusal::Unauthenticated); + return Err(CallerRefusal::Unauthenticated( + FailedCheck::TokenAssertionIssuer, + )); } let issuer = verified .claims @@ -150,14 +137,7 @@ impl Authenticator { && issuer.len() <= MAX_CALLER_ISSUER_BYTES && !issuer.contains('\0') }) - .ok_or_else(|| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Profile, - "Adapter authentication refused: the issuer is absent or unusable for caller isolation" - ); - CallerRefusal::Unauthenticated - })?; + .ok_or(CallerRefusal::Unauthenticated(FailedCheck::TokenClaims))?; let client_id = verified .matched_client_id() .ok() @@ -168,14 +148,7 @@ impl Authenticator { && !client.contains('\0') }) .map(str::to_owned) - .ok_or_else(|| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Client, - "Adapter authentication refused: the admitted client identity is unavailable" - ); - CallerRefusal::Unauthenticated - })?; + .ok_or(CallerRefusal::Unauthenticated(FailedCheck::TokenClient))?; let reference = verified .claims .sub @@ -185,14 +158,7 @@ impl Authenticator { && subject.len() <= MAXIMUM_SUBJECT_BYTES && !subject.contains('\0') }) - .ok_or_else(|| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Profile, - "Adapter authentication refused: the subject is absent or unusable as a caller reference" - ); - CallerRefusal::Unauthenticated - })?; + .ok_or(CallerRefusal::Unauthenticated(FailedCheck::TokenClaims))?; Ok(Caller { reference, issuer, diff --git a/crates/registry-adapter/src/serve/token_characterisation.rs b/crates/registry-adapter/src/serve/token_characterisation.rs index f07e66e7b7..3745536892 100644 --- a/crates/registry-adapter/src/serve/token_characterisation.rs +++ b/crates/registry-adapter/src/serve/token_characterisation.rs @@ -9,7 +9,7 @@ //! payment host builds its authenticator through the same function and //! authenticates a bearer through the same method. The module sits under //! `serve` so it can also ask the authenticator's own verifier for the check -//! that refused a token, which `CallerRefusal` does not carry. +//! that refused a token and compare it with the check `CallerRefusal` carries. use super::*; use registry_platform_config::SecretProvider; use registry_platform_testing::{ @@ -68,8 +68,15 @@ async fn observe(authenticator: &Authenticator, token: &str) -> Outcome { match (admission, verdict) { (Ok(_), Ok(_)) => Outcome::Admitted(None), (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), - (Err(_), Err(error)) => stage_of(&error), - (Err(CallerRefusal::Unauthenticated), Ok(_)) => { + (Err(refusal), Err(error)) => { + assert_eq!( + refusal.failed_check(), + error.failed_check(), + "the refusal carries the check the verifier named" + ); + stage_of(&error) + } + (Err(CallerRefusal::Unauthenticated(_)), Ok(_)) => { "refused/claims".parse().expect("result value") } (Err(CallerRefusal::Unavailable), Ok(_)) => { diff --git a/crates/registry-adapter/tests/facade_refusals.rs b/crates/registry-adapter/tests/facade_refusals.rs new file mode 100644 index 0000000000..018f56b317 --- /dev/null +++ b/crates/registry-adapter/tests/facade_refusals.rs @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Every refusal of a facade caller, end to end through the built `adapter` +//! binary over a real journal: the answer is frozen against a checked-in +//! golden file (status, `content-type`, `www-authenticate`, `retry-after`, +//! `cache-control` and the body with its correlation identifier removed), the +//! refusal counter on the operator-private metrics listener rises by one under +//! the check that refused, and the log carries one value-free line naming that +//! check. +//! +//! `ADAPTER_WRITE_GOLDEN=1` rewrites the golden file from the running binary. +//! Without it the answers are compared to the file. Needs +//! `ADAPTER_TEST_DATABASE_URL`; without it every test fails on the spot. +#![cfg(feature = "postgres-test")] + +#[allow(dead_code)] +#[path = "support/served/mod.rs"] +mod served_harness; + +use std::collections::BTreeMap; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::time::Duration; + +use serde_json::{json, Value}; +use served_harness::upstream::{Response, UpstreamDouble}; +use served_harness::{capture, copy_govstack_project, fixture, Served, STDERR_WAIT}; + +const GET_PATH: &str = "/govstack/registries/v1/collections/people/records/EeBJ3Sn9uLg"; +const LIST_PATH: &str = "/govstack/registries/v1/collections/people/records"; +const LOOKUP_PATH: &str = "/govstack/registries/v1/collections/people/lookup"; +const COUNTER: &str = "adapter_request_refusals_total"; +const GOLDEN: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/golden/facade_refusals.json" +); + +/// A second access profile for the copied project: a caller holding +/// `records.write` is admitted to retrieve and to nothing else. +const WRITER_PROFILE: &str = " - id: records-writer\n scopes: [records.write]\n operations: [retrieve]\n recordTypes: [people]\n"; + +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0") + .expect("bind a probe port") + .local_addr() + .expect("the probe port") + .port() +} + +fn scrape(port: u16) -> String { + let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect the metrics port"); + stream + .write_all(b"GET /metrics HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") + .expect("write"); + let mut raw = String::new(); + stream.read_to_string(&mut raw).expect("read"); + raw.split_once("\r\n\r\n") + .expect("a header block") + .1 + .to_owned() +} + +/// The refusal counter as `check -> count`. +fn refusals(port: u16) -> BTreeMap { + scrape(port) + .lines() + .filter_map(|line| { + let rest = line.strip_prefix(COUNTER)?.strip_prefix("{check=\"")?; + let (check, count) = rest.split_once("\"} ")?; + Some((check.to_owned(), count.parse().expect("a counter value"))) + }) + .collect() +} + +fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> { + head.lines().skip(1).find_map(|line| { + let (candidate, value) = line.split_once(':')?; + candidate.eq_ignore_ascii_case(name).then(|| value.trim()) + }) +} + +/// The answer as the golden file holds it. The correlation identifiers differ +/// per request, so they are replaced by a marker. +fn frozen(status: u16, head: &str, body: &Value) -> Value { + let mut body = body.clone(); + if let Some(object) = body.as_object_mut() { + for member in ["traceId", "requestId"] { + if object.contains_key(member) { + object.insert(member.to_owned(), json!("")); + } + } + } + json!({ + "status": status, + "content-type": header(head, "content-type"), + "www-authenticate": header(head, "www-authenticate"), + "retry-after": header(head, "retry-after"), + "cache-control": header(head, "cache-control"), + "body": body, + }) +} + +/// The `request refused` lines the binary wrote, as their `failed_check` +/// values, in order. +fn refused_lines(stderr: &str) -> Vec { + stderr + .lines() + .filter_map(|line| serde_json::from_str::(line.trim()).ok()) + .filter(|event| event["fields"]["message"] == "request refused") + .map(|event| { + assert_eq!(event["fields"]["decision"], "refused"); + event["fields"]["failed_check"] + .as_str() + .expect("a failed check") + .to_owned() + }) + .collect() +} + +fn page(page: u64) -> Response { + let document = fixture("search-page"); + let mut body = document["entries"][0]["upstream"][0]["response"]["body"].clone(); + body["pager"]["page"] = json!(page); + body["pager"]["pageCount"] = json!(9); + Response::json(200, &body.to_string()) +} + +struct Case { + name: &'static str, + status: u16, + head: String, + body: Value, + check: &'static str, +} + +#[tokio::test] +async fn every_refusal_keeps_its_answer_and_is_counted_and_logged_under_its_check() { + let upstream = UpstreamDouble::start(); + upstream.respond_with(vec![page(1)]); + let directory = tempfile::tempdir().expect("a scratch directory"); + copy_govstack_project(directory.path()); + let project = directory.path().join("project.yaml"); + let mut text = std::fs::read_to_string(&project).expect("the project is readable"); + if !text.ends_with('\n') { + text.push('\n'); + } + text.push_str(WRITER_PROFILE); + std::fs::write(&project, text).expect("write the project"); + let metrics_port = free_port(); + let served = + Served::start_with_metrics(&upstream.url(""), directory.path(), metrics_port).await; + + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("the test clock follows the epoch") + .as_secs(); + let reader = served.token("records.read"); + let first = served.get(&format!("{LIST_PATH}?pageSize=5"), Some(&reader)); + assert_eq!(first.0, 200, "{}", first.2); + let cursor = first.2["pageInfo"]["nextCursor"] + .as_str() + .expect("a cursor") + .to_owned(); + let tokens: Vec<(&str, String)> = vec![ + ("wrong-audience", served.token_with("subject", "records.read", json!({"aud": "another-service"}))), + ("expired", served.token_with("subject", "records.read", json!({"exp": now.saturating_sub(3_600)}))), + ("unlisted-client", served.token_with("subject", "records.read", json!({"client_id": "stranger"}))), + ( + "exchanged", + served.token_with( + "subject", + "records.read", + json!({registry_platform_oidc::ASSERTION_ISSUER_CLAIM: "https://other.example.invalid"}), + ), + ), + ("subject-too-long", served.token_for(&"s".repeat(257), "records.read")), + ("scope-not-held", served.token("other.scope")), + ("operation-not-named", served.token("records.write")), + ( + "cursor-of-another-client", + served.token_with( + served_harness::SUBJECT, + "records.read", + json!({"client_id": served_harness::SECOND_CLIENT}), + ), + ), + ]; + let token = |name: &str| { + tokens + .iter() + .find(|(candidate, _)| *candidate == name) + .map(|(_, value)| value.as_str()) + .expect("a prepared token") + }; + + let mut cases: Vec = Vec::new(); + let mut run = |name: &'static str, check: &'static str, answer: (u16, String, Value)| { + cases.push(Case { + name, + status: answer.0, + head: answer.1, + body: answer.2, + check, + }); + }; + run( + "no-authorization", + "credential-missing", + served.get(GET_PATH, None), + ); + run( + "basic-scheme", + "credential-missing", + served.request( + "GET", + GET_PATH, + None, + &[("Authorization", "Basic YWJjOmRlZg==")], + b"", + ), + ); + run( + "bearer-without-token", + "credential-malformed", + served.request("GET", GET_PATH, None, &[("Authorization", "Bearer")], b""), + ); + run( + "not-a-compact-token", + "credential-malformed", + served.get(GET_PATH, Some("not-a-token")), + ); + run( + "unknown-signer", + "token-signature", + served.get(GET_PATH, Some(&Served::forged_token())), + ); + run( + "wrong-audience", + "token-audience", + served.get(GET_PATH, Some(token("wrong-audience"))), + ); + run( + "expired", + "token-time", + served.get(GET_PATH, Some(token("expired"))), + ); + run( + "unlisted-client", + "token-client", + served.get(GET_PATH, Some(token("unlisted-client"))), + ); + run( + "exchanged", + "token-assertion-issuer", + served.get(GET_PATH, Some(token("exchanged"))), + ); + run( + "subject-too-long", + "token-claims", + served.get(GET_PATH, Some(token("subject-too-long"))), + ); + run( + "scope-not-held", + "scope", + served.get(GET_PATH, Some(token("scope-not-held"))), + ); + run( + "operation-not-named", + "operation", + served.post(LOOKUP_PATH, Some(token("operation-not-named")), &json!({})), + ); + run( + "cursor-of-another-client", + "ownership", + served.get( + &format!("{LIST_PATH}?cursor={cursor}"), + Some(token("cursor-of-another-client")), + ), + ); + + let frozen_answers: Value = Value::Object( + cases + .iter() + .map(|case| { + ( + case.name.to_owned(), + frozen(case.status, &case.head, &case.body), + ) + }) + .collect(), + ); + if std::env::var_os("ADAPTER_WRITE_GOLDEN").is_some() { + std::fs::create_dir_all(std::path::Path::new(GOLDEN).parent().expect("a directory")) + .expect("create the golden directory"); + std::fs::write( + GOLDEN, + serde_json::to_string_pretty(&frozen_answers).expect("serialize the golden") + "\n", + ) + .expect("write the golden file"); + } + let golden: Value = serde_json::from_str( + &std::fs::read_to_string(GOLDEN).expect("the golden file is checked in"), + ) + .expect("the golden file is JSON"); + assert_eq!(frozen_answers, golden, "a refusal answer changed"); + + let mut expected: BTreeMap = BTreeMap::new(); + for case in &cases { + *expected.entry(case.check.to_owned()).or_default() += 1; + } + let counted = refusals(metrics_port); + for (check, count) in &expected { + assert_eq!( + counted.get(check), + Some(count), + "the counter for {check}: {counted:?}" + ); + } + assert_eq!( + counted.values().sum::(), + expected.values().sum::(), + "no other check was counted: {counted:?}" + ); + assert_eq!(counted.len(), 45, "every check is declared at zero"); + + let stderr = served.wait_for_stderr("\"request refused\"", STDERR_WAIT); + std::thread::sleep(Duration::from_millis(300)); + let stderr = served.stderr_text().max(stderr); + let mut logged = refused_lines(&stderr); + logged.sort(); + let mut wanted: Vec = cases.iter().map(|case| case.check.to_owned()).collect(); + wanted.sort(); + assert_eq!(logged, wanted, "one value-free line per refusal"); + for secret in tokens.iter().map(|(_, value)| value.as_str()).chain([ + reader.as_str(), + "stranger", + cursor.as_str(), + ]) { + assert!(!stderr.contains(secret), "a caller value reached the log"); + } + let _ = capture; +} diff --git a/crates/registry-adapter/tests/golden/facade_refusals.json b/crates/registry-adapter/tests/golden/facade_refusals.json new file mode 100644 index 0000000000..ae92e99830 --- /dev/null +++ b/crates/registry-adapter/tests/golden/facade_refusals.json @@ -0,0 +1,171 @@ +{ + "basic-scheme": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "bearer-without-token": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "cursor-of-another-client": { + "body": { + "status": 400, + "title": "the cursor is not valid", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/invalid-cursor" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 400, + "www-authenticate": null + }, + "exchanged": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "expired": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "no-authorization": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "not-a-compact-token": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "operation-not-named": { + "body": { + "status": 403, + "title": "the caller may not make this request", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/forbidden" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 403, + "www-authenticate": null + }, + "scope-not-held": { + "body": { + "status": 403, + "title": "the caller may not make this request", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/forbidden" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 403, + "www-authenticate": null + }, + "subject-too-long": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "unknown-signer": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "unlisted-client": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "wrong-audience": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + } +} diff --git a/crates/registry-adapter/tests/golden/payment_refusals.json b/crates/registry-adapter/tests/golden/payment_refusals.json new file mode 100644 index 0000000000..6782bbbe73 --- /dev/null +++ b/crates/registry-adapter/tests/golden/payment_refusals.json @@ -0,0 +1,182 @@ +{ + "basic-scheme": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "client-not-allowed": { + "body": { + "code": "adapter.payment.forbidden", + "status": 403, + "title": "adapter.payment.forbidden", + "type": "urn:registry:problem:adapter.payment.forbidden" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 403, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "expired": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "no-authorization": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "not-a-compact-token": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "scope-not-held": { + "body": { + "code": "adapter.payment.forbidden", + "status": 403, + "title": "adapter.payment.forbidden", + "type": "urn:registry:problem:adapter.payment.forbidden" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 403, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "two-authorization-headers": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unknown-attempt": { + "body": { + "code": "adapter.payment.not-found", + "status": 404, + "title": "adapter.payment.not-found", + "type": "urn:registry:problem:adapter.payment.not-found" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 404, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unknown-connection": { + "body": { + "code": "adapter.payment.not-found", + "status": 404, + "title": "adapter.payment.not-found", + "type": "urn:registry:problem:adapter.payment.not-found" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 404, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unknown-disbursement-connection": { + "body": { + "code": "adapter.payment.not-found", + "status": 404, + "title": "adapter.payment.not-found", + "type": "urn:registry:problem:adapter.payment.not-found" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 404, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unknown-signer": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unlisted-client": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + } +} diff --git a/crates/registry-adapter/tests/records_get_served.rs b/crates/registry-adapter/tests/records_get_served.rs index 849747aa49..b3f2ac1757 100644 --- a/crates/registry-adapter/tests/records_get_served.rs +++ b/crates/registry-adapter/tests/records_get_served.rs @@ -420,10 +420,14 @@ async fn every_401_path_leaves_a_value_free_log_line() { assert_eq!(status, 401); let stderr = served.stop_and_read_stderr(); - for stage in ["header", "client", "profile"] { + for check in [ + "credential-missing", + "token-assertion-issuer", + "token-claims", + ] { assert!( - stderr.contains(&format!("\"stage\":\"{stage}\"")), - "no {stage}-stage refusal was logged: {stderr}" + stderr.contains(&format!("\"failed_check\":\"{check}\"")), + "no {check} refusal was logged: {stderr}" ); } assert!( diff --git a/crates/registry-adapterctl/src/verify/mod.rs b/crates/registry-adapterctl/src/verify/mod.rs index 5cd983d52a..d759ce7f80 100644 --- a/crates/registry-adapterctl/src/verify/mod.rs +++ b/crates/registry-adapterctl/src/verify/mod.rs @@ -878,13 +878,10 @@ fn destination_profile(base: &Url) -> DestinationProfile { } fn denotes_loopback(origin: &Url) -> bool { - let parsed = origin.to_url(); - parsed.host_str().is_some_and(|host| { - host.eq_ignore_ascii_case("localhost") - || host - .parse::() - .is_ok_and(|address| address.is_loopback()) - }) + origin + .to_url() + .host_str() + .is_some_and(|host| registry_platform_httputil::loopback::loopback_host(host).is_some()) } /// Read one declared CA bundle under the platform ceiling. Every failure is diff --git a/crates/registry-payment-simulator-connector/src/lib.rs b/crates/registry-payment-simulator-connector/src/lib.rs index 74943d22ed..2b6d1d68fb 100644 --- a/crates/registry-payment-simulator-connector/src/lib.rs +++ b/crates/registry-payment-simulator-connector/src/lib.rs @@ -3,6 +3,7 @@ use registry_payment_protocol::{CollectionState, Money, MAX_MINOR_UNITS}; use registry_platform_httputil::client::{build_client, BearerToken, OutboundOptions}; +use registry_platform_httputil::loopback::loopback_address; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; use std::time::Duration; @@ -67,9 +68,10 @@ impl SimulatorConnection { registry_platform_yaml::Url::new(self.callback_url.clone()) .map_err(|_| ConnectorError::Configuration)?; let url = Url::parse(&self.base_url).map_err(|_| ConnectorError::Configuration)?; + // An address literal only: the name `localhost` is refused. let loopback = match url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Ipv4(ip)) => loopback_address(ip.into()), + Some(Host::Ipv6(ip)) => loopback_address(ip.into()), _ => false, }; if !loopback diff --git a/crates/registry-payment-simulator-connector/tests/profile.rs b/crates/registry-payment-simulator-connector/tests/profile.rs index 1c9707b679..bb3fef6480 100644 --- a/crates/registry-payment-simulator-connector/tests/profile.rs +++ b/crates/registry-payment-simulator-connector/tests/profile.rs @@ -43,6 +43,23 @@ fn synthetic_transport_cannot_point_to_live_or_named_remote_hosts() { } } #[test] +fn the_synthetic_transport_takes_loopback_address_literals_and_no_name() { + for base in ["http://127.0.0.1/", "http://[::1]/"] { + let mut config = connection(); + config.base_url = base.into(); + assert!(config.validate().is_ok(), "{base}"); + } + for base in [ + "http://localhost/", + "http://10.0.0.1/", + "http://a.localhost/", + ] { + let mut config = connection(); + config.base_url = base.into(); + assert!(config.validate().is_err(), "{base}"); + } +} +#[test] fn request_amount_is_an_exact_json_number_even_near_the_portable_bound() { let mut cmd = command(); cmd.money.value = "90071992547409.91".into(); diff --git a/docs/site/src/content/docs/configure/adapter.mdx b/docs/site/src/content/docs/configure/adapter.mdx index 29d445fb14..f217225070 100644 --- a/docs/site/src/content/docs/configure/adapter.mdx +++ b/docs/site/src/content/docs/configure/adapter.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -689,6 +689,28 @@ Any admitted client with a matching scope sees every record that the deployment' Record-level authorisation is not built. Admitting a client means trusting it with the full reach of the deployment credential. +A refused facade or payment request is counted and logged under the check that refused it, never under a caller value. +`adapter_request_refusals_total{check}` rises by one and the log carries one `request refused` line with the fixed `failed_check` label, for example `credential-missing`, `token-signature`, `token-client`, `scope`, `operation` or `ownership`. +The answer to the caller is unchanged. +The line is rate limited per check, so a flood of one kind of refusal cannot fill the log. +See [Scrape metrics](../../operate/adapter/#scrape-metrics). + +### Plain HTTP, private ranges and loopback + +An origin is plain HTTP only inside the loopback exception or inside the private ranges the runtime config declares in `allowedPrivateCidrs`. +Loopback means a `127.0.0.0/8` address, `::1`, an IPv4-mapped form of a `127.0.0.0/8` address, or the exact name `localhost`. +A payment provider connection takes only the address literals, never the name. +The name is pinned: the connection goes only to loopback addresses. +`a.localhost` and `localhost.` are named hosts. +An omitted or empty `allowedPrivateCidrs` admits no private address. +An origin plain HTTP names by host name, with no range declared, fails the runtime check with `adapter.runtime.insecure-origin`. +The text names the fix: serve the origin over TLS, declare the range the host resolves to, or use a loopback origin. + +**Breaking, for ingestion job hosts.** Before this change a job host whose runtime document named a plain `http://` endpoint by host name, with `allowedPrivateCidrs` omitted or empty, reached every private address the name resolved to. +Now that job fails the runtime check with `adapter.runtime.insecure-origin`. +To migrate, add the smallest range that contains the endpoint to `allowedPrivateCidrs`, serve the endpoint over HTTPS, or bind it on loopback. +The served facade is not affected: it already refused an empty list at load. + ### Upstream authentication {/* Evidence: crates/registry-adapter-core/src/auth.rs EndpointAuthentication */} diff --git a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx index 124a789b12..acbcb76f76 100644 --- a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx +++ b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-20" +last_reviewed: "2026-11-27" doc_type: how-to persona: - operator @@ -264,6 +264,7 @@ Set `metricsListener.bind` to serve Prometheus text at `/metrics` on a private a | `evidence_oid4vci_store_entries` | Entries in the fullest bounded offer, ledger, or token keyspace | | `evidence_oid4vci_store_capacity` | Refusal threshold for each bounded keyspace | | `evidence_oid4vci_cleanup_expired_total` | Expired in-memory entries released by cleanup | +| `evidence_oid4vci_request_refusals_total` | Requests refused, by the check that failed, with every check published at zero. Each refusal also writes one `request refused` log line with `failed_check`, at most five per check per minute. Neither carries a token, claim or client | {/* Evidence: crates/registry-evidence-oid4vci/src/observability.rs, Outcome, ALL, render_metrics. */} diff --git a/docs/site/src/content/docs/operate/adapter.mdx b/docs/site/src/content/docs/operate/adapter.mdx index e60b2066df..f91aa9fed1 100644 --- a/docs/site/src/content/docs/operate/adapter.mdx +++ b/docs/site/src/content/docs/operate/adapter.mdx @@ -862,6 +862,7 @@ Facade series: | --- | --- | --- | --- | | `adapter_http_requests_total` | counter | `route` (route template, or `unmatched`), `method`, `status` (`1xx`, `2xx`, `3xx`, `4xx`, `5xx`, `other`) | Answered facade requests. | | `adapter_upstream_failures_total` | counter | `class` (`upstream`, `upstream.http`, `upstream.timeout`, `upstream.connection`, `upstream.malformed`, `upstream.too-large`, `upstream.redirect`, `breaker.open`, `throttle.rejected`, `credential.rejected`, `egress.refused`) | Calls to the source that failed, by error class. It counts failed exchanges, status polls, bounded-wait polls and recovery checks. | +| `adapter_request_refusals_total` | counter | `check` (the 45 shared failed-check labels, all present at zero, for example `credential-missing`, `token-signature`, `scope`, `operation`, `ownership`, `visibility`) | Facade and payment requests refused, by the check that failed. Each refusal also writes one `request refused` log line carrying `failed_check` and no caller value, at most five lines per check per minute. | | `adapter_journal_write_failures_total` | counter | none | Audit journal writes that failed, so the exchange answered an internal error. Custody and rendering failures are not counted here. | | `adapter_retention_sweep_failures_total` | counter | `store` (`journal`, `idempotency`, `other`) | Retention sweep batches that failed and were left to the next tick. | @@ -873,6 +874,7 @@ Job host series: | `adapter_job_last_successful_pass_age_seconds` | gauge | none | Seconds since a pass in this process settled its page. Absent until the first such pass. | | `adapter_job_pass_failures_total` | counter | `reason` (`page-fault`, `destination-stop`, `refusal-limit`, `store-unreachable`) | Passes that did not settle, and passes that could not reach the store. A pass that finds another process holding the lease is not a failure and is not counted. | | `adapter_job_hook_refusals_total` | counter | `reason` (`not-found`, `method`, `unauthenticated`, `rate-limited`, `unavailable`, `body-timeout`, `body-too-large`, `body-unreadable`) | Hook requests the ingress refused. | +| `adapter_job_request_refusals_total` | counter | `check` (the 45 shared failed-check labels, all present at zero. The hook ingress records `credential-missing`, `credential-malformed`, `shared-secret` and `rate-limit`) | Hook requests refused for a credential or the rate limit, by the check that failed. Each refusal also writes one `request refused` log line carrying `failed_check` and no caller value, at most five lines per check per minute. Present when the host is built with `job-hook`. | | `adapter_job_gauge_sample_failures_total` | counter | none | Item count reads that failed or timed out. | When the store cannot be read at scrape time, `adapter_job_items` carries no samples and diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index 66a413df92..13f7a2b48c 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -746,6 +746,7 @@ The metrics are Prometheus text (`text/plain; version=0.0.4`, served with `Cache | `coordinator_runs_finished_total` | counter | `state`: `finished`, `failed`, `cancelled`, `cancelled-after-effect`, `expired` | | `coordinator_step_attempts_total` | counter | `outcome`: `accepted`, `transient`, `permanent`, `maybe-sent`, `unavailable` | | `coordinator_authentication_refusals_total` | counter | `reason`: `refused`, `policy`, `unavailable` | +| `coordinator_request_refusals_total` | counter | `check`: the closed set of 45 failed checks, every value published at zero | | `coordinator_metrics_sample_failures_total` | counter | `sample`: `dispatch-queue`, `run-holds` | | `coordinator_dispatch_jobs` | gauge | `state`: `pending`, `leased`, `unknown` | | `coordinator_runs_attention` | gauge | `reason`: `definition-refused`, `other` | diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index a6df8ab39b..b92af2ce05 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -494,6 +494,7 @@ The series are: | `messaging_provider_attempts_total` | `outcome`: `accepted`, `transient`, `permanent`, `maybe-sent` | Provider attempts, by class | | `messaging_provider_callbacks_total` | `outcome`: `unverified`, `unreadable`, `ignored`, `applied`, `unchanged`, `unmatched`, `ambiguous`, `unavailable` | Provider callbacks, by what became of them | | `messaging_limit_refusals_total` | `limit`: `rate`, `daily`, `pacing`, `callback` | Submissions, attempts, and callbacks a limit refused | +| `messaging_request_refusals_total` | `check`: the closed set of 45 failed checks, every value published at zero | Requests refused, by the check that failed. Each refusal also writes one `request refused` log line with `failed_check`, at most five per check per minute, with `suppressed` counting what a window held back. Neither carries a token, claim, client, subject or identifier | | `messaging_retention_runs_total` | `outcome`: `erased`, `idle`, `failed` | Retention sweeps this process ran | | `messaging_metrics_sample_failures_total` | `sample`: `dispatch-queue` | Scrapes in which the database read failed, since the process started | | `messaging_dispatch_jobs` | `state`: `pending`, `leased`, `unknown` | Gauge read from the database at each scrape | diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index 2d7c554036..f5c30bbbc1 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to persona: - operator @@ -359,6 +359,7 @@ the series below and nothing else. The public listener does not route `/metrics` | `scheduling_hook_oldest_pending_age_seconds` | none | Gauge of how many seconds ago the oldest pending hook delivery's event was captured. Zero when none is pending | | `scheduling_worker_last_success_age_seconds` | `worker`: `hold-expiry`, `retention` | Gauge of seconds since the worker last finished a pass | | `scheduling_metrics_sample_failures_total` | `queue`: `outbox`, `hook-deliveries` | Scrapes in which that queue could not be read | +| `scheduling_request_refusals_total` | `check`: the closed set of 45 failed checks, every value published at zero | Requests refused, by the check that failed. Each refusal also writes one `request refused` log line with `failed_check`, at most five per check per minute, with `suppressed` counting what a window held back. Neither carries a token, claim, client, subject or identifier | Every state is listed, with a zero when no row is in it. Watch `scheduling_outbox_items{state="dead-lettered"}` and diff --git a/docs/site/src/content/docs/operate/stuck-work.mdx b/docs/site/src/content/docs/operate/stuck-work.mdx index 56e2d9db50..4e820e7944 100644 --- a/docs/site/src/content/docs/operate/stuck-work.mdx +++ b/docs/site/src/content/docs/operate/stuck-work.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-20" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -50,6 +50,7 @@ Four more gauges show holds and attention, all read from the database at scrape - `coordinator_runs_restore_review_required` counts runs held for review after a restore. - `coordinator_hold_active{hold}` is 1 while the `restore` or `admissions` hold is set. - `coordinator_metrics_sample_failures_total{sample}` counts scrapes where the dispatch queue or the held-work gauges could not be read. +- `coordinator_request_refusals_total{check}` counts requests refused to a caller, by the check that failed. - `coordinator_oldest_due_age_seconds` is how long ago the oldest pending step was due, counting only steps the worker can claim. Runs a worker cannot claim, such as runs waiting for restore review or with a refused definition, are not counted. Read `coordinator_runs_attention` and `coordinator_hold_active` beside it. @@ -90,6 +91,7 @@ Fix the definition and apply it instead. - `breg_ingestion_runs{state}` counts durable ingestion runs in `open`, `complete`, `cancelled`, or `blocked`. - `breg_metrics_sample_failures_total{sample}` counts scrapes where a database sample failed. The `sample` label is `queue`, `record-timer`, `hook-delivery`, or `ingestion-run`. +- `breg_request_refusals_total{check}` counts requests refused to a caller, by the check that failed. - `bregctl status` and `bregctl doctor` take `--runtime-config`. Doctor reports `external-refresh.status` and `external-projection.status`. @@ -152,6 +154,7 @@ Use the metrics. It is the overdue signal. - `casework_database_up` is 0 when the database cannot answer the review counts. - `casework_metrics_sample_failures_total{sample}` counts each read of the review counts or the completion backlog that failed. +- `casework_request_refusals_total{check}` counts requests refused to a caller, by the check that failed. - `casework_completion_deliveries{state}` counts completion deliveries in `pending`, `retrying`, `leased`, `unknown`, `dead-lettered`, or `expired`. - `casework_completion_oldest_undelivered_age_seconds` is how long the oldest undelivered completion has waited. - `caseworkctl status` and `caseworkctl doctor` take `--runtime-config`. @@ -185,6 +188,7 @@ See the retention guide for what is kept. - `messaging_provider_attempts_total{outcome}` counts `accepted`, `transient`, `permanent`, and `maybe-sent`. - `messaging_provider_callbacks_total{outcome}` counts callbacks, including `unmatched` and `ambiguous`. - `messaging_metrics_sample_failures_total{sample}` counts scrapes where the dispatch queue could not be read. +- `messaging_request_refusals_total{check}` counts requests refused to a caller, by the check that failed. - `messagingctl messages list --status` filters by status, with `--limit` (default 50). A message whose attempts run out leaves `pending` and becomes `failed`. @@ -222,6 +226,7 @@ These series show stuck work: - `scheduling_hook_deliveries{state}` counts observer-hook deliveries by state, and `scheduling_hook_oldest_pending_age_seconds` is the age of the oldest pending one. - `scheduling_worker_last_success_age_seconds{worker}` is the age of the last completed pass of the `hold-expiry` or `retention` worker. - `scheduling_metrics_sample_failures_total{queue}` counts scrapes where a queue could not be read. +- `scheduling_request_refusals_total{check}` counts requests refused to a caller, by the check that failed. The operate page lists the states and the other series. Its probes are `/healthz` and `/readyz`. @@ -253,6 +258,7 @@ The signals are: The reasons are `page-fault`, `destination-stop`, `refusal-limit`, and `store-unreachable`. A standby process that finds the lease held by another process is not counted. - `adapter_job_hook_refusals_total{reason}` counts refused hook-trigger requests. +- `adapter_job_request_refusals_total{check}` counts hook requests refused for a credential or the rate limit, by the check that failed. - `adapter_job_gauge_sample_failures_total` counts item count reads that failed or timed out. Scrapes served from the cached result do not count again. The items gauge then has no samples. @@ -281,6 +287,7 @@ It can publish metrics on an optional `metricsListener.bind`, off by default and - `adapter_journal_write_failures_total` counts audit journal writes that failed. - `adapter_retention_sweep_failures_total{store}` counts failed retention sweeps of the `journal`, `idempotency`, or `other` store. - `adapter_http_requests_total{route,method,status}` counts answered requests. +- `adapter_request_refusals_total{check}` counts refused requests by the check that failed. The operate page has the full table. @@ -303,6 +310,7 @@ With the optional `metricsListener` turned on, Documents also publishes these se - `documents_worker_last_success_age_seconds{worker}` is the age of the last completed pass of the `cleanup` worker. The other workers have no age, so watch their overdue ages. - `documents_metrics_sample_failures_total{sample}` counts scrapes where a queue could not be read. - `documents_http_requests_total{route,method,status}` counts answered requests. +- `documents_request_refusals_total{check}` counts requests refused to a caller, by the check that failed. The operate page has the full table. diff --git a/docs/site/src/content/docs/reference/messaging-configuration.mdx b/docs/site/src/content/docs/reference/messaging-configuration.mdx index e70da27cb3..23366516ce 100644 --- a/docs/site/src/content/docs/reference/messaging-configuration.mdx +++ b/docs/site/src/content/docs/reference/messaging-configuration.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: reference locale: en standards_referenced: @@ -130,6 +130,7 @@ The metrics are Prometheus text, and every label is closed: | `messaging_provider_callbacks_total` | counter | `outcome` | | `messaging_provider_attempts_total` | counter | `outcome`: `accepted`, `transient`, `permanent`, `maybe-sent` | | `messaging_limit_refusals_total` | counter | `limit`: `rate`, `daily`, `pacing`, `callback` | +| `messaging_request_refusals_total` | counter | `check`: the closed set of 45 failed checks, every value published at zero | | `messaging_retention_runs_total` | counter | `outcome`: `erased`, `idle`, `failed` | | `messaging_dispatch_jobs` | gauge | `state`: `pending`, `leased`, `unknown` | diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index f360ff04c2..67f66a6117 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-21" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -160,11 +160,13 @@ A request batch audits both items as not available, and the metric still counts declared_existence_disclosure_mode_governs_the_public_collapse, a_declared_unresolved_problem_logs_a_cause_only_when_a_404_does_not_match_it. */} +BReg counts every refused request by the check that refused it, in `breg_request_refusals_total{check}` on the private metrics listener. +The `check` label is a closed set of 45 names, every one published at zero, and no caller value becomes a label. +Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. A request that BReg answers `404 resource.not_found` because the caller may not see the target reads the same to the caller whatever the reason. -The operator can tell the reasons apart. -`breg_request_refusals_total{check}` counts the request under the rule that refused it, for example `scope`, `purpose`, `requester-client`, `row-boundary`, `task-grant-binding`, `disclosure` or `visibility`, and one `request refused` line names the same `failed_check`. +The operator can tell the reasons apart: the counter holds the request under the rule that refused it, for example `scope`, `purpose`, `requester-client`, `row-boundary`, `task-grant-binding`, `disclosure` or `visibility`. A refused write the engine answers with `write.outside-boundary` counts under `row-boundary`, and a Proposal outside the caller's scope counts under `ownership`. -The counter and the line carry only that fixed name, never a token, claim, client, subject, route parameter or record identifier, and they change nothing the caller receives. +Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and recording a refusal changes nothing the caller receives. A `visibility` count is a record that is absent or outside the boundary, and BReg does not say which, so it also counts a caller probing for identifiers. The audit journal's `refusalReason` stays the three values it lists below. @@ -506,8 +508,7 @@ The residuals refer to these obligations by number. Loopback HTTP is accepted for an issuer; anything else needs `authentication.oidc.allowInsecureHttp: true`, which is logged at startup and reported by `bregctl doctor` (`BREG-RES-17`). - Loopback means an address in `127.0.0.0/8`, `::1`, an IPv4-mapped form of a `127.0.0.0/8` - address, or the exact name `localhost`. + Loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name `localhost` in any letter case, which BReg connects to only through the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. A pinned key set (`authentication.oidc.jwksSource.type: static`) holds public keys only. BReg refuses a key that carries a private or symmetric member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth`, `k`), a repeated member name, a missing or repeated `kid`, or a key that does not match diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index 70832cf93b..6cf76aa755 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-18" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -162,15 +162,23 @@ grants in [Registry Casework task grants](../../reference/casework-task-grants/) separate_human_source_credentials_bind_before_empty_inbox_and_guard_mutations; crates/registry-casework/src/http/source_credentials.rs, verified_provider_handles_do_not_forward_casework_or_mix_invocations. */} -- Refusals the caller cannot tell apart are told apart in the operator's counter. A review or - administration request refused for its role, its profile's stage eligibility, an earlier - decision by the same person (separation of duties), a task the caller does not hold, a task - grant that is expired, invalidated or bound to another client, or a source that declines to - disclose, counts once under its own check in `casework_request_refusals_total` +- Casework counts every refused request by the check that refused it, in + `casework_request_refusals_total{check}` on the private metrics listener ([metrics](../../operate/casework/#scrape-metrics-and-the-running-version)). + The `check` label is a closed set of 45 names, every one published at zero, and no caller value + becomes a label. + Refusals the caller cannot tell apart are told apart there. + A review or administration request refused for its role, its profile's stage eligibility, an + earlier decision by the same person (separation of duties), a task the caller does not hold, a + task grant that is expired, invalidated or bound to another client, or a source that declines to + disclose, counts once under its own check. A target concealed as not found counts under `visibility`, or under the check that hid it. - The caller's answer is the same `operation.not-authorized` or `request.not-found` body as - before, so the counter is for the operator and tells the caller nothing. + Each refusal also writes one `request refused` log line with `failed_check` and the request's + trace id when it has one, at most five lines per check per minute, with `suppressed` counting what + a window held back. + Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and + recording a refusal changes nothing the caller receives: the answer is the same + `operation.not-authorized` or `request.not-found` body as before. {/* Evidence: crates/registry-casework/src/http.rs, impl From for HttpError; crates/registry-casework/src/review.rs, a_reviewer_who_already_acted_is_refused_for_separation_of_duties, diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 333d0b2120..c691fa564b 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -38,15 +38,18 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ Admission accepts a token only when its caller policy lists the token's exact `sub`, and refuses a delegated token (COORDINATOR-INV-10). Start input is the caller's assertion: Coordinator does not compare it with the caller's `sub`. -- Coordinator counts every refusal of a caller by the check that failed, in +- Coordinator counts every refused request by the check that refused it, in `coordinator_request_refusals_total{check}` on the private metrics listener. - It logs one `request refused` line with `failed_check` and the request's trace id, and at most - five lines per check per minute, with `suppressed` counting what a window held back. - The counter and the line carry only a fixed check name, never a token, claim, client, subject or - route value. + The `check` label is a closed set of 45 names, every one published at zero, and no caller value + becomes a label. The counter covers a refused credential, a policy denial after authentication, a refused signed event delivery or completion callback, an unreachable key source, and a run the caller cannot see. + Each refusal also writes one `request refused` log line with `failed_check` and the request's + trace id when it has one, at most five lines per check per minute, with `suppressed` counting what + a window held back. + Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and + recording a refusal changes nothing the caller receives. The older `coordinator_authentication_refusals_total{reason}` counter is unchanged. - Host users run `coordinatorctl`, which is local operator tooling for a trusted single-user machine. @@ -359,9 +362,12 @@ Enforcement: deleted with the wait. Inspection adds the connection's `requestLink` with the Proposal id filled in, only for a caller already authorised to inspect the run; the id grants nothing without BReg's own grant. - The link must be `https` unless its host is a loopback IP address (`127.0.0.0/8`, `::1` or an - IPv4-mapped form of `127.0.0.0/8`), the same rule as a connection endpoint; a host name such as `localhost` is refused because name resolution is outside - Coordinator's control. + The link must be `https` unless its host is a loopback IP address, the same rule as a connection + endpoint. + Loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` + address. + Coordinator accepts no name as loopback, not even `localhost`, because name resolution is outside + its control. - The run list finds waits on one Proposal through the keyed wait commitment over the database identity and the Proposal id, so neither the database nor the list cursor holds the id in clear. Each page reapplies the caller's owner and workflow scope, and a cursor is refused unless its diff --git a/docs/site/src/content/docs/security/documents.mdx b/docs/site/src/content/docs/security/documents.mdx index ae070d7b41..8082ca99d6 100644 --- a/docs/site/src/content/docs/security/documents.mdx +++ b/docs/site/src/content/docs/security/documents.mdx @@ -43,7 +43,8 @@ and the restore drill is in Members it does not know, such as `x5c` or `ext`, are ignored. - The operator's view of a refusal: the answer to the caller names a problem code and no cause, so an operator tells the causes apart from the private metrics listener and the log. - Every refused request is counted in `documents_request_refusals_total{check}`. + The Document Store counts every refused request by the check that refused it, in + `documents_request_refusals_total{check}` on the private metrics listener. The `check` label is a closed set of 45 names such as `credential-missing`, `token-signature`, `scope`, `actor-kind`, `access-profile`, `operation`, `ownership` and `visibility`, every one published at zero, and no caller value becomes a label. @@ -51,9 +52,9 @@ and the restore drill is in refused custody placement, a caller that sees a document but may not act on it, a document or upload the caller may not see, and a verifier that cannot reach its key source (`key-source-unavailable`). - Each refusal also writes one `request refused` log line that names the check. - The runtime writes at most five such lines per check per minute and reports how many it held back - in `suppressed`. + Each refusal also writes one `request refused` log line with `failed_check` and the request's + trace id when it has one, at most five lines per check per minute, with `suppressed` counting what + a window held back. A scope refusal carries a fixed remedy that names `authentication.oidc.scopeClaim`. Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and recording a refusal changes nothing the caller receives. @@ -113,6 +114,7 @@ Findings name the member and rule, never the value. `development-loopback` is the only listener setting that permits a disabled verifier or an `http` hook URL, and the hook URL must also be a loopback address. +Loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name `localhost` in any letter case, which the Document Store connects to only through the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. Do not set it in production. {/* Evidence: crates/registry-documents/src/config.rs diff --git a/docs/site/src/content/docs/security/evidence.mdx b/docs/site/src/content/docs/security/evidence.mdx index f3c20a4592..1ab855a8a7 100644 --- a/docs/site/src/content/docs/security/evidence.mdx +++ b/docs/site/src/content/docs/security/evidence.mdx @@ -41,16 +41,16 @@ A failed authentication, a malformed request, an invalid selector, and a rate limit write no native audit entry, even when Evidence decides them after authorisation. Watch for them in operational logs and metrics instead. -Evidence counts every `401`, `403` and `429` answer by the check that failed, in +Evidence counts every refused request by the check that refused it, in `evidence_request_refusals_total{check}` on the private metrics listener. The `check` label is a closed set of 45 names such as `credential-missing`, `token-signature`, `scope`, `access-profile`, -`purpose`, `revision-pin` and `rate-limit`, and no caller value becomes a label. Each refusal also -writes one `request refused` log line that names the check and the request's trace id. The runtime -writes at most five such lines per check per minute and reports how many it held back in -`suppressed`. The counter and the line carry only a fixed check name, never a token, claim, client, -selector value or requirement. The check is operator-side only: the response a caller receives is -the same closed `401`, `403` or `429` it always was. An issuer key set that cannot be reached -still answers `401`, and counts under `key-source-unavailable`. +`purpose`, `revision-pin` and `rate-limit`, every one published at zero, and no caller value becomes +a label. An issuer key set that cannot be reached still answers `401`, and counts under +`key-source-unavailable`. Each refusal also writes one `request refused` log line with +`failed_check` and the request's trace id when it has one, at most five lines per check per minute, +with `suppressed` counting what a window held back. Neither the counter nor the line holds a token, +claim, client, subject, scope or identifier, and recording a refusal changes nothing the caller +receives: the response is the same closed `401`, `403` or `429` it always was. {/* Evidence: crates/registry-evidence/src/observability.rs, record_refusal and Metrics::render; crates/registry-evidence/src/refusal_recording_tests.rs, diff --git a/docs/site/src/content/docs/security/hardening-checklist.mdx b/docs/site/src/content/docs/security/hardening-checklist.mdx index 8f7619fa73..fa79f897ee 100644 --- a/docs/site/src/content/docs/security/hardening-checklist.mdx +++ b/docs/site/src/content/docs/security/hardening-checklist.mdx @@ -8,7 +8,7 @@ source_repos: - registry-evidence - registry-breg - registry-casework -last_reviewed: "2026-11-20" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -165,6 +165,16 @@ Correct the responsible policy, grants, or credentials and rerun the test before components as well as the runtime. - Keep the refusal surface uninformative end to end. Do not let the edge add distinguishing error pages, redirects, or timing differences in front of the runtime's closed problem shapes. +- Alert on the runtime's refusal counter. Each runtime counts every refused request by the check that + refused it, in `_request_refusals_total{check}`, and writes one `request refused` log line + per refusal with no caller value. The line is limited to five per check per minute, so the counter + is the signal ([refused requests](../#refused-requests)). +- Treat loopback as one rule on every outbound destination. A host is loopback when it is an + address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name + `localhost`, which the runtime connects to only through loopback addresses. `a.localhost` and + `localhost.` are ordinary named hosts. Allow plain `http` only to loopback. +- Leave `allowedPrivateCidrs` out unless a destination needs a private address. An omitted or empty + list admits no private address. Name the smallest range that holds the service when one does. - Do not let an edge cache store an authenticated response. BReg, Casework and Registry Evidence mark such responses `no-store`. Render marks only its error responses, so set the cache policy for Render at the edge. diff --git a/docs/site/src/content/docs/security/index.mdx b/docs/site/src/content/docs/security/index.mdx index 1ad5566390..79607ab78f 100644 --- a/docs/site/src/content/docs/security/index.mdx +++ b/docs/site/src/content/docs/security/index.mdx @@ -8,7 +8,7 @@ source_repos: - registry-platform - registry-breg - registry-evidence -last_reviewed: "2026-11-20" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -164,9 +164,11 @@ Every product that validates access tokens fetches the issuer's keys under one s network policy: - The declared issuer and a declared key set URI may be on a private network or on loopback. - Loopback means a host written as a literal loopback address or `localhost`. A name that resolves - to a loopback address is refused. The operator who writes the runtime file is trusted to name - them. + Loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` + address, or the name `localhost` in any letter case, which the product connects to only through + the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. Any + other name that resolves to a loopback address is refused. The operator who writes the runtime + file is trusted to name them. - Cloud metadata and link-local addresses are refused for declared and discovered endpoints alike. - A key endpoint discovered on the issuer's own origin inherits the issuer's policy. On another origin it must use HTTPS and is refused when it resolves to a private or loopback address. @@ -206,6 +208,28 @@ verifier front end log no startup warning when `allowInsecureHttp` is on. crates/registry-messaging/src/config.rs, insecure_http_startup_diagnostic; crates/registry-scheduling/src/config.rs, insecure_http_startup_diagnostic. */} +## Refused requests + +Each runtime counts every refused request by the check that refused it, in +`_request_refusals_total{check}`, with a closed set of 45 checks that start at zero. +Each refusal also writes one `request refused` log line with `failed_check`, at most five lines per +check per minute, and no token, claim, scope value or client identifier. +The answer a caller receives does not change, so the counter is how an operator tells apart refusals +that look the same to the caller. +Alert on the counter, and not on a log line, because the line is rate limited. +The counter names the check and never the caller. +The labels `ownership` and `visibility` tell apart a target that exists from one that does not, so +keep metrics to the operator. +The product pages say what each counter covers: +[BReg](breg/), [Casework](casework/), [Coordinator](coordinator/), +[Document Store](documents/), [Evidence](evidence/), [Messaging](messaging/), [Render](render/) and +[Scheduling](scheduling/). + +{/* Evidence: crates/registry-platform-authcommon/src/refusal.rs; + crates/registry-breg/tests/golden/authentication_refusals.json; + crates/registry-messaging/tests/golden/refusals.json; + crates/registry-scheduling/tests/golden/refusal-answers.json. */} + ## Operator responsibilities Operators provide identity issuance, TLS and network controls, secret storage, key rotation, durable diff --git a/docs/site/src/content/docs/security/messaging.mdx b/docs/site/src/content/docs/security/messaging.mdx index df72d51486..57b0e335bb 100644 --- a/docs/site/src/content/docs/security/messaging.mdx +++ b/docs/site/src/content/docs/security/messaging.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-18" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -43,15 +43,17 @@ A verifier that cannot reach a verdict, because the issuer's discovery document fetched, read or used, is `503 service.unavailable` with `Retry-After: 5`; the credential is not what is wrong, so a caller should retry rather than rotate it. Causes inside each status are told apart only by operator-side signals, never in the response. -Every refused request is counted in `messaging_request_refusals_total{check}` on the private metrics -listener. The `check` label is a closed set of 45 names such as `token-signature`, `scope`, -`actor-kind`, `access-profile`, `delivery-signature` and `visibility`, and no caller value becomes a -label. Each refusal also writes one `request refused` log line that names the check and the -request's trace id. The runtime writes at most five such lines per check per minute and reports how -many it held back in `suppressed`. Where an operator can fix the cause in configuration, the line -carries a fixed remedy that names the setting, for example `accessProfiles` for `access-profile` or -`authentication.oidc.scopeClaim` for `scope`. A verifier that cannot reach its key source counts -under `key-source-unavailable`. +Messaging counts every refused request by the check that refused it, in +`messaging_request_refusals_total{check}` on the private metrics listener. The `check` label is a +closed set of 45 names such as `token-signature`, `scope`, `actor-kind`, `access-profile`, +`delivery-signature` and `visibility`, every one published at zero, and no caller value becomes a +label. A verifier that cannot reach its key source counts under `key-source-unavailable`. Each +refusal also writes one `request refused` log line with `failed_check` and the request's trace id +when it has one, at most five lines per check per minute, with `suppressed` counting what a window +held back. Where an operator can fix the cause in configuration, the line carries a fixed remedy +that names the setting, for example `accessProfiles` for `access-profile` or +`authentication.oidc.scopeClaim` for `scope`. Neither the counter nor the line holds a token, claim, +client, subject, scope or identifier, and recording a refusal changes nothing the caller receives. A static key set (`jwksSource: static`) holds public keys only. The runtime refuses to start on a set that carries a private member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth` or `k`), a symmetric key, a repeated member name, or a key without a unique `kid`, and the startup error names the rule and @@ -123,10 +125,10 @@ no `import`, `eval`, `print` or `debug`. SMTP requires `STARTTLS` or implicit TLS, verifies the certificate against the configured host name, sends no credential to a relay that does not offer `STARTTLS`, and cannot have a header line opened from template data. -Plain `http` and `development-loopback` SMTP are limited to loopback, which means an address in -`127.0.0.0/8`, `::1`, an IPv4-mapped form of a `127.0.0.0/8` address, or the exact name `localhost`. -No other name is loopback, so `localhost.` and `gateway.localhost` are refused. SMTP connects only -to the loopback address it checked. +Plain `http` and `development-loopback` SMTP are limited to loopback. +Loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name `localhost` in any letter case, which Messaging connects to only through the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. +SMTP refuses `localhost.` and `gateway.localhost`, and connects only to the loopback address it +checked. A production listener posture refuses plaintext SMTP at `messagingctl check` and at startup. (MESSAGING-SEC-03) diff --git a/docs/site/src/content/docs/security/render.mdx b/docs/site/src/content/docs/security/render.mdx index db50ddb0da..4f015c1bbc 100644 --- a/docs/site/src/content/docs/security/render.mdx +++ b/docs/site/src/content/docs/security/render.mdx @@ -213,16 +213,18 @@ rules only. ## How refusals are recorded -Render counts every refusal of a caller by the check that failed, in +Render counts every refused request by the check that refused it, in `render_request_refusals_total{check}` on the private metrics listener. -It writes one `request refused` log line with `failed_check` and the request's trace id, and at -most five lines per check per minute, with `suppressed` counting what a window held back. -The counter and the line carry only a fixed check name, never a token, claim, client, scope or -route value. +The `check` label is a closed set of 45 names, every one published at zero, and no caller value +becomes a label. The counter covers a missing or malformed credential, a legacy API key mismatch, a token the verifier refuses, an unreachable key source, a missing scope, the legacy key presented to the seal route, and a client that the seal's `allowedClients` does not list. -The answer a caller receives does not change. +Each refusal also writes one `request refused` log line with `failed_check` and the request's trace +id when it has one, at most five lines per check per minute, with `suppressed` counting what a +window held back. +Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and +recording a refusal changes nothing the caller receives. {/* Evidence: crates/registry-render/src/server.rs each_refusal_is_counted_and_logged_under_its_check, diff --git a/docs/site/src/content/docs/security/scheduling.mdx b/docs/site/src/content/docs/security/scheduling.mdx index b42afb76bc..0c9da29bc0 100644 --- a/docs/site/src/content/docs/security/scheduling.mdx +++ b/docs/site/src/content/docs/security/scheduling.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: explanation locale: en standards_referenced: [] @@ -49,6 +49,18 @@ callers holding bearer tokens from a configured issuer. The OIDC verifier and the grant expiry check at the door read the system clock. Hook delivery uses PostgreSQL `transaction_timestamp()`. The clock pin used in tests exists only in `postgres-test` builds (SCHEDULING-SEC-23). +- The operator's view of a refusal: Scheduling counts every refused request by the check that + refused it, in `scheduling_request_refusals_total{check}` on the private metrics listener + ([metrics](../../operate/scheduling/#watch-the-metrics)). + The `check` label is a closed set of 45 names, every one published at zero, and no caller value + becomes a label. + Each refusal also writes one `request refused` log line with `failed_check` and the request's + trace id when it has one, at most five lines per check per minute, with `suppressed` counting what + a window held back. + Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and + recording a refusal changes nothing the caller receives. + A hook or reminder destination in plain `http` must be on loopback. + Loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name `localhost` in any letter case, which Scheduling connects to only through the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. {/* Evidence: products/scheduling/contracts/security-invariant-matrix.yaml SCHEDULING-SEC-03, SCHEDULING-SEC-04, SCHEDULING-SEC-05, SCHEDULING-SEC-14, SCHEDULING-SEC-23, SCHEDULING-SEC-29, diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index e5070c69e7..835074ae82 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -2,6 +2,35 @@ ## Unreleased +- BREAKING: an Adapter job whose runtime document names a plain `http://` + endpoint by host name must now list the address range that host resolves to + in `allowedPrivateCidrs`. An omitted or empty list admits no private + address, where before it admitted every one for such a host. To migrate, add + the smallest range that contains the endpoint, serve the endpoint over + https, or bind it on loopback. An affected job now fails `check` with + `adapter.runtime.insecure-origin`. The job host's hook ingress also counts + and logs every refused credential and rate limit under + `adapter_job_request_refusals_total{check}`, with no answer change, and the + fixture destination and the plaintext test RabbitMQ and PostgreSQL sources + use the Adapter's one loopback definition (the RabbitMQ and PostgreSQL test + sources still take address literals only). +- The payment routes count and log every refused caller under the check that + refused it, in the same `adapter_request_refusals_total{check}` counter and + `request refused` line as the facade. No answer changes. The simulator + provider connection and a payment provider base URL accept the same + loopback address literals as the rest of the Adapter (the rest of + `127.0.0.0/8`, `::1` and the IPv4-mapped forms) and still refuse the name + `localhost`. +- The facade counts and logs every refused caller under the check that + refused it. `adapter_request_refusals_total{check}` rises by one and the log + carries one `request refused` line with the fixed `failed_check` label, at + most five lines per check per minute, replacing the per-stage + authentication log line. No answer changes. Loopback is one definition + everywhere the Adapter decides it: the rest of `127.0.0.0/8`, `::1` and the + IPv4-mapped forms count beside `127.0.0.1`, the name `localhost` is pinned to + loopback addresses, and `a.localhost` and `localhost.` stay named hosts. A + plain `http://` origin named by host name now fails the runtime check with + `adapter.runtime.insecure-origin` when `allowedPrivateCidrs` is empty. - The facade listener answers `GET /health` and `GET /ready` without authentication. `/health` answers `{"status":"ok"}`. `/ready` answers `{"status":"ready"}` when the journal migrations match the binary and the From 7beeba84fcf8006d4de85199cc193b3293dacd4b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:05:37 +0100 Subject: [PATCH 037/136] fix: count Scheduling and Evidence refusals under their precise checks fix(scheduling): count each refusal under the check that refused it and keep unknown ids indistinguishable A grant or token that lapses inside the capacity transaction now counts under task-grant-expired instead of ownership, and a reads-scope caller reading another owner's appointment counts under ownership. The classification of refusal codes is exhaustive. On release, confirm, reschedule, attendance and cancel, a grant whose remaining lifetime is too long answers operation.not-authorized, the same answer as a hold or appointment that does not exist. The counter still records task-grant-lifetime. grant.lifetime-too-long is answered only when creating a hold or an appointment, and the OpenAPI document lists it there alone. docs(scheduling): cite the renamed offline-path test on the task-grants page fix(evidence): name each refusal check precisely with no change to any answer An expired task grant counts under task-grant-expired at the request as it does at release, and a grant bound to another principal counts under task-grant-binding. A caller whose actor kind or audience falls outside a definition's grant ceiling counts under actor-kind or access-profile unless it presented a task grant. The key-source WARN line follows the same classification as the key-source-unavailable count. OID4VP states the rule a refused static key set broke in its startup message, still under evidence.oid4vp.issuer-unavailable, and counts an Authorization header that is present but not readable as text under credential-malformed. Each wallet service's refusal log line carries the check name, and the refusal golden files cover an expired task grant and an unreachable key set. Signed-off-by: Jeremi Joslin --- .../src/authorizer.rs | 1 + .../registry-evidence-oid4vci/src/service.rs | 87 +++++--- .../tests/golden/refusals.json | 12 + crates/registry-evidence-oid4vp/src/auth.rs | 9 +- .../registry-evidence-oid4vp/src/metrics.rs | 33 +++ .../registry-evidence-oid4vp/src/service.rs | 43 ++-- .../tests/common/mod.rs | 23 +- .../tests/golden/refusals.json | 15 ++ .../tests/refusal_golden.rs | 12 + .../tests/refusal_recording.rs | 50 +++++ .../registry-evidence-oid4vp/tests/startup.rs | 41 ++++ crates/registry-evidence/src/auth.rs | 85 ++++--- crates/registry-evidence/src/observability.rs | 6 +- .../src/refusal_recording_tests.rs | 21 ++ crates/registry-evidence/src/runtime.rs | 24 ++ crates/registry-evidence/src/runtime_tests.rs | 13 ++ crates/registry-evidence/src/selector.rs | 50 +++-- .../tests/golden/refusal_answers.json | 18 ++ .../tests/selector_conformance.rs | 75 ++++++- crates/registry-scheduling/src/auth.rs | 48 +++- crates/registry-scheduling/src/http.rs | 9 +- crates/registry-scheduling/src/lib.rs | 1 + crates/registry-scheduling/src/refusal.rs | 77 +++++++ crates/registry-scheduling/src/service.rs | 117 +++++----- crates/registry-scheduling/src/store.rs | 10 +- .../tests/postgres_commitments.rs | 12 + .../review_regressions.rs | 208 ++++++++++++++++++ .../src/content/docs/operate/stuck-work.mdx | 2 +- .../reference/apis/registry-scheduling.mdx | 6 +- .../docs/reference/scheduling-task-grants.mdx | 8 +- .../src/content/docs/security/evidence.mdx | 18 +- .../src/content/docs/security/scheduling.mdx | 9 +- products/evidence/CHANGELOG.md | 12 + products/evidence/OPERATOR-CONTRACT.md | 34 ++- .../evidence/contracts/oid4vci-profile.yaml | 3 +- .../contracts/security-invariant-matrix.yaml | 2 +- .../contracts/security-test-traceability.yaml | 1 + products/scheduling/CHANGELOG.md | 28 ++- .../contracts/recorded-decisions.yaml | 7 + .../contracts/security-invariant-matrix.yaml | 4 +- .../registry-scheduling.openapi.json | 25 +-- .../scheduling/scripts/generate_openapi.py | 23 +- .../scripts/test_generate_openapi.py | 19 +- 43 files changed, 1063 insertions(+), 238 deletions(-) create mode 100644 crates/registry-scheduling/src/refusal.rs diff --git a/crates/registry-evidence-oid4vci/src/authorizer.rs b/crates/registry-evidence-oid4vci/src/authorizer.rs index b029c310e9..8f13472049 100644 --- a/crates/registry-evidence-oid4vci/src/authorizer.rs +++ b/crates/registry-evidence-oid4vci/src/authorizer.rs @@ -63,6 +63,7 @@ pub enum AuthorizationError { impl AuthorizationError { /// The check the request failed. #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] pub const fn failed_check(&self) -> FailedCheck { match self { Self::Missing => FailedCheck::CredentialMissing, diff --git a/crates/registry-evidence-oid4vci/src/service.rs b/crates/registry-evidence-oid4vci/src/service.rs index 2f35ec22f1..b86d33c2cd 100644 --- a/crates/registry-evidence-oid4vci/src/service.rs +++ b/crates/registry-evidence-oid4vci/src/service.rs @@ -1523,22 +1523,24 @@ async fn authorize_offer( .authorizer .authorize(credential) .await - .map_err(|error| match error { - AuthorizationError::Missing => unauthorized( - FailedCheck::CredentialMissing, - "a bearer access token is required", - ), - AuthorizationError::Refused(check) => { - unauthorized(check, "the presented credential was refused") - } - AuthorizationError::KeySource => refused( - problem( - StatusCode::SERVICE_UNAVAILABLE, - "temporarily_unavailable", - "offers cannot be authorized at the moment", + .map_err(|error| { + let check = error.failed_check(); + match error { + AuthorizationError::Missing => { + unauthorized(check, "a bearer access token is required") + } + AuthorizationError::Refused(_) => { + unauthorized(check, "the presented credential was refused") + } + AuthorizationError::KeySource => refused( + problem( + StatusCode::SERVICE_UNAVAILABLE, + "temporarily_unavailable", + "offers cannot be authorized at the moment", + ), + check, ), - FailedCheck::KeySourceUnavailable, - ), + } }) } @@ -1933,6 +1935,16 @@ mod tests { } } + /// An authorizer whose issuer key set cannot be reached. + struct UnreachableKeySetAuthorizer; + + #[async_trait] + impl OfferAuthorizer for UnreachableKeySetAuthorizer { + async fn authorize(&self, _: &str) -> Result { + Err(AuthorizationError::KeySource) + } + } + /// Records every request it is asked to issue, and answers with one /// credential per holder key. struct RecordingIssuer { @@ -5388,6 +5400,16 @@ mod tests { (TestServer::new(build_app(Arc::clone(&service))), service) } + fn unreachable_key_set_server(directory: &Path) -> (TestServer, Arc) { + let service = Arc::new(DeliveryService::with_halves( + load_deployment(directory), + Arc::new(UnreachableKeySetAuthorizer), + Arc::new(RecordingIssuer::new()), + test_audit(), + )); + (TestServer::new(build_app(Arc::clone(&service))), service) + } + fn draft13_server(directory: &Path) -> (TestServer, Arc) { let mut config = load_deployment(directory); config.draft13_profile = true; @@ -5578,10 +5600,24 @@ mod tests { offers().await, ); + // An issuer key set that cannot be reached. + let (unreachable, service) = unreachable_key_set_server(directory.path()); + services.push(service); + current.set(3); + put( + "offer-key-source-unavailable", + Some(FailedCheck::KeySourceUnavailable), + unreachable + .post(OFFERS_PATH) + .add_header("authorization", format!("Bearer {OFFER_TOKEN}")) + .json(&offer_body(false)) + .await, + ); + // Evidence refusing. let (refused_catalog, service) = refusing_server(directory.path(), true); services.push(service); - current.set(3); + current.set(4); put( "offer-evidence-refused", Some(FailedCheck::SourceAuthority), @@ -5593,7 +5629,7 @@ mod tests { ); let (refused_issue, service) = refusing_server(directory.path(), false); services.push(service); - current.set(4); + current.set(5); let token = access_token(&refused_issue).await; let nonce = minted_nonce(&refused_issue).await; let key = private_jwk("refusal-golden"); @@ -5644,13 +5680,10 @@ mod tests { /// it, nothing else is counted, and the log carries fixed lines only. #[tokio::test] async fn each_refusal_is_counted_and_logged_under_its_check() { - let buffer = TestLogBuffer::default(); - let subscriber = tracing_subscriber::fmt() - .without_time() - .with_ansi(false) - .with_writer(buffer.clone()) - .finish(); - let _logging = tracing::subscriber::set_default(subscriber); + // The shared capture keeps a parallel test that reaches the refusal + // callsite with no subscriber from disabling it for this one. + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let _logging = tracing::dispatcher::set_default(&captured.subscriber()); let (cases, services) = refusal_cases().await; for (index, service) in services.iter().enumerate() { @@ -5674,13 +5707,11 @@ mod tests { ); } } - let rendered = String::from_utf8(buffer.0.lock().expect("log buffer lock").clone()) - .expect("logs are UTF-8"); + let rendered = captured.text(); for (name, check, _, _) in &cases { let check = check.expect("every case names its check"); assert!( - rendered.contains(&format!("failed_check=\"{}\"", check.as_str())) - || rendered.contains(&format!("failed_check={}", check.as_str())), + rendered.contains(&format!("\"failed_check\":\"{}\"", check.as_str())), "{name}: no log line for {}: {rendered}", check.as_str() ); diff --git a/crates/registry-evidence-oid4vci/tests/golden/refusals.json b/crates/registry-evidence-oid4vci/tests/golden/refusals.json index db0fbd2f3b..d2c0b0463c 100644 --- a/crates/registry-evidence-oid4vci/tests/golden/refusals.json +++ b/crates/registry-evidence-oid4vci/tests/golden/refusals.json @@ -113,6 +113,18 @@ }, "status": 403 }, + "offer-key-source-unavailable": { + "body": { + "error": "temporarily_unavailable", + "error_description": "offers cannot be authorized at the moment" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 503 + }, "offer-no-header": { "body": { "error": "invalid_token", diff --git a/crates/registry-evidence-oid4vp/src/auth.rs b/crates/registry-evidence-oid4vp/src/auth.rs index 4e568fc335..184be04511 100644 --- a/crates/registry-evidence-oid4vp/src/auth.rs +++ b/crates/registry-evidence-oid4vp/src/auth.rs @@ -34,6 +34,7 @@ pub enum AuthError { impl AuthError { /// The check the request failed. #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] pub const fn failed_check(&self) -> FailedCheck { match self { Self::Refused(check) => *check, @@ -51,8 +52,10 @@ pub enum AuthSetupError { Discovery, #[error("the static key set secret could not be read")] StaticKeySecret, - #[error("the static key set is not a valid JWKS")] - StaticKeySet, + /// The validator's account of the rule the document broke. It names a key + /// position and a member, never a value. + #[error("the static key set is not a valid JWKS: {0}")] + StaticKeySet(String), } /// Verifies bearer tokens from one issuer and extracts the caller. @@ -111,7 +114,7 @@ impl TokenAuthenticator { .resolve(document_ref) .map_err(|_| AuthSetupError::StaticKeySecret)?; let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| AuthSetupError::StaticKeySet)?; + .map_err(|error| AuthSetupError::StaticKeySet(error.to_string()))?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; diff --git a/crates/registry-evidence-oid4vp/src/metrics.rs b/crates/registry-evidence-oid4vp/src/metrics.rs index d9533f1fe2..db98facfdb 100644 --- a/crates/registry-evidence-oid4vp/src/metrics.rs +++ b/crates/registry-evidence-oid4vp/src/metrics.rs @@ -185,3 +185,36 @@ async fn scrape(State(state): State) -> Response { Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), } } + +#[cfg(test)] +mod tests { + use registry_platform_authcommon::FailedCheck; + + use super::*; + use crate::session::system_clock; + + #[test] + fn the_scrape_publishes_every_check_at_zero_and_counts_a_refusal_under_its_check() { + let metrics = Metrics::new().expect("the metrics declare"); + let store = SessionStore::new(4, 1024, system_clock()); + let scrape = metrics.render(&store).expect("the scrape renders"); + for check in FailedCheck::ALL { + let series = format!( + "evidence_oid4vp_request_refusals_total{{check=\"{}\"}} ", + check.as_str() + ); + assert!( + scrape.contains(&format!("{series}0")), + "{} is published at zero", + check.as_str() + ); + } + + assert!(metrics + .refusal_recorder() + .record(FailedCheck::Scope) + .is_some()); + let scrape = metrics.render(&store).expect("the scrape renders"); + assert!(scrape.contains("evidence_oid4vp_request_refusals_total{check=\"scope\"} 1")); + } +} diff --git a/crates/registry-evidence-oid4vp/src/service.rs b/crates/registry-evidence-oid4vp/src/service.rs index 7a10912c20..c176fbc9ec 100644 --- a/crates/registry-evidence-oid4vp/src/service.rs +++ b/crates/registry-evidence-oid4vp/src/service.rs @@ -40,7 +40,7 @@ use zeroize::Zeroizing; use crate::{ audit::{AuditFailure, Pending, SessionAudit}, - auth::{AuthError, TokenAuthenticator}, + auth::{AuthError, AuthSetupError, TokenAuthenticator}, client_identifier::RequestIdentity, config::{Oid4vpConfig, PolicyConfig}, metrics::{metrics_app, Event, Metrics}, @@ -96,7 +96,7 @@ impl StartupError { fn new( code: &'static str, pointer: &'static str, - message: &'static str, + message: impl Into, action: &'static str, ) -> Self { Self { @@ -205,11 +205,11 @@ impl VerifierService { let jwks = (!keys.is_empty()).then(|| json!({ "keys": keys }).to_string()); let applicants = TokenAuthenticator::build(&config.applicant_tokens, &resolver) .await - .map_err(|_| issuer_unavailable("/applicantTokens"))?; + .map_err(|error| issuer_unavailable("/applicantTokens", &error))?; let evidence_credentials = TokenAuthenticator::build(&config.evidence_credentials, &resolver) .await - .map_err(|_| issuer_unavailable("/evidenceCredentials"))?; + .map_err(|error| issuer_unavailable("/evidenceCredentials", &error))?; let audit_key = resolver .resolve_binary_reference(&config.audit.key.hash_key_ref) @@ -376,12 +376,24 @@ impl VerifierService { } } -fn issuer_unavailable(pointer: &'static str) -> StartupError { +fn issuer_unavailable(pointer: &'static str, error: &AuthSetupError) -> StartupError { + // A static key set the validator refused says which rule it broke, so the + // fix starts at the document rather than at the issuer's reachability. + let (message, action) = match error { + AuthSetupError::StaticKeySet(refusal) => ( + refusal.clone(), + "Replace the document behind jwksSource.documentRef with a public key set that follows the rule named here.", + ), + _ => ( + "the token issuer or its key source could not be set up".to_owned(), + "Check the issuer, its key source, and that the service can reach it.", + ), + }; StartupError::new( "evidence.oid4vp.issuer-unavailable", pointer, - "the token issuer or its key source could not be set up", - "Check the issuer, its key source, and that the service can reach it.", + message, + action, ) } @@ -619,11 +631,18 @@ async fn ready(State(service): State>) -> Response { } } +/// The `Authorization` header as text. A header that is present but not +/// readable as text reads as an empty value, which the authenticator refuses as +/// a malformed credential rather than counting it as absent. +fn authorization_header(headers: &HeaderMap) -> Option<&str> { + headers + .get(AUTHORIZATION) + .map(|value| value.to_str().unwrap_or_default()) +} + /// Authenticate the applicant, or return the response that refuses them. async fn applicant(service: &VerifierService, headers: &HeaderMap) -> Result { - let authorization = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()); + let authorization = authorization_header(headers); match service.applicants.authenticate(authorization).await { Ok(principal) => Ok(principal), Err(AuthError::KeySource) => { @@ -1193,9 +1212,7 @@ async fn read_presentation( headers: HeaderMap, body: Bytes, ) -> Response { - let authorization = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()); + let authorization = authorization_header(&headers); let reader = match service .evidence_credentials .authenticate(authorization) diff --git a/crates/registry-evidence-oid4vp/tests/common/mod.rs b/crates/registry-evidence-oid4vp/tests/common/mod.rs index 2fa48c91ab..e07173a257 100644 --- a/crates/registry-evidence-oid4vp/tests/common/mod.rs +++ b/crates/registry-evidence-oid4vp/tests/common/mod.rs @@ -73,6 +73,12 @@ pub struct Options { pub wallet_response_burst: u32, pub response_burst_per_request: u32, pub evidence_read_burst: u32, + /// Serve the applicant-token key set from this static document instead of + /// the test issuer's key endpoint. + pub applicant_static_jwks: Option<&'static str>, + /// Fetch the applicant-token key set from this URI instead of the test + /// issuer's key endpoint. + pub applicant_jwks_uri: Option<&'static str>, } impl Default for Options { @@ -92,6 +98,8 @@ impl Default for Options { wallet_response_burst: 50, response_burst_per_request: 20, evidence_read_burst: 50, + applicant_static_jwks: None, + applicant_jwks_uri: None, } } } @@ -235,6 +243,18 @@ impl Harness { keys.registered_jwk.as_bytes(), ); write_secret(&secrets, "audit-hash-key", &[7u8; 48]); + let applicant_jwks_source = match options.applicant_static_jwks { + Some(document) => { + write_secret(&secrets, "applicant-jwks.json", document.as_bytes()); + "type: static\n documentRef: secret:file/applicant-jwks.json".to_owned() + } + None => format!( + "type: uri\n uri: {}", + options + .applicant_jwks_uri + .map_or_else(|| idp.jwks_uri().to_string(), str::to_owned) + ), + }; let audit_path = dir.path().join("audit.jsonl"); let authorities = if options.trusted_authorities { @@ -296,8 +316,7 @@ applicantTokens: audience: {AUDIENCE} allowInsecureHttp: true jwksSource: - type: uri - uri: {jwks} + {applicant_jwks_source} algorithms: [EdDSA] requiredScope: {SESSION_SCOPE} evidenceCredentials: diff --git a/crates/registry-evidence-oid4vp/tests/golden/refusals.json b/crates/registry-evidence-oid4vp/tests/golden/refusals.json index 72d8ba3f91..3a6eaeaee2 100644 --- a/crates/registry-evidence-oid4vp/tests/golden/refusals.json +++ b/crates/registry-evidence-oid4vp/tests/golden/refusals.json @@ -14,6 +14,21 @@ }, "status": 401 }, + "create-key-source-unavailable": { + "body": { + "detail": "the token issuer is unavailable", + "status": 503, + "title": "Service Unavailable", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/issuer-unavailable" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "5", + "x-content-type-options": "nosniff" + }, + "status": 503 + }, "create-no-header": { "body": { "detail": "a valid bearer token is required", diff --git a/crates/registry-evidence-oid4vp/tests/refusal_golden.rs b/crates/registry-evidence-oid4vp/tests/refusal_golden.rs index 9082c4c13b..a5e274999a 100644 --- a/crates/registry-evidence-oid4vp/tests/refusal_golden.rs +++ b/crates/registry-evidence-oid4vp/tests/refusal_golden.rs @@ -249,6 +249,18 @@ async fn answers() -> Value { assert_eq!(first.status_code().as_u16(), 400); put("response-rate-limited", &form(&server).await); + let unreachable = Harness::new(&Options { + applicant_jwks_uri: Some("http://127.0.0.1:1/jwks"), + ..Options::default() + }) + .await; + let (down, _) = unreachable.server().await; + let down_token = unreachable.applicant_token("portal", "user-1"); + put( + "create-key-source-unavailable", + &create(&down, Some(&bearer(&down_token))).await, + ); + Value::Object(answers) } diff --git a/crates/registry-evidence-oid4vp/tests/refusal_recording.rs b/crates/registry-evidence-oid4vp/tests/refusal_recording.rs index 11bb320df9..5aa87ca0ba 100644 --- a/crates/registry-evidence-oid4vp/tests/refusal_recording.rs +++ b/crates/registry-evidence-oid4vp/tests/refusal_recording.rs @@ -203,6 +203,25 @@ async fn each_refusal_is_counted_and_logged_under_its_check() { create(Some("Bearer canary-token-7f3a".to_owned())).into_future(), ) .await; + // A credential the server cannot read as text was sent, so it is + // malformed rather than missing. + expect( + s, + l, + c, + FailedCheck::CredentialMalformed, + 401, + server + .post("/v1/sessions") + .add_header( + "authorization", + axum::http::HeaderValue::from_bytes(b"Bearer \x80\x81 canary-token-7f3a") + .expect("a byte above 0x7F is a legal header value"), + ) + .json(&json!({"policy": "national-id"})) + .into_future(), + ) + .await; expect( s, l, @@ -300,6 +319,16 @@ async fn each_refusal_is_counted_and_logged_under_its_check() { ) .await; + expect( + s, + l, + c, + FailedCheck::CredentialMalformed, + 401, + create(Some("Bearer canary-token-7f3a".to_owned())).into_future(), + ) + .await; + // A read of a reference nobody holds is not recorded: the consult maps // only another principal's session. let before = total(&service); @@ -307,6 +336,27 @@ async fn each_refusal_is_counted_and_logged_under_its_check() { assert_eq!(absent.status_code().as_u16(), 404); assert_eq!(total(&service), before); + // An issuer key set that cannot be reached answers 503 and is counted. + let unreachable = Harness::new(&Options { + applicant_jwks_uri: Some("http://127.0.0.1:1/jwks"), + ..Options::default() + }) + .await; + let (down, down_service) = unreachable.server().await; + let down_token = unreachable.applicant_token("portal", "user-1"); + expect( + &down_service, + &logs, + &canaries, + FailedCheck::KeySourceUnavailable, + 503, + down.post("/v1/sessions") + .add_header("authorization", bearer(&down_token)) + .json(&json!({"policy": "national-id"})) + .into_future(), + ) + .await; + // Spent budgets, each in a deployment whose burst is one. let limited = Harness::new(&Options { session_creation_burst: 1, diff --git a/crates/registry-evidence-oid4vp/tests/startup.rs b/crates/registry-evidence-oid4vp/tests/startup.rs index b44faf7b09..7e21509d8c 100644 --- a/crates/registry-evidence-oid4vp/tests/startup.rs +++ b/crates/registry-evidence-oid4vp/tests/startup.rs @@ -559,3 +559,44 @@ async fn startup_code_for(harness: &Harness) -> String { .code .clone() } + +const PUBLIC_KEY_WITH_EXT: &str = r#"{"keys":[{"kty":"EC","crv":"P-256","kid":"issuer-key","ext":true,"x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}]}"#; +const KEY_WITH_PRIVATE_MEMBER: &str = r#"{"keys":[{"kty":"EC","crv":"P-256","kid":"issuer-key","d":"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}]}"#; + +#[tokio::test] +async fn a_static_key_set_with_an_ext_member_loads() { + let harness = Harness::new(&Options { + applicant_static_jwks: Some(PUBLIC_KEY_WITH_EXT), + ..Options::default() + }) + .await; + harness + .try_service() + .await + .expect("a public key with an ext member is a valid static key set"); +} + +#[tokio::test] +async fn a_static_key_set_with_a_private_member_is_refused_with_the_validator_text() { + let harness = Harness::new(&Options { + applicant_static_jwks: Some(KEY_WITH_PRIVATE_MEMBER), + ..Options::default() + }) + .await; + let error = harness + .try_service() + .await + .expect_err("a key set holding a private member is refused at startup"); + let diagnostic = error.diagnostic(); + assert_eq!(diagnostic.code, "evidence.oid4vp.issuer-unavailable"); + assert_eq!(diagnostic.path, "/applicantTokens"); + assert!( + diagnostic.message.contains("private-key member \"d\""), + "the startup message names the broken rule: {}", + diagnostic.message + ); + assert!( + !diagnostic.message.contains("jpsQnnGQmL"), + "the key material is never repeated" + ); +} diff --git a/crates/registry-evidence/src/auth.rs b/crates/registry-evidence/src/auth.rs index 09a815441d..ae9c0686d2 100644 --- a/crates/registry-evidence/src/auth.rs +++ b/crates/registry-evidence/src/auth.rs @@ -118,6 +118,8 @@ pub struct AuthenticatedContext { pub enum TaskGrantError { #[error("task-grant claims are invalid")] Claims, + #[error("task grant has expired")] + Expired, #[error("task-grant principal does not match the authenticated principal")] PrincipalMismatch, #[error("task-grant client context is invalid")] @@ -547,8 +549,12 @@ impl Authenticator { .map_err(|_| AuthenticationError::Context(FailedCheck::TokenTime))? .as_secs(); let mut task_grant = - grant_claims(&verified.claims, &self.claims.contextual_claims, now_unix) - .map_err(|_: ClaimError| TaskGrantError::Claims); + grant_claims(&verified.claims, &self.claims.contextual_claims, now_unix).map_err( + |error| match error { + ClaimError::Expired => TaskGrantError::Expired, + _ => TaskGrantError::Claims, + }, + ); let claims = serde_json::to_value(&verified.claims).map_err(|_| AuthenticationError::claims())?; let claims_object = claims.as_object().ok_or_else(AuthenticationError::claims)?; @@ -666,41 +672,10 @@ fn jwks_fetch_policy(config: &OidcAuthenticationConfig) -> FetchUrlPolicy { } /// Whether a verification failure was this deployment's key source rather than -/// the caller's token. -/// -/// Every known failure is listed rather than folded into the wildcard, which -/// covers only variants added to the shared verifier after this was written. -/// Those default to the caller's side: a failure this code has never seen is -/// one it cannot honestly describe as an unreachable key set, and an operator -/// misdirected by a confident wrong message is worse off than one who reads -/// the same `auth.invalid-credential` twice. +/// the caller's token. The shared verifier owns the classification, so the +/// operator log line and the `key-source-unavailable` count agree. fn is_key_source_failure(error: &OidcError) -> bool { - match error { - OidcError::Transport(_) - | OidcError::BoundedRead(_) - | OidcError::FetchUrl(_) - | OidcError::HttpStatus(_) - | OidcError::InvalidUrl - | OidcError::Parse - | OidcError::InvalidJwk - | OidcError::EmptyKeySet - | OidcError::MissingIssuer => true, - OidcError::IssuerMismatch { .. } - | OidcError::MalformedToken - | OidcError::AlgorithmNotAllowed - | OidcError::TokenTypeNotAllowed - | OidcError::MissingKid - | OidcError::KidTooLong - | OidcError::UnknownKid - | OidcError::TokenExpired - | OidcError::TokenNotYetValid - | OidcError::AudienceMismatch - | OidcError::SignatureInvalid - | OidcError::InvalidToken - | OidcError::ClientNotAllowed - | OidcError::AssertionIssuerNotAllowed => false, - _ => false, - } + error.is_key_source_unavailable() } /// Render an error together with the causes beneath it, bounded. @@ -1215,6 +1190,44 @@ mod tests { assert_eq!(context.grant(), Err(TaskGrantError::PrincipalMismatch)); } + #[test] + fn an_expired_task_grant_is_kept_apart_from_a_malformed_one() { + let now = chrono::Utc::now().timestamp(); + let claims = |grant_exp: i64| { + serde_json::from_value(serde_json::json!({ + "iss": "https://issuer.invalid", + "aud": "evidence-resource", + "sub": "institutional-agent", + "exp": now + 300, + "registry_actor_kind": "agent", + "registry_purpose": "eligibility-check", + "registry_grant_id": "grant-1", + "registry_grant_source_issuer": "https://casework.invalid", + "registry_grant_client": "evidence-agent", + "registry_grant_resource": "evidence-resource", + "registry_grant_exp": grant_exp, + "registry_grant_bounds": {"type":"evidence", "requirement":"urn:example:requirement"}, + "registry_approver": "h:synthetic-approver", + "evidence_tags": ["caseworker"], + "evidence_audience": "https://relying-party.invalid" + })) + .expect("claims parse") + }; + let grant_of = |claims| { + context_extraction_authenticator("sub") + .extract_context(VerifiedToken { + claims, + matched_client: Some("client_id:evidence-agent".to_owned()), + scopes: Vec::new(), + }) + .expect("verified product context extracts") + .grant() + .map(|grant| grant.is_some()) + }; + assert_eq!(grant_of(claims(now - 1)), Err(TaskGrantError::Expired)); + assert_eq!(grant_of(claims(now + 300)), Ok(true)); + } + #[test] fn token_without_actor_kind_is_refused_during_context_extraction() { let now = chrono::Utc::now().timestamp(); diff --git a/crates/registry-evidence/src/observability.rs b/crates/registry-evidence/src/observability.rs index e779b66fd1..4b6e663744 100644 --- a/crates/registry-evidence/src/observability.rs +++ b/crates/registry-evidence/src/observability.rs @@ -24,6 +24,10 @@ //! drifted from the declared projection and emits rate-limited operator WARN //! records that name the source, declared JSON pointers, and closed reasons, //! never a response value, an undeclared member name, a selector, or a subject. +//! +//! The refusal counter is the second exception. Its `check` label is the +//! closed [`FailedCheck`](registry_platform_authcommon::FailedCheck) set, fixed +//! and zero-filled at construction, so no request can extend it. use std::{ collections::BTreeMap, @@ -268,7 +272,7 @@ fn record_response_refusal(metrics: &Metrics, response: &Response, operation: &O .is_some_and(|code| is_refusal_code(*code)) { tracing::error!( - target: "registry_evidence::refusal", + target: module_path!(), trace_id = operation.trace_id().as_str(), "a refusal was answered without the check that failed" ); diff --git a/crates/registry-evidence/src/refusal_recording_tests.rs b/crates/registry-evidence/src/refusal_recording_tests.rs index 92d02e9409..1ba5e5dc7f 100644 --- a/crates/registry-evidence/src/refusal_recording_tests.rs +++ b/crates/registry-evidence/src/refusal_recording_tests.rs @@ -244,6 +244,17 @@ fn scenarios() -> Vec { unauthorized, FailedCheck::TokenClaims, ), + evidence( + "expired-task-grant", + Credential::Token(access_token(Some({ + let mut grant = parent_grant_claims(); + grant["registry_grant_exp"] = json!(now - 1); + grant + }))), + adult(), + forbidden, + FailedCheck::TaskGrantExpired, + ), Scenario { name: "batch-without-credential", method: "POST", @@ -516,5 +527,15 @@ async fn a_request_over_the_rate_budget_is_counted_under_rate_limit() { .await; assert_eq!(limited.status_code(), StatusCode::TOO_MANY_REQUESTS); assert_eq!(limited.header("retry-after"), "1"); + assert_eq!(limited.header("content-type"), "application/problem+json"); + assert_eq!(limited.header("cache-control"), "no-store"); + let body: Value = limited.json(); + assert_eq!(body["status"], json!(429)); + assert_eq!(body["code"], json!("evidence.rate-limited")); + assert_eq!(body["title"], json!("Evidence request rate is exhausted")); + assert_eq!( + body["detail"], + json!("the Evidence request rate is exhausted") + ); assert_eq!(counted(&metrics.render(), FailedCheck::RateLimit), 1); } diff --git a/crates/registry-evidence/src/runtime.rs b/crates/registry-evidence/src/runtime.rs index e19284b41c..2e8652295f 100644 --- a/crates/registry-evidence/src/runtime.rs +++ b/crates/registry-evidence/src/runtime.rs @@ -4589,6 +4589,11 @@ mod tests { let failure = pack_source_failure(error); assert_eq!(failure.problem, problem); assert_eq!(failure.category, category); + assert_eq!( + failure.check(), + (category == "source-authority").then_some(FailedCheck::SourceAuthority), + "only the authority refusal is recorded as a refusal: {category}" + ); assert!( categories.insert(category), "two pack failures share the category {category}" @@ -4601,6 +4606,25 @@ mod tests { } } + #[test] + fn refusals_built_outside_the_request_path_carry_the_check_that_refused() { + let channel = acquisition_channel_refusal(); + assert_eq!(channel.problem(), ProblemCode::NotAuthorized); + assert_eq!(channel.check(), Some(FailedCheck::AcquisitionChannel)); + + let request_rate = map_request_limit(RateLimitError::RequestExceeded); + assert_eq!(request_rate.problem(), ProblemCode::RateLimited); + assert_eq!(request_rate.check(), Some(FailedCheck::RateLimit)); + let selector_rate = map_selector_limit(RateLimitError::FailedSelectorExceeded); + assert_eq!(selector_rate.problem(), ProblemCode::RateLimited); + assert_eq!(selector_rate.check(), Some(FailedCheck::RateLimit)); + assert_eq!( + map_request_limit(RateLimitError::CostExceedsBurst).check(), + None, + "a request the burst can never hold is not a rate-limit refusal" + ); + } + #[test] fn audit_scope_is_unambiguous_for_component_boundaries() { assert_ne!( diff --git a/crates/registry-evidence/src/runtime_tests.rs b/crates/registry-evidence/src/runtime_tests.rs index fd214898e8..6f4e35fcc9 100644 --- a/crates/registry-evidence/src/runtime_tests.rs +++ b/crates/registry-evidence/src/runtime_tests.rs @@ -3820,10 +3820,19 @@ async fn release_admission_needs_both_the_acquisition_deadline_and_the_grant_ahe release_admission(ahead, Some(deadline(wall_seconds - 1))).expect_err("grant expired"); assert_eq!(expired_grant.problem(), ProblemCode::NotAuthorized); assert_eq!(expired_grant.category(), "grant-expired"); + assert_eq!( + expired_grant.check(), + Some(registry_platform_authcommon::FailedCheck::TaskGrantExpired) + ); let expired_budget = release_admission(behind, Some(deadline(expiry_ahead))).expect_err("budget spent"); assert_eq!(expired_budget.problem(), ProblemCode::DependencyUnavailable); assert_eq!(expired_budget.category(), "acquisition-budget"); + assert_eq!( + expired_budget.check(), + None, + "a spent budget is not a refusal" + ); } #[test] @@ -8653,6 +8662,10 @@ async fn failed_selector_budget_is_enforced_by_the_runtime_and_scoped_to_authori .await .expect_err("the next request is rejected before selector resolution"); assert_eq!(exhausted.problem(), ProblemCode::RateLimited); + assert_eq!( + exhausted.check(), + Some(registry_platform_authcommon::FailedCheck::RateLimit) + ); retained_failures.push_str(&format!("{exhausted:?} {exhausted}\n")); let now = Utc::now().timestamp(); diff --git a/crates/registry-evidence/src/selector.rs b/crates/registry-evidence/src/selector.rs index 5da76fe4aa..052ecd50f6 100644 --- a/crates/registry-evidence/src/selector.rs +++ b/crates/registry-evidence/src/selector.rs @@ -467,8 +467,11 @@ pub fn authority_selected_by_principal( #[deny(clippy::wildcard_enum_match_arm)] fn task_grant_check(error: TaskGrantError) -> FailedCheck { match error { - TaskGrantError::Claims | TaskGrantError::PrincipalMismatch => FailedCheck::TaskGrantClaims, - TaskGrantError::Client | TaskGrantError::Resource => FailedCheck::TaskGrantBinding, + TaskGrantError::Claims => FailedCheck::TaskGrantClaims, + TaskGrantError::Expired => FailedCheck::TaskGrantExpired, + TaskGrantError::PrincipalMismatch | TaskGrantError::Client | TaskGrantError::Resource => { + FailedCheck::TaskGrantBinding + } } } @@ -484,11 +487,7 @@ pub fn match_entitlement( ) -> Result { let has_task_grant = match context.grant() { Ok(Some(_)) if context.actor_kind() == ActorKind::Agent => true, - Ok(Some(_)) => { - return Err(AuthorizationError::Unauthorized( - FailedCheck::TaskGrantClaims, - )) - } + Ok(Some(_)) => return Err(AuthorizationError::Unauthorized(FailedCheck::ActorKind)), Err(error) => return Err(AuthorizationError::Unauthorized(task_grant_check(error))), Ok(None) => false, }; @@ -498,16 +497,23 @@ pub fn match_entitlement( .iter() .find(|candidate| candidate.id == request.requirement) .ok_or(AuthorizationError::Unauthorized(FailedCheck::AccessProfile))?; - if requirement.grant_ceiling.as_ref().is_some_and(|ceiling| { - !ceiling + if let Some(ceiling) = &requirement.grant_ceiling { + if !ceiling.actor_kinds.contains(&context.actor_kind()) { + return Err(AuthorizationError::Unauthorized(FailedCheck::ActorKind)); + } + if !ceiling .audiences .iter() .any(|audience| audience == context.evidence_audience()) - || !ceiling.actor_kinds.contains(&context.actor_kind()) - }) { - return Err(AuthorizationError::Unauthorized( - FailedCheck::TaskGrantBinding, - )); + { + // The audience is the caller's own claim. It is a grant binding + // only when the caller presented a task grant. + return Err(AuthorizationError::Unauthorized(if has_task_grant { + FailedCheck::TaskGrantBinding + } else { + FailedCheck::AccessProfile + })); + } } if !requirement .purposes @@ -1487,6 +1493,22 @@ mod tests { use crate::model::HolderPublicKey; + #[test] + fn every_task_grant_error_is_counted_under_the_member_that_names_it() { + for (error, check) in [ + (TaskGrantError::Claims, FailedCheck::TaskGrantClaims), + (TaskGrantError::Expired, FailedCheck::TaskGrantExpired), + ( + TaskGrantError::PrincipalMismatch, + FailedCheck::TaskGrantBinding, + ), + (TaskGrantError::Client, FailedCheck::TaskGrantBinding), + (TaskGrantError::Resource, FailedCheck::TaskGrantBinding), + ] { + assert_eq!(task_grant_check(error), check, "{error:?}"); + } + } + #[test] fn resolved_selector_debug_never_exposes_values() { let subject = ResolvedSubject { diff --git a/crates/registry-evidence/tests/golden/refusal_answers.json b/crates/registry-evidence/tests/golden/refusal_answers.json index 9d69b2a05f..0335fd54fe 100644 --- a/crates/registry-evidence/tests/golden/refusal_answers.json +++ b/crates/registry-evidence/tests/golden/refusal_answers.json @@ -107,6 +107,24 @@ }, "status": 401 }, + "expired-task-grant": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, "expired-token": { "body": { "code": "auth.invalid-credential", diff --git a/crates/registry-evidence/tests/selector_conformance.rs b/crates/registry-evidence/tests/selector_conformance.rs index d244c878eb..1f27f3b1bd 100644 --- a/crates/registry-evidence/tests/selector_conformance.rs +++ b/crates/registry-evidence/tests/selector_conformance.rs @@ -998,6 +998,57 @@ async fn standing_agent_requires_an_explicit_agent_profile() { assert!(bound.server.received_requests().await.unwrap().is_empty()); } +/// The package grant ceiling names the actor kinds and audiences a definition +/// serves for every caller, so a standing caller outside it is counted under +/// the member for the claim that failed, not under a task-grant member. +#[tokio::test] +async fn a_package_grant_ceiling_refusal_is_counted_under_the_claim_that_failed() { + let request = grant_request(None); + + let wrong_actor_kind = prepare_service_with_ceiling( + false, + None, + Some(("agent", &format!("\"{EVIDENCE_AUDIENCE}\""))), + ) + .await; + assert_authorization_error( + &wrong_actor_kind, + &access_token(json!({})), + &request, + AuthorizationError::Unauthorized(FailedCheck::ActorKind), + ) + .await; + + let wrong_audience = + prepare_service_with_ceiling(false, None, Some(("service", "\"urn:example:other\""))).await; + assert_authorization_error( + &wrong_audience, + &access_token(json!({})), + &request, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), + ) + .await; + let subject = json!({ + "given_name": "Adaeze", + "family_name": "Okafor", + "birth_date": "1990-07-11", + "event_reference": "synthetic-event-001" + }); + let wrong_audience_for_a_grant = prepare_service_with_ceiling( + false, + None, + Some(("service, agent", "\"urn:example:other\"")), + ) + .await; + assert_authorization_error( + &wrong_audience_for_a_grant, + &access_token(task_grant_claims(subject)), + &request, + AuthorizationError::Unauthorized(FailedCheck::TaskGrantBinding), + ) + .await; +} + #[tokio::test] async fn task_grant_context_is_bound_before_selector_or_source_access() { let service = prepare_service(false).await; @@ -1066,7 +1117,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(wrong_actor), &request, - AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims), + AuthorizationError::Unauthorized(FailedCheck::ActorKind), ) .await; @@ -1076,7 +1127,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(expired), &request, - AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims), + AuthorizationError::Unauthorized(FailedCheck::TaskGrantExpired), ) .await; @@ -1120,6 +1171,16 @@ async fn prepare_service(write_source_secret: bool) -> PreparedService { async fn prepare_service_for_actor( write_source_secret: bool, profile_actor: Option<&str>, +) -> PreparedService { + prepare_service_with_ceiling(write_source_secret, profile_actor, None).await +} + +/// `ceiling` is the actor kinds and audiences, as YAML flow sequence bodies, +/// that every requirement's package grant ceiling admits. +async fn prepare_service_with_ceiling( + write_source_secret: bool, + profile_actor: Option<&str>, + ceiling: Option<(&str, &str)>, ) -> PreparedService { let temporary = tempfile::tempdir().expect("temporary selector conformance root"); let root = temporary @@ -1149,6 +1210,16 @@ async fn prepare_service_for_actor( ) .unwrap(); } + if let Some((actor_kinds, audiences)) = ceiling { + let config_path = bundle_root.join("evidence.yaml"); + let config = fs::read_to_string(&config_path).unwrap(); + let marker = " purposes:\n"; + assert!(config.contains(marker)); + let block = format!( + " grantCeiling:\n authorities: [statutory, organizational, consent, delegated, explicit-request]\n actorKinds: [{actor_kinds}]\n valueOrigins: [authenticated-context, authenticated-grant, request]\n audiences: [{audiences}]\n{marker}" + ); + fs::write(&config_path, config.replace(marker, &block)).unwrap(); + } write_secret(&secret_root, "audit-key", AUDIT_KEY); write_secret(&secret_root, "binding-key", BINDING_KEY); write_secret(&secret_root, "signing-key", EVIDENCE_PRIVATE_JWK.as_bytes()); diff --git a/crates/registry-scheduling/src/auth.rs b/crates/registry-scheduling/src/auth.rs index e74ffb7bc7..f78eee21d7 100644 --- a/crates/registry-scheduling/src/auth.rs +++ b/crates/registry-scheduling/src/auth.rs @@ -388,6 +388,8 @@ fn unix_now() -> Result { /// committing capacity for as long as the clock stayed unreadable, and the /// deployment would be told nothing. Nothing has been learned about the /// credential either, so the answer is the outage answer, not a challenge. +/// The edge counts that answer as `key-source-unavailable` because no member +/// names a clock failure. The error line above names the clock. fn unix_seconds(observed: SystemTime) -> Result { observed .duration_since(UNIX_EPOCH) @@ -1025,16 +1027,48 @@ mod tests { )); } #[tokio::test] - async fn malformed_compact_tokens_are_refused_as_malformed_credentials() { + async fn malformed_compact_tokens_are_refused_as_malformed_credentials_and_logged_value_free() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let captured = CapturedDiagnosticLogs::default(); + let subscriber = captured.subscriber(); let tokens = registry_platform_testing::malformed_access_token_fixtures(); let auth = authenticator(); + let malformed = Some(AuthenticationError::Refused( + FailedCheck::CredentialMalformed, + )); for token in &tokens { - let malformed = Some(AuthenticationError::Refused( - FailedCheck::CredentialMalformed, - )); - assert_eq!(auth.authenticate_read(token).await.err(), malformed); - assert_eq!(auth.authenticate_explain(token).await.err(), malformed); - assert_eq!(auth.authenticate_mutate(token).await.err(), malformed); + assert_eq!( + auth.authenticate_read(token) + .with_subscriber(subscriber.clone()) + .await + .err(), + malformed + ); + assert_eq!( + auth.authenticate_explain(token) + .with_subscriber(subscriber.clone()) + .await + .err(), + malformed + ); + assert_eq!( + auth.authenticate_mutate(token) + .with_subscriber(subscriber.clone()) + .await + .err(), + malformed + ); + } + // The refusal line is written at the HTTP edge. Whatever the + // authenticator itself logs carries no part of a credential. + let rendered = captured.text(); + assert!(!rendered.contains("canary")); + for token in tokens.iter().filter(|token| !token.is_empty()) { + assert!( + !rendered.contains(token), + "diagnostics must not contain credentials" + ); } } diff --git a/crates/registry-scheduling/src/http.rs b/crates/registry-scheduling/src/http.rs index 065c8c302f..14e13d92f9 100644 --- a/crates/registry-scheduling/src/http.rs +++ b/crates/registry-scheduling/src/http.rs @@ -1401,11 +1401,12 @@ mod tests { "task-grant-lifetime", ]; - /// Every refusal answer keeps its status, headers and body. The golden - /// file holds what each refusal answered before its check was recorded, - /// with the trace id removed. + /// The renderer answers each refusal code with the status, headers and + /// body the golden file holds, with the trace id removed. The cases build + /// each error directly, so this pins the rendering. The postgres suite + /// pins which code each real path answers. #[tokio::test] - async fn refusal_answers_match_the_golden_bodies() { + async fn the_refusal_renderer_matches_the_golden_bodies() { use tracing::instrument::WithSubscriber as _; let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); let mut observed = serde_json::Map::new(); diff --git a/crates/registry-scheduling/src/lib.rs b/crates/registry-scheduling/src/lib.rs index 317b6b1f18..1e6682c56b 100644 --- a/crates/registry-scheduling/src/lib.rs +++ b/crates/registry-scheduling/src/lib.rs @@ -25,6 +25,7 @@ pub mod hooks; pub mod http; pub mod metrics; pub mod operational; +pub mod refusal; pub mod runtime; #[cfg(feature = "schema")] pub mod schema; diff --git a/crates/registry-scheduling/src/refusal.rs b/crates/registry-scheduling/src/refusal.rs new file mode 100644 index 0000000000..7899c22b10 --- /dev/null +++ b/crates/registry-scheduling/src/refusal.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The problem codes that refuse a caller's authority. +//! +//! Kept apart from the request path so the vocabulary classification names +//! every problem code on purpose: the OpenAPI generator reads the request +//! path for the codes it produces, and a classification there would count +//! every code as produced. + +use registry_scheduling_core::ProblemCode; + +/// The problem codes that refuse a caller's authority. A refusal is built +/// with the check it failed (`ServiceError::Refused`), never from the bare +/// code, so the operator's counter and log line can name the check. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RefusalCode { + AuthenticationRefused, + GrantLifetimeTooLong, + OperationNotAuthorized, + ProfileNotAuthorized, +} + +impl RefusalCode { + /// The problem this refusal answers with. + #[must_use] + pub const fn problem(self) -> ProblemCode { + match self { + Self::AuthenticationRefused => ProblemCode::AuthenticationRefused, + Self::GrantLifetimeTooLong => ProblemCode::GrantLifetimeTooLong, + Self::OperationNotAuthorized => ProblemCode::OperationNotAuthorized, + Self::ProfileNotAuthorized => ProblemCode::ProfileNotAuthorized, + } + } + + /// Sort a problem into a refusal or a plain answer. The match names every + /// code, so a code added to the vocabulary does not compile until it is + /// sorted here. The vocabulary test in `http.rs` pins the refusal set. + #[must_use] + pub const fn of(problem: ProblemCode) -> Option { + match problem { + ProblemCode::AuthenticationRefused => Some(Self::AuthenticationRefused), + ProblemCode::GrantLifetimeTooLong => Some(Self::GrantLifetimeTooLong), + ProblemCode::OperationNotAuthorized => Some(Self::OperationNotAuthorized), + ProblemCode::ProfileNotAuthorized => Some(Self::ProfileNotAuthorized), + ProblemCode::BookingDuplicateActive + | ProblemCode::CancellationCutoffPassed + | ProblemCode::CapabilityUnmatched + | ProblemCode::CapacityExhausted + | ProblemCode::CursorExpired + | ProblemCode::CursorInvalid + | ProblemCode::EligibilityUnavailable + | ProblemCode::HoldExpired + | ProblemCode::HoldReleased + | ProblemCode::HookUnavailable + | ProblemCode::HorizonOutside + | ProblemCode::IdempotencyExpired + | ProblemCode::IdempotencyKeyReused + | ProblemCode::LocationClosed + | ProblemCode::PartyCapacityInadequate + | ProblemCode::PolicyChanged + | ProblemCode::PreconditionFailed + | ProblemCode::PreconditionRequired + | ProblemCode::PrerequisiteMissing + | ProblemCode::ReceiptUnresolved + | ProblemCode::RequestBodyTooLarge + | ProblemCode::RequestInvalid + | ProblemCode::RequestMethodNotAllowed + | ProblemCode::RequestNotFound + | ProblemCode::RequestUnprocessable + | ProblemCode::RequestUnsupportedMediaType + | ProblemCode::ResourceUnavailable + | ProblemCode::RevisionMismatch + | ProblemCode::ScheduleUnpublished + | ProblemCode::ServiceUnavailable => None, + } + } +} diff --git a/crates/registry-scheduling/src/service.rs b/crates/registry-scheduling/src/service.rs index 6e0a2447cc..6ebc524474 100644 --- a/crates/registry-scheduling/src/service.rs +++ b/crates/registry-scheduling/src/service.rs @@ -166,44 +166,7 @@ pub enum CommitmentAnswer { Replay { status_code: u16, receipt: Value }, } -/// The problem codes that refuse a caller's authority. A refusal is built -/// with the check it failed (`ServiceError::Refused`), never from the bare -/// code, so the operator's counter and log line can name the check. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum RefusalCode { - AuthenticationRefused, - GrantLifetimeTooLong, - OperationNotAuthorized, - ProfileNotAuthorized, -} - -impl RefusalCode { - /// The problem this refusal answers with. - #[must_use] - pub const fn problem(self) -> ProblemCode { - match self { - Self::AuthenticationRefused => ProblemCode::AuthenticationRefused, - Self::GrantLifetimeTooLong => ProblemCode::GrantLifetimeTooLong, - Self::OperationNotAuthorized => ProblemCode::OperationNotAuthorized, - Self::ProfileNotAuthorized => ProblemCode::ProfileNotAuthorized, - } - } - - /// Sort a problem into a refusal or a plain answer. Every code outside the - /// four refusals is plain. The vocabulary test in `http.rs` pins the set, - /// so a code added to the vocabulary that refuses authority fails it until - /// it is listed here. - #[must_use] - pub const fn of(problem: ProblemCode) -> Option { - match problem { - ProblemCode::AuthenticationRefused => Some(Self::AuthenticationRefused), - ProblemCode::GrantLifetimeTooLong => Some(Self::GrantLifetimeTooLong), - ProblemCode::OperationNotAuthorized => Some(Self::OperationNotAuthorized), - ProblemCode::ProfileNotAuthorized => Some(Self::ProfileNotAuthorized), - _ => None, - } - } -} +pub use crate::refusal::RefusalCode; #[derive(Debug, thiserror::Error)] pub enum ServiceError { @@ -1189,7 +1152,7 @@ impl SchedulingService { self.commitment(caller, &actor, &grant, &release_key, &request_hash, now, 0)?; commitment.source_manager = source_manager; let (correlation, _request) = self - .audit_request( + .audit_named_request( caller, &grant, HOLD_RELEASE_ACTION, @@ -1312,7 +1275,7 @@ impl SchedulingService { )?; commitment.source_manager = source_manager; let (correlation, _request) = self - .audit_request(caller, &grant, operation, now, assisted) + .audit_named_request(caller, &grant, operation, now, assisted) .await?; let outcome = match (&supply, confirmation_request.as_ref()) { (ResolvedRequestSupply::Exact(bundle), Some(request)) => { @@ -1635,9 +1598,21 @@ impl SchedulingService { && claim.is_owned_by(&caller.issuer, &caller.subject) => {} None if claim.owner.is_some() => { let offering = self.claim_offering(&claim, now).await?; - let grant = self + let grant = match self .require_permission(caller, &offering, APPOINTMENT_READ_ACTION) - .await?; + .await + { + // A reads-scope caller carries no task grant, and the + // appointment is another caller's: that is an ownership + // refusal, not a missing grant. + Err(ServiceError::Refused { + check: FailedCheck::TaskGrantMissing, + .. + }) if admission == DetailAdmission::ReadsScope => { + return Err(ServiceError::operation_refused(FailedCheck::Ownership)); + } + other => other?, + }; self.require_current_task_grant(caller, &grant, APPOINTMENT_READ_ACTION, now, true) .await?; } @@ -1900,7 +1875,7 @@ impl SchedulingService { )?; commitment.source_manager = source_manager; let (correlation, _request) = self - .audit_request( + .audit_named_request( caller, &grant, APPOINTMENT_RESCHEDULE_ACTION, @@ -2009,7 +1984,7 @@ impl SchedulingService { 0, )?; let (correlation, _request) = self - .audit_request(caller, &grant, ATTENDANCE_RECORD_ACTION, now, false) + .audit_named_request(caller, &grant, ATTENDANCE_RECORD_ACTION, now, false) .await?; let outcome = self .store @@ -2090,7 +2065,7 @@ impl SchedulingService { )?; commitment.source_manager = source_manager; let (correlation, _request) = self - .audit_request( + .audit_named_request( caller, &grant, APPOINTMENT_CANCEL_ACTION, @@ -2356,8 +2331,9 @@ impl SchedulingService { /// the bound that failed nor whether a grant was carried at all. The one /// later answer that does say a grant was carried is a current-grant /// refusal for too much lifetime left, and it is given only after this - /// check has passed, so it tells a caller nothing about which services - /// and locations a grant reaches. + /// check has passed and only on a route that names no existing hold or + /// appointment, so it tells a caller nothing about which services and + /// locations a grant reaches or which ids exist. async fn require_permission( &self, caller: &Caller, @@ -2543,6 +2519,30 @@ impl SchedulingService { } } + /// `audit_request` for a route that names an existing hold or + /// appointment. A grant with too much lifetime left answers + /// `operation.not-authorized` there, as an unknown id does, so the answer + /// never says whether the id exists (SCHEDULING-DEC-01). The refusal + /// still counts under `task-grant-lifetime`. + async fn audit_named_request( + &self, + caller: &Caller, + grant: &GrantClaims, + operation: &str, + now: DateTime, + online_required: bool, + ) -> Result<(Uuid, AuditRequest), ServiceError> { + self.audit_request(caller, grant, operation, now, online_required) + .await + .map_err(|error| match error { + ServiceError::Refused { + code: RefusalCode::GrantLifetimeTooLong, + check, + } => ServiceError::operation_refused(check), + other => other, + }) + } + /// Append the `request` entry of one commitment and return the /// correlation its `response` entry will carry, with the handle that owes /// it. It names the caller, the grant, and the operation the capacity @@ -2912,7 +2912,9 @@ impl SchedulingService { CommitError::KeyReused | CommitError::KeyExpired => { Unanswered::Unfinished(key_refusal_reason(&error)) } - CommitError::Unauthorized => Unanswered::Denied("authorization.refused"), + CommitError::Unauthorized | CommitError::GrantLapsed => { + Unanswered::Denied("authorization.refused") + } CommitError::Refused(_) | CommitError::HoldCeiling | CommitError::RevisionMismatch @@ -3013,16 +3015,13 @@ impl SchedulingService { }; self.record_refusal(correlation, record).await?; Err(match RefusalCode::of(problem) { - // `CommitError::Unauthorized` is the only commit failure - // that refuses authority: the transaction found the grant - // lapsed, or the target not managed by this caller. A - // grant still current at this request's time was not the - // cause. + // `CommitError::Unauthorized` and `CommitError::GrantLapsed` + // are the only commit failures that refuse authority: the + // target is not this caller's to change, or the grant or + // its access token lapsed inside the transaction. Some(code) => ServiceError::Refused { code, - check: if u64::try_from(now.timestamp()) - .map_or(true, |observed| observed >= grant.exp()) - { + check: if matches!(error, CommitError::GrantLapsed) { FailedCheck::TaskGrantExpired } else { FailedCheck::Ownership @@ -3879,7 +3878,7 @@ fn problem_of(error: &CommitError) -> ProblemCode { CommitError::KeyReused => ProblemCode::IdempotencyKeyReused, CommitError::KeyExpired => ProblemCode::IdempotencyExpired, CommitError::HoldCeiling => ProblemCode::CapacityExhausted, - CommitError::Unauthorized => ProblemCode::OperationNotAuthorized, + CommitError::Unauthorized | CommitError::GrantLapsed => ProblemCode::OperationNotAuthorized, CommitError::RevisionMismatch => ProblemCode::RevisionMismatch, CommitError::ObservationInFuture => ProblemCode::RequestUnprocessable, CommitError::CutoffPassed => ProblemCode::CancellationCutoffPassed, @@ -4590,6 +4589,10 @@ mod tests { problem_of(&CommitError::Unauthorized), ProblemCode::OperationNotAuthorized ); + assert_eq!( + problem_of(&CommitError::GrantLapsed), + ProblemCode::OperationNotAuthorized + ); assert_eq!( problem_of(&CommitError::CutoffPassed), ProblemCode::CancellationCutoffPassed diff --git a/crates/registry-scheduling/src/store.rs b/crates/registry-scheduling/src/store.rs index 5d57329635..4e1c63fecf 100644 --- a/crates/registry-scheduling/src/store.rs +++ b/crates/registry-scheduling/src/store.rs @@ -896,8 +896,14 @@ pub enum CommitError { KeyExpired, #[error("the caller holds more active holds than the hold policy allows")] HoldCeiling, - #[error("the task grant lapsed before the commitment")] + /// The target is not the caller's to change: another caller holds it, or + /// its source manager differs. + #[error("the target is not managed by this caller")] Unauthorized, + /// The task grant, or the access token that carried it, lapsed before the + /// commitment. + #[error("the task grant lapsed before the commitment")] + GrantLapsed, #[error("the observed revision does not match the current revision")] RevisionMismatch, #[error("the attendance observation time is in the future")] @@ -3862,7 +3868,7 @@ fn check_grant_current_at( ) -> Result<(), CommitError> { match commitment.grant_exp_unix { Some(exp) if now.timestamp() < i64::try_from(exp).unwrap_or(i64::MAX) => Ok(()), - Some(_) => Err(CommitError::Unauthorized), + Some(_) => Err(CommitError::GrantLapsed), // A mutating commitment without a grant never reaches the store: the // service refuses it before the transaction opens. None => Ok(()), diff --git a/crates/registry-scheduling/tests/postgres_commitments.rs b/crates/registry-scheduling/tests/postgres_commitments.rs index 2c22a59906..6259488ad0 100644 --- a/crates/registry-scheduling/tests/postgres_commitments.rs +++ b/crates/registry-scheduling/tests/postgres_commitments.rs @@ -8892,6 +8892,18 @@ async fn the_offline_path_accepts_at_most_fifteen_minutes_of_remaining_lifetime( .await; assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); assert_eq!(problem["code"], "grant.lifetime-too-long"); + // The refusal is audited under the same reason every grant refusal + // carries, so an audit consumer keyed on it still sees these. + let journal = audit_by_reason(&fx); + assert_eq!( + journal.keys().cloned().collect::>(), + vec!["authorization.refused".to_owned()] + ); + assert_eq!(journal["authorization.refused"]["outcome"], "denied"); + assert_eq!( + journal["authorization.refused"]["operation"], + "appointment.create" + ); let a_day_left = agent_token_with_grant_exp(pinned_now().timestamp() + 86_400); let (status, problem) = fx diff --git a/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs b/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs index 4f358fea0c..b6d57359dc 100644 --- a/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs +++ b/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs @@ -429,3 +429,211 @@ async fn a_foreign_callers_refusals_name_ownership_and_grant_scope() { ); } } + +/// The task grant the booking agent carries, with a day left on it and the +/// attendance action added: past the offline path's fifteen-minute cap. +fn long_lived_agent_token() -> String { + let mut grant = grant_claims(); + grant["registry_grant_exp"] = json!(pinned_now().timestamp() + 86_400); + grant["registry_grant_bounds"]["permissions"][0]["actions"] + .as_array_mut() + .expect("the actions are a list") + .push(json!("attendance.record")); + let mut claims = json!({ + "sub": "principal-agent", + "azp": CLIENT, + "registry_scopes": "scheduling-read scheduling-explain", + "registry_actor_kind": "service", + }); + claims + .as_object_mut() + .expect("claims are an object") + .extend( + grant + .as_object() + .expect("grant claims are an object") + .iter() + .map(|(key, value)| (key.clone(), value.clone())), + ); + token(claims) +} + +/// SCHEDULING-DEC-01. On a route that names an existing hold or appointment, +/// a grant with too much lifetime left answers `operation.not-authorized`, +/// the same answer an unknown id gives, so the answer never says whether the +/// id exists. The operator's line still names `task-grant-lifetime`. +#[tokio::test] +async fn an_id_addressed_route_answers_an_existing_and_an_unknown_id_alike_under_a_long_grant() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let long = long_lived_agent_token(); + let held = first_slot(&fx, OFFERING, 300, 440).await; + let (status, hold) = fx + .post( + "/v1/holds", + &fx.agent, + "long-grant-hold", + admission(&fx, OFFERING, held), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{hold}"); + let hold_id = hold["holdId"].as_str().unwrap().to_owned(); + let (appointment_id, revision) = booked(&fx, 480, 620, "long-grant-appointment").await; + let other = first_slot(&fx, OFFERING, 640, 700).await; + let unknown = Uuid::new_v4().to_string(); + + let routes = |hold: &str, appointment: &str| { + vec![ + ("release", "DELETE", format!("/v1/holds/{hold}"), None, None), + ( + "confirm", + "POST", + "/v1/appointments".to_owned(), + Some("long-grant-confirm"), + Some(json!({"hold": hold, "admission": null})), + ), + ( + "reschedule", + "POST", + format!("/v1/appointments/{appointment}/reschedule"), + Some("long-grant-reschedule"), + Some( + json!({"observedRevision": revision, "admission": admission(&fx, OFFERING, other)}), + ), + ), + ( + "attendance", + "PUT", + format!("/v1/appointments/{appointment}/attendance"), + Some("long-grant-attendance"), + Some(json!({ + "observedAppointmentRevision": revision, + "observedRevision": 0, + "state": "arrived", + "observedAt": stamp(pinned_now() - TimeDelta::minutes(5)), + })), + ), + ( + "cancel", + "POST", + format!("/v1/appointments/{appointment}/cancel"), + Some("long-grant-cancel"), + Some(json!({"observedRevision": revision, "reason": null})), + ), + ] + }; + let existing_routes = routes(&hold_id, &appointment_id); + let unknown_routes = routes(&unknown, &unknown); + for (existing, missing) in existing_routes.into_iter().zip(unknown_routes) { + let (label, method, uri, key, body) = existing; + let mut answers = Vec::new(); + let mut checks = Vec::new(); + for (target, (_, method, uri, key, body)) in [ + ("existing", (label, method, uri, key, body)), + ("unknown", missing), + ] { + let captured = CapturedDiagnosticLogs::default(); + let (status, mut answer) = fx + .request(method, &uri, &long, key, body) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{label} {target}: {answer}"); + assert_eq!( + answer["code"], "operation.not-authorized", + "{label} {target}" + ); + answer + .as_object_mut() + .expect("a problem body") + .remove("traceId"); + answers.push(answer); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1, "{label} {target}"); + checks.push(lines[0]["fields"]["failed_check"].clone()); + } + assert_eq!( + answers[0], answers[1], + "{label}: an existing id and an unknown id answer alike" + ); + assert_eq!(checks, ["task-grant-lifetime", "visibility"], "{label}"); + } + + // No caller-named id is involved: a new hold keeps the specific code. A + // fresh deployment keeps this line clear of the per-check log limit the + // five routes above used up. + let fx = fixture().await; + let other = first_slot(&fx, OFFERING, 640, 700).await; + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .post( + "/v1/holds", + &long, + "long-grant-new-hold", + admission(&fx, OFFERING, other), + ) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{answer}"); + assert_eq!(answer["code"], "grant.lifetime-too-long"); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "task-grant-lifetime"); +} + +/// A task grant that lapses between the request's admission and the capacity +/// transaction's decision-time re-check is a lapsed grant, not an ownership +/// refusal. +#[tokio::test] +async fn a_grant_that_lapses_inside_the_transaction_is_counted_as_expired() { + use registry_platform_testing::CapturedDiagnosticLogs; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let slot = first_slot(&fx, OFFERING, 90, 200).await; + let door = pinned_now(); + let observations = Arc::new(AtomicUsize::new(0)); + let observed = observations.clone(); + fx.store.pin_clock(Arc::new(move || { + if observed.fetch_add(1, Ordering::SeqCst) == 0 { + door + } else { + door + TimeDelta::minutes(20) + } + })); + let captured = CapturedDiagnosticLogs::default(); + let (status, problem) = fx + .post( + "/v1/appointments", + &fx.agent, + "lapsed-in-transaction", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "operation.not-authorized"); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "task-grant-expired"); +} + +/// A caller with the reads scope and no task grant, reading another +/// caller's appointment, is refused on ownership. +#[tokio::test] +async fn a_reads_scope_caller_reading_another_owners_appointment_is_an_ownership_refusal() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let (appointment_id, _) = booked(&fx, 300, 440, "reads-scope-foreign").await; + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .get(&format!("/v1/appointments/{appointment_id}"), &fx.reader) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{answer}"); + assert_eq!(answer["code"], "operation.not-authorized"); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "ownership"); +} diff --git a/docs/site/src/content/docs/operate/stuck-work.mdx b/docs/site/src/content/docs/operate/stuck-work.mdx index 4e820e7944..1f0e1c4fab 100644 --- a/docs/site/src/content/docs/operate/stuck-work.mdx +++ b/docs/site/src/content/docs/operate/stuck-work.mdx @@ -124,7 +124,7 @@ The signals show a failing dependency instead. Outcomes other than `success` are failures, for example `timeout`, `transport`, `credential`, and `rate-limited`. - `evidence_signer_requests_total{signer,outcome}` does the same for the signer. - `evidence_source_shape_drift_total{source}` rises when a source starts answering in a shape the bundle does not describe. -- `evidence_request_refusals_total{check}` counts requests refused with `401`, `403` or `429`, by the check that failed. A rise under `key-source-unavailable` means the issuer's key set cannot be reached. +- `evidence_request_refusals_total{check}` counts requests refused with `401`, `403` or `429`, by the check that failed. A rise under `key-source-unavailable` means Evidence cannot reach or use the issuer's key set, or a caller named a published key that Evidence refuses. - `evidence_rate_limiter_tracked_keys` rises toward its ceiling of 100,000 keys. - With OID4VCI enabled, `evidence_oid4vci_store_entries` approaches `evidence_oid4vci_store_capacity`, and `evidence_oid4vci_outcomes_total{outcome}` counts `store-saturated` and `store-fault`. - `evidencectl doctor --runtime-config` is a preflight of the runtime file and, with `--require-audit-under`, of the audit path. diff --git a/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx b/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx index a3bde4e337..828af7e367 100644 --- a/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx +++ b/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-09-15" +last_reviewed: "2026-11-27" doc_type: reference locale: en standards_referenced: @@ -166,7 +166,9 @@ exact identity, bounds, signed subjects, and deadline. An inactive, mismatched, unlisted, or incompletely bound grant answers `operation.not-authorized`; an authority or service credential outage, including an unusable authority response, answers `service.unavailable`. On the offline path (`unchecked-final-fifteen-minutes`), an unexpired grant with more than 900 seconds left answers -`grant.lifetime-too-long` once its bounds have matched; an expired grant answers `operation.not-authorized`. Positive answers +`grant.lifetime-too-long` once its bounds have matched when it creates a hold or an appointment, and +`operation.not-authorized` on a request that names an existing hold or appointment, the same answer as an +unknown one; an expired grant answers `operation.not-authorized`. Positive answers are not cached, and the complete attempt is limited to ten seconds. No capacity lock is held during the outbound call. This is a fresh observation rather than a distributed transaction: withdrawal after a positive answer can race the in-flight local commit. diff --git a/docs/site/src/content/docs/reference/scheduling-task-grants.mdx b/docs/site/src/content/docs/reference/scheduling-task-grants.mdx index 6ffa83e255..e44d238f56 100644 --- a/docs/site/src/content/docs/reference/scheduling-task-grants.mdx +++ b/docs/site/src/content/docs/reference/scheduling-task-grants.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-18" +last_reviewed: "2026-11-27" doc_type: reference locale: en standards_referenced: [] @@ -127,15 +127,17 @@ The answer is a fresh observation, not a distributed transaction with the author `taskGrantStatus: unchecked-final-fifteen-minutes` selects the offline path. No authority is asked, no revocation is observed, and Registry Scheduling accepts a grant only while it is unexpired with no more than 900 seconds remaining at request entry. -An unexpired grant with more than 900 seconds remaining answers `grant.lifetime-too-long`, so the caller knows to present a grant that expires sooner. An expired grant answers `operation.not-authorized`. +An unexpired grant with more than 900 seconds remaining answers `grant.lifetime-too-long` when it creates a hold or an appointment, so the caller knows to present a grant that expires sooner. An expired grant answers `operation.not-authorized`. The lifetime answer follows the bounds match: a caller with no grant, or whose grant does not cover the offering, still answers `operation.not-authorized`. A listed authority never answers `grant.lifetime-too-long`. +A route that names an existing hold or appointment, which is releasing a hold, confirming a hold, rescheduling, recording attendance, and cancelling, answers `operation.not-authorized` for that grant, the same answer an unknown identifier gives, so the answer never says whether the identifier exists. +The appointment detail read, and every operation on a source-managed or assisted hold or appointment, needs a listed authority and so never answers `grant.lifetime-too-long`. A list of authorities disables that path for every source, including an unlisted one, which is refused even with less than 15 minutes left. The token does not name its authorisation mode, so the final 15 minutes of an originally deferred grant can use the offline path on a deployment that writes the keyword. List the task authorities for every deployment that accepts deferred grants. {/* Evidence: crates/registry-scheduling/src/service.rs listed_authorities_refuse_an_unlisted_source_and_an_unbound_grant_without_the_offline_path, - the_offline_path_accepts_only_an_unexpired_grant_with_at_most_fifteen_minutes_left; + the_offline_path_tells_a_grant_with_too_much_lifetime_from_an_expired_one; crates/registry-scheduling/src/config.rs a_missing_task_grant_status_is_refused_naming_both_choices; crates/registry-scheduling/tests/postgres_commitments.rs configured_task_status_is_fresh_for_a_capacity_commit_and_its_replay, diff --git a/docs/site/src/content/docs/security/evidence.mdx b/docs/site/src/content/docs/security/evidence.mdx index 1ab855a8a7..df7dcdcedc 100644 --- a/docs/site/src/content/docs/security/evidence.mdx +++ b/docs/site/src/content/docs/security/evidence.mdx @@ -57,14 +57,18 @@ receives: the response is the same closed `401`, `403` or `429` it always was. every_refusal_is_counted_logged_once_by_its_check_and_answered_as_before; crates/registry-evidence/tests/golden/refusal_answers.json. */} -The wallet-facing services record every refused request the same way. Evidence OID4VCI counts each -one in `evidence_oid4vci_request_refusals_total{check}` and Evidence OID4VP in -`evidence_oid4vp_request_refusals_total{check}`, and each writes one bounded `request refused` log -line that carries only the check name. The checks cover a missing or malformed bearer credential, a -token that fails verification, a missing scope or client, an unusable single-use code or access +The wallet-facing services record refused requests the same way. Evidence OID4VCI counts each one in +`evidence_oid4vci_request_refusals_total{check}` and Evidence OID4VP in +`evidence_oid4vp_request_refusals_total{check}`. Each writes one bounded `request refused` log line +with the check name, with `decision` and `suppressed`, and for OID4VP also the answer's trace id. +The checks cover a missing or malformed bearer credential, a token that fails verification, a +missing scope or client, a task grant the offer cannot use, an unusable single-use code or access token, an Evidence refusal, a session read that belongs to another principal, an unknown or foreign -session status, and a spent request budget. Capacity answers, unknown routes and malformed requests -are not recorded. The answers a caller receives are unchanged. +session status, and a spent request budget. An issuer key set that cannot be reached answers `503` +from both wallet services and counts under `key-source-unavailable`, so alert on that check rather +than on a rise in `401`. Capacity answers, unknown routes, malformed requests, the read of a +reference nobody holds and the wallet response protocol refusals are not recorded. The answers a +caller receives are unchanged. {/* Evidence: crates/registry-evidence-oid4vci/src/observability.rs, observe and record_refusal; crates/registry-evidence-oid4vci/src/service.rs, unauthorized, store_response, diff --git a/docs/site/src/content/docs/security/scheduling.mdx b/docs/site/src/content/docs/security/scheduling.mdx index 0c9da29bc0..dc76985668 100644 --- a/docs/site/src/content/docs/security/scheduling.mdx +++ b/docs/site/src/content/docs/security/scheduling.mdx @@ -184,9 +184,12 @@ it is listed with them. The signed token does not say whether the grant was issued in immediate or deferred mode. - Consequence: a grant with 900 seconds or less remaining qualifies for the bounded offline path with no revocation check. An unexpired grant with more than 900 seconds remaining answers - `grant.lifetime-too-long`, only after its bounds have matched, so the answer reveals nothing about - which services and locations a grant reaches. It does reveal to the holder that the deployment has - no status authority listed. The holder already controls its own grant, so this is accepted. + `grant.lifetime-too-long` when it creates a hold or an appointment, only after its bounds have + matched, so the answer reveals nothing about which services and locations a grant reaches. On a + route that names an existing hold or appointment, the same grant answers + `operation.not-authorized`, as an unknown identifier does, so the answer reveals nothing about + which identifiers exist. The code does reveal to the holder that the deployment has no status + authority listed. The holder already controls its own grant, so this is accepted. Even with status checks, a withdrawal that follows a positive status answer can race the in-flight local commit; the interval is bounded by the short execution credential and by deadline re-checks after every lock wait and before commit. diff --git a/products/evidence/CHANGELOG.md b/products/evidence/CHANGELOG.md index b803d92145..c5ed84e516 100644 --- a/products/evidence/CHANGELOG.md +++ b/products/evidence/CHANGELOG.md @@ -14,6 +14,18 @@ five lines per check per minute. This bounded `INFO` line replaces the key-source `WARN` line of both services: alert on the counter under `key-source-unavailable` instead. Responses are unchanged. +- Evidence names the refusal check more precisely, with no change to any + answer. An expired task grant counts under `task-grant-expired` at the + request as it does at release, a grant bound to another principal counts + under `task-grant-binding`, and a caller whose actor kind or audience falls + outside a definition's grant ceiling counts under `actor-kind` or + `access-profile` unless it presented a task grant. The key-source `WARN` + line now follows the same classification as the `key-source-unavailable` + count. +- Evidence OID4VP states the rule a refused static key set broke in its + startup message, still under `evidence.oid4vp.issuer-unavailable`. A request + whose `Authorization` header is present but unreadable as text counts under + `credential-malformed`. The answer is unchanged. - BREAKING (experimental surface): `evidencectl check` and `evidencectl package` refuse a `publicCheck` definition whose Source facts schema states more than diff --git a/products/evidence/OPERATOR-CONTRACT.md b/products/evidence/OPERATOR-CONTRACT.md index 4742d1fba1..d1d995cc22 100644 --- a/products/evidence/OPERATOR-CONTRACT.md +++ b/products/evidence/OPERATOR-CONTRACT.md @@ -776,7 +776,8 @@ event. Operational logs contain route templates, the public `trace_id`, the server-minted audit operation identifier, duration, status category, the public problem code, and safe internal error categories -only. The internal category is narrower than the public problem code but is +only. A refused request adds one `request refused` line that names the failed +check, as described under the refusal counter below. The internal category is narrower than the public problem code but is drawn from the same kind of fixed, closed set of service-chosen strings. It names the internal step that failed, never what that step saw, and it carries no counts. A record that was not found and a record that matched more than once @@ -845,7 +846,8 @@ the same bytes. Operators must update semantic audit readers to recognize all three entry schemas before deploying the request-batch runtime. The serving process writes those records as line-delimited JSON on standard -error, one per served request, and `EVIDENCE_LOG` selects verbosity with a +error, one per served request, plus at most five `request refused` lines per +check per minute, and `EVIDENCE_LOG` selects verbosity with a default of `info`. Offline commands print their own result and emit no operational records. Every response, including responses to unrouted paths, carries a W3C `traceparent` header. Evidence reuses a valid inbound trace @@ -861,8 +863,9 @@ public addresses are refused. A container deployment may declare `metricsListener.networkExposure: container-private` to bind `0.0.0.0` or `::`. The evidence listener never serves `/metrics`, and the metrics listener never serves evidence. Series carry only the registered -route template, request method, status category, and reviewed problem code, or -for the source series a governed source identifier from the bundle, so series +route template, request method, status category, and reviewed problem code, for +the source series a governed source identifier from the bundle, or for the +refusal series the closed failed-check name, so series cardinality is bounded by the deployed contract and cannot grow with caller input. A path that matches no route is counted as `unmatched` and a method outside the served set as `other`, so a caller cannot write a label @@ -1031,18 +1034,29 @@ lifecycle: the telemetry listener cannot outlive a failed evidence listener. The listener serves `GET /metrics` and answers every other path with `404`, including the evidence routes. The exposition is Prometheus text format, declared as `Content-Type: text/plain; version=0.0.4`. Two request-boundary -series are published: +series and one refusal counter are published: | Series | Type | Meaning | |---|---|---| | `evidence_http_requests_total` | counter | Requests served at the evidence boundary | | `evidence_http_request_duration_seconds` | histogram | Duration of those requests | +| `evidence_request_refusals_total{check}` | counter | Requests refused with `401`, `403` or `429`, by the check that refused them | + +The refusal counter has one label, `check`. Its values are the closed set of 45 +failed-check names (for example `credential-missing`, `token-signature`, `scope`, +`access-profile`, `purpose`, `revision-pin` and `rate-limit`), and every value is +published at zero from startup. No caller value becomes a label. Each refusal +also writes one `request refused` log line with `failed_check`, the request's +`trace_id` and `suppressed`, at most five lines per check per minute. The caller +still receives the same closed `401`, `403` or `429`. The counter and the line +are for the operator and name which check refused a request, so scrape access +to the private metrics listener is operator-only. The histogram publishes `_bucket`, `_sum`, and `_count`. Its upper bounds in seconds are `0.005`, `0.01`, `0.025`, `0.05`, `0.1`, `0.25`, `0.5`, `1.0`, `5.0`, and `+Inf`. They are fixed by the build and are not configurable. -Both series carry the same four labels, and each is drawn from a closed set +The two request-boundary series carry the same four labels, and each is drawn from a closed set fixed by the deployed contract rather than by anything a caller sends: | Label | Values | @@ -1065,10 +1079,12 @@ reviewed problem codes are the closed public set: `evidence.invalid-request`, exact status of a denial belongs to the closed public problem contract rather than to operational telemetry. `error` carries the same reviewed problem code the caller received, which makes a denial rate observable without making the -reason for any one request observable. +reason for any one request observable on these two series. The refusal counter +is the series that names the failed check, in aggregate and without a request +identifier. -Because both label sets are closed, series cardinality is bounded by the route -table and the problem-code set regardless of traffic, and the registry needs no +Because every label set is closed, series cardinality is bounded by the route +table, the problem-code set and the failed-check set regardless of traffic, and the registry needs no eviction. A caller cannot create a series or write a label value: a path matching no route is counted as `unmatched` and the requested path is never recorded anywhere in the exposition. diff --git a/products/evidence/contracts/oid4vci-profile.yaml b/products/evidence/contracts/oid4vci-profile.yaml index 77d9385795..b174b1d06f 100644 --- a/products/evidence/contracts/oid4vci-profile.yaml +++ b/products/evidence/contracts/oid4vci-profile.yaml @@ -302,7 +302,8 @@ operational_telemetry: delivery listener's binding. An operator may declare metricsListener.networkExposure: container-private to bind the wildcard address inside a container network it controls. Its route, - method, status, problem, and outcome labels come from closed vocabularies, + method, status, problem, outcome, and refused-check labels come from closed + vocabularies, state pressure and cleanup are unlabeled gauges or counters, and neither metrics nor request logs carry a request-derived or deployment-specific identifier. diff --git a/products/evidence/contracts/security-invariant-matrix.yaml b/products/evidence/contracts/security-invariant-matrix.yaml index f527af8481..c5ac7cff83 100644 --- a/products/evidence/contracts/security-invariant-matrix.yaml +++ b/products/evidence/contracts/security-invariant-matrix.yaml @@ -165,7 +165,7 @@ invariants: - id: V1-I33 rule: Operational telemetry is off by default, served only on a separate operator-private listener, and carries no caller-supplied or protected value in any label or series. threat: A metrics surface becomes a public existence oracle, or per-request labels reconstruct selectors, requirement usage, or registry membership through unbounded series cardinality. - enforcement: Optional runtime metricsListener bound to a private address distinct from the evidence listener (the wildcard only when the operator sets metricsListener.networkExposure to container-private), serving only GET /metrics; request series labels are drawn from the closed registered route-template set, a fixed method set, a fixed status category, and the reviewed problem-code set, and the source shape-drift series is labeled only by a governed bundle source identifier registered at startup, never from request or response content. + enforcement: Optional runtime metricsListener bound to a private address distinct from the evidence listener (the wildcard only when the operator sets metricsListener.networkExposure to container-private), serving only GET /metrics; request series labels are drawn from the closed registered route-template set, a fixed method set, a fixed status category, and the reviewed problem-code set, the source shape-drift series is labeled only by a governed bundle source identifier registered at startup, never from request or response content, and the refusal counter is labeled only by the closed failed-check set, zero-filled at construction. negative_test: sec-telemetry-bounded-and-operator-private - id: V1-I34 rule: Only the explicit local assurance profile may omit a requirement fixture reference or use focused fixture coverage; production and evidence-grade retain complete fixture validation before the bundle can load. diff --git a/products/evidence/contracts/security-test-traceability.yaml b/products/evidence/contracts/security-test-traceability.yaml index 7888444e22..8c59723e9f 100644 --- a/products/evidence/contracts/security-test-traceability.yaml +++ b/products/evidence/contracts/security-test-traceability.yaml @@ -168,6 +168,7 @@ entries: - {file: crates/registry-evidence/src/config.rs, name: the_metrics_wildcard_needs_container_private_exposure} - {file: crates/registry-evidence/src/observability.rs, name: shape_drift_series_stay_bounded_by_the_governed_sources} - {file: crates/registry-evidence/src/runtime_tests.rs, name: a_renamed_source_member_warns_once_per_interval_and_counts_every_drifted_response} + - {file: crates/registry-evidence/src/observability.rs, name: a_populated_scrape_is_byte_identical_to_the_recorded_one} - id: sec-no-entitlement-union tests: - {file: crates/registry-evidence/src/config.rs, name: complete_authority_paths_cannot_be_unioned_across_partial_grants} diff --git a/products/scheduling/CHANGELOG.md b/products/scheduling/CHANGELOG.md index 8a6f0e785d..0a7d6c6bac 100644 --- a/products/scheduling/CHANGELOG.md +++ b/products/scheduling/CHANGELOG.md @@ -8,10 +8,19 @@ `request refused` line with `failed_check` and the request's trace id, at most five lines per check per minute. That line replaces the authentication refusal line that carried a `stage` field. Refusal statuses, - headers and bodies are unchanged. -- A static key set with a private key member or a repeated member name is - refused at startup under `scheduling.runtime.unreadable-jwks-secret`, with - the rule it broke, in place of `scheduling.runtime-dependency.unavailable`. + headers and bodies are unchanged. An answer replayed from a stored receipt + under the same idempotency key is not counted again, because the decision + was counted when it was made. A grant or access token that lapses while a + commitment waits inside the capacity transaction counts under + `task-grant-expired`, and a hold or appointment that another caller or + source manager holds counts under `ownership`. +- A static key set that the shared key set rule refuses is refused at startup + under `scheduling.runtime.unreadable-jwks-secret`, with the rule it broke, + in place of `scheduling.runtime-dependency.unavailable`. The rule refuses a + key set that is not JSON, is not a key set, is empty, holds a key that is + not an object, a symmetric or unsupported key type, an OKP key or a key of + the wrong shape, a private key member, a missing `kid`, or a repeated + `kid`. - A reminder or hook destination in plain `http` accepts any loopback host by the shared rule: an address of `127.0.0.0/8`, `::1`, an IPv4-mapped form of `127.0.0.0/8`, or `localhost` in any case. `localhost.` and `*.localhost` @@ -27,8 +36,15 @@ caller learns to present a grant that expires sooner. The status is unchanged. An expired grant, a missing grant, and a grant that does not cover the offering still answer `operation.not-authorized`, and a deployment that - lists status authorities never answers the new code. Clients that branch on - the code gain the new member in `SchedulingProblemCode`. + lists status authorities never answers the new code. The code is answered + only where no existing hold or appointment is named, which is creating a + hold and creating an appointment. Releasing or confirming a hold, + rescheduling, recording attendance and cancelling answer + `operation.not-authorized` for the same grant, as an unknown identifier does, + so the answer does not say whether the identifier exists. Clients that + branch on the code gain the new member in `SchedulingProblemCode`. A client + from before this release reports the code as a protocol error with an + unknown outcome, so upgrade the client before shortening grants. ## 0.47.0 - 2026-11-21 diff --git a/products/scheduling/contracts/recorded-decisions.yaml b/products/scheduling/contracts/recorded-decisions.yaml index de1eef6c23..07601c2b70 100644 --- a/products/scheduling/contracts/recorded-decisions.yaml +++ b/products/scheduling/contracts/recorded-decisions.yaml @@ -26,6 +26,11 @@ decisions: permission is checked, the same answer a hold the caller's grant does not reach would give, so a caller cannot learn the id's existence from its own authorization. Confirmation resolves a hold by the same rule. + A grant with too much lifetime left on the offline path answers + operation.not-authorized on every route that names an existing hold or + appointment, so the lifetime answer does not tell a caller whether an + id exists. Only a route that names no existing id answers + grant.lifetime-too-long. A hold belonging to another caller is refused inside the transaction, where the refusal is audited. A hold consumes capacity only while its state is active and its expiry is still ahead of the transaction's @@ -38,6 +43,8 @@ decisions: - {path: crates/registry-scheduling-core/src/admission.rs, name: an_expired_hold_consumes_nothing_and_cannot_be_confirmed} - {path: crates/registry-scheduling/tests/postgres_commitments.rs, name: release_hold_refuses_indistinguishably_for_missing_and_unauthorized_holds} - {path: crates/registry-scheduling/tests/postgres_commitments.rs, name: confirm_appointment_refuses_indistinguishably_for_missing_and_unauthorized_holds} + - {path: crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs, name: an_id_addressed_route_answers_an_existing_and_an_unknown_id_alike_under_a_long_grant} + - {path: crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs, name: an_id_addressed_route_answers_an_existing_and_an_unknown_id_alike_under_a_long_grant} - id: SCHEDULING-DEC-02 subject: Cancellation never answers policy.changed decision: >- diff --git a/products/scheduling/contracts/security-invariant-matrix.yaml b/products/scheduling/contracts/security-invariant-matrix.yaml index 668e2d61e0..09be8ccc9f 100644 --- a/products/scheduling/contracts/security-invariant-matrix.yaml +++ b/products/scheduling/contracts/security-invariant-matrix.yaml @@ -58,7 +58,9 @@ invariants: back to the offline path. The unchecked-final-fifteen-minutes keyword admits only grants with at most 900 seconds remaining, and answers an unexpired grant with more left with grant.lifetime-too-long once the - bounds have matched. The transaction + bounds have matched, on a route that creates a hold or an appointment. + A route that names an existing hold or appointment answers + operation.not-authorized instead. The transaction re-checks the earlier of the verified access-token and grant deadlines after every lock wait and immediately before commit. Status is an observation, not a distributed transaction: withdrawal after a diff --git a/products/scheduling/generated/registry-scheduling.openapi.json b/products/scheduling/generated/registry-scheduling.openapi.json index 7432330fa2..d8f61ee27f 100644 --- a/products/scheduling/generated/registry-scheduling.openapi.json +++ b/products/scheduling/generated/registry-scheduling.openapi.json @@ -4104,15 +4104,12 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" - }, - { - "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", + "description": "Problem response: profile.not-authorized, operation.not-authorized", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -4311,15 +4308,12 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" - }, - { - "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", + "description": "Problem response: profile.not-authorized, operation.not-authorized", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -4609,15 +4603,12 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" - }, - { - "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", + "description": "Problem response: profile.not-authorized, operation.not-authorized", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -5146,15 +5137,12 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" - }, - { - "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", + "description": "Problem response: profile.not-authorized, operation.not-authorized", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" @@ -6573,15 +6561,12 @@ }, { "$ref": "#/components/schemas/ProblemOperationNotAuthorized" - }, - { - "$ref": "#/components/schemas/ProblemGrantLifetimeTooLong" } ] } } }, - "description": "Problem response: profile.not-authorized, operation.not-authorized, grant.lifetime-too-long", + "description": "Problem response: profile.not-authorized, operation.not-authorized", "headers": { "cache-control": { "$ref": "#/components/headers/CacheControlHeader" diff --git a/products/scheduling/scripts/generate_openapi.py b/products/scheduling/scripts/generate_openapi.py index 74368a7876..e95e9eaa10 100644 --- a/products/scheduling/scripts/generate_openapi.py +++ b/products/scheduling/scripts/generate_openapi.py @@ -52,6 +52,7 @@ ATTENDANCE_SOURCE = "crates/registry-scheduling-core/src/attendance.rs" ADMISSION_SOURCE = "crates/registry-scheduling-core/src/admission.rs" PROBLEM_SOURCE = "crates/registry-scheduling-core/src/problem.rs" +REFUSAL_SOURCE = "crates/registry-scheduling/src/refusal.rs" HTTPSEC_SOURCE = "crates/registry-platform-httpsec/src/server.rs" # The committed document `--write` produces and `--check` verifies. @@ -250,6 +251,9 @@ AUTHORITY = ["operation.not-authorized"] # An operation that asks the task grant's own status answers a grant that is # unexpired but has more than fifteen minutes left on the offline path. +# Only a route that names no existing hold or appointment answers it: on an +# id-addressed route a caller cannot learn whether the id exists +# (SCHEDULING-DEC-01), so the same grant answers `operation.not-authorized`. GRANT_LIFETIME = ["grant.lifetime-too-long"] IDEMPOTENCY = ["idempotency.expired", "idempotency.key-reused"] # An operation that resolves a caller-named offering against the deployed @@ -294,25 +298,25 @@ + OFFERING + ["service.unavailable"], # A release carries no caller-chosen key, so `idempotency.key-reused` is # not reachable: the key and the request hash are both the hold's own id. - ("DELETE", "/v1/holds/{hold_id}"): EDGE + AUTHENTICATION + PATH + AUTHORITY + GRANT_LIFETIME + ("DELETE", "/v1/holds/{hold_id}"): EDGE + AUTHENTICATION + PATH + AUTHORITY + ["hold.released", "idempotency.expired", "service.unavailable"], ("POST", "/v1/appointments"): EDGE + AUTHENTICATION + JSON_BODY + ADMISSION + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + OFFERING + ["hold.expired", "hold.released", "service.unavailable"], ("POST", "/v1/appointments/receipt"): EDGE + AUTHENTICATION + JSON_BODY + ["receipt.unresolved", "service.unavailable"], ("GET", "/v1/appointments"): EDGE + AUTHENTICATION + QUERY + CURSOR + STORAGE, - ("GET", "/v1/appointments/{appointment_id}"): EDGE + AUTHENTICATION + PATH + AUTHORITY + GRANT_LIFETIME + STORAGE, + ("GET", "/v1/appointments/{appointment_id}"): EDGE + AUTHENTICATION + PATH + AUTHORITY + STORAGE, # A reschedule resolves its offering from the appointment rather than from # the caller, so an unknown offering is operator state, not a refusal the # caller can read. ("POST", "/v1/appointments/{appointment_id}/reschedule"): EDGE + AUTHENTICATION + PATH + JSON_BODY - + ADMISSION + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + ["hold.released", "service.unavailable"], + + ADMISSION + IDEMPOTENCY + AUTHORITY + ["hold.released", "service.unavailable"], # Cancellation is guarded by the observed revision and the cutoff, never by # the policy revision, so it answers no admission refusal at all. ("POST", "/v1/appointments/{appointment_id}/cancel"): EDGE + AUTHENTICATION + PATH + JSON_BODY - + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + + IDEMPOTENCY + AUTHORITY + ["cancellation.cutoff-passed", "hold.released", "revision.mismatch", "service.unavailable"], ("PUT", "/v1/appointments/{appointment_id}/attendance"): EDGE + AUTHENTICATION + PATH + JSON_BODY - + IDEMPOTENCY + AUTHORITY + GRANT_LIFETIME + ["revision.mismatch", "service.unavailable"], + + IDEMPOTENCY + AUTHORITY + ["revision.mismatch", "service.unavailable"], ("GET", "/v1/appointments/{appointment_id}/history"): EDGE + AUTHENTICATION + PATH + AUTHORITY + QUERY + CURSOR + STORAGE, } @@ -1570,6 +1574,13 @@ def produced_problem_codes(repository_root: Path, variants: dict[str, str]) -> s produced |= { variants[name] for name in re.findall(r"ProblemCode::([A-Z][A-Za-z0-9]*)", source) } + # The refusal codes are answered through `RefusalCode::problem`. The + # classification after it names every code and so says nothing about + # which are produced. + refusals = production_source(repository_root, REFUSAL_SOURCE).split("pub const fn of", 1)[0] + produced |= { + variants[name] for name in re.findall(r"ProblemCode::([A-Z][A-Za-z0-9]*)", refusals) + } return produced @@ -1880,7 +1891,7 @@ def verify_source(repository_root: Path) -> None: "CommitError::KeyReused => ProblemCode::IdempotencyKeyReused", "CommitError::KeyExpired => ProblemCode::IdempotencyExpired", "CommitError::HoldCeiling => ProblemCode::CapacityExhausted", - "CommitError::Unauthorized => ProblemCode::OperationNotAuthorized", + "CommitError::Unauthorized | CommitError::GrantLapsed => ProblemCode::OperationNotAuthorized", "CommitError::RevisionMismatch => ProblemCode::RevisionMismatch", "CommitError::CutoffPassed => ProblemCode::CancellationCutoffPassed", ): diff --git a/products/scheduling/scripts/test_generate_openapi.py b/products/scheduling/scripts/test_generate_openapi.py index 83c2b39fbf..3152d876b8 100644 --- a/products/scheduling/scripts/test_generate_openapi.py +++ b/products/scheduling/scripts/test_generate_openapi.py @@ -775,19 +775,20 @@ def test_mutating_routes_name_ordinary_and_assisted_task_grant_actions(self) -> self.assertIn("hold.create, hold.release, appointment.create, appointment.reschedule, appointment.cancel", self.openapi["components"]["securitySchemes"]["bearerAuth"]["description"]) - def test_a_grant_gated_operation_documents_the_lifetime_refusal_beside_the_bounds_refusal(self) -> None: - gated = { + def test_only_the_routes_naming_no_existing_id_document_the_lifetime_refusal(self) -> None: + # A new hold and a create or confirm answer it. Every route that + # addresses an existing hold or appointment answers + # operation.not-authorized instead, so an id's existence is not + # revealed (SCHEDULING-DEC-01), and the detail read needs a listed + # authority, so it never reaches the lifetime check. + lifetime = { key for key in GENERATOR.ROUTE_HANDLERS - if operation(self.openapi, key)["x-scheduling-authority"] - in ("task-grant", "appointment-detail") + if "grant.lifetime-too-long" in GENERATOR.OPERATION_PROBLEMS[key] } - self.assertEqual(7, len(gated)) - for key in gated: - self.assertIn("grant.lifetime-too-long", GENERATOR.OPERATION_PROBLEMS[key], key) + self.assertEqual({("POST", "/v1/holds"), ("POST", "/v1/appointments")}, lifetime) + for key in lifetime: self.assertIn("operation.not-authorized", GENERATOR.OPERATION_PROBLEMS[key], key) - for key in set(GENERATOR.ROUTE_HANDLERS) - gated: - self.assertNotIn("grant.lifetime-too-long", GENERATOR.OPERATION_PROBLEMS[key], key) def test_the_document_carries_no_tag_list_and_no_timestamp(self) -> None: self.assertNotIn("tags", self.openapi) From f932829a80f9ccc6a00618007996d01a49ee3704 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:18:09 +0100 Subject: [PATCH 038/136] fix(platform): refuse unsafe provisioning targets and report what ran provision refuses a role or database name with a control character or a backslash, a database name with "=", the postgres, template0 and template1 databases, the administrator's own database and any template database, and the role names public, none and pg_*. It refuses an existing role with role-level settings or a membership the plan did not grant, and a PostGIS installed outside its schema or without the bbox membership. A login failure names the password only for SQLSTATE 28P01 and points at pg_hba.conf for 28000. The plan grants the runtime role USAGE on public directly, so running provision again restores it. The printed script stops at the first error. A run that stops part-way reports the statements that ran before the error. A change to a product's apply, start check or tool dispatch selects that product's provisioning journey in CI. The errors reference shows the shared probe bodies, and the Scheduling and Messaging operate pages say which command restores the runtime role's USAGE on public. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 19 +- .github/scripts/test_ci_changes.py | 22 +- crates/registry-documentsctl/src/provision.rs | 5 +- crates/registry-messagingctl/src/provision.rs | 5 +- crates/registry-platform-provision/README.md | 37 +- .../schema/provision-report.schema.json | 4 +- crates/registry-platform-provision/src/cli.rs | 503 ++++++++++++++++-- .../src/execute.rs | 219 +++++++- crates/registry-platform-provision/src/lib.rs | 10 +- .../registry-platform-provision/src/plan.rs | 256 ++++++++- crates/registry-platform-provision/src/sql.rs | 35 +- .../tests/postgres.rs | 396 +++++++++++++- crates/registry-rstack-dev/src/database.rs | 19 +- .../registry-schedulingctl/src/provision.rs | 5 +- .../src/content/docs/operate/messaging.mdx | 5 +- .../src/content/docs/operate/scheduling.mdx | 9 +- .../src/content/docs/reference/errors.mdx | 13 +- .../identifiers/generated/catalog.v1.json | 28 +- products/platform/CHANGELOG.md | 19 + 19 files changed, 1472 insertions(+), 137 deletions(-) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 8308df282a..986f63ff62 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -624,6 +624,21 @@ "crates/registry-documents/migrations/**", "crates/registry-messaging/migrations/**", "crates/registry-scheduling/migrations/**", + # What `apply` grants and what the start check reads, per product. + "crates/registry-casework/src/activation.rs", + "crates/registry-documents/src/activation.rs", + "crates/registry-messaging/src/activation.rs", + "crates/registry-scheduling/src/store/activation.rs", + # The Coordinator keeps its DDL in code, and dispatches its tool from cli.rs. + "crates/registry-coordinator/src/deployment.rs", + "crates/registry-coordinator/src/store.rs", + "crates/registry-coordinator/src/cli.rs", + # The tool dispatch of every other product. + *( + f"crates/{package}/src/lib.rs" + for package in PROVISION_JOURNEY_PACKAGES + if package != "registry-coordinator" + ), ) BREG_CONTRACTS_LANES = ( @@ -1691,8 +1706,8 @@ def classify( # casework_postgres read the selection above, so the provisioning crate # on its own does not select them. # Each product's provisioning journey runs in the same lane after the - # suite, so a product's provision command, its journey or its migrations - # select the lane too. + # suite, so a product's provision command, its journey, its migrations, its + # apply and start check or its tool's dispatch select the lane too. provision_postgres = "registry-platform-provision" in affected or any( matches(path, *PROVISION_JOURNEY_INPUTS) for path in paths ) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 6ce2f89968..d4dcde5527 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -38,6 +38,7 @@ ADAPTER_PACKAGES, MESSAGING_PACKAGES, MESSAGING_TUTORIAL_INPUTS, + PROVISION_JOURNEY_INPUTS, PROVISION_JOURNEY_PACKAGES, RENDER_TUTORIAL_INPUTS, SCHEDULING_TUTORIAL_INPUTS, @@ -2890,7 +2891,9 @@ def test_casework_task_approval_journey_runs_wherever_its_inputs_change( # The casework-postgres job owns the stock-issuer task approval # journey through Evidence, BReg, and Scheduling. It must run on every # change that selects the BReg product gate and on every change to the - # Scheduling runtime whose probe example the journey builds. + # Scheduling runtime whose probe example the journey builds. A change + # that joins the BReg contracts lane only for another product's + # provisioning journey does not select the BReg product gate. paths = [f"{root}/src/lib.rs" for root in self.workspace.roots.values()] paths.extend( ( @@ -2905,7 +2908,10 @@ def test_casework_task_approval_journey_runs_wherever_its_inputs_change( for path in paths: with self.subTest(path=path): outputs = classify(self.workspace, (path,)) - if outputs["breg_contracts"] or ( + provisioning_only = matches(path, *PROVISION_JOURNEY_INPUTS) and not ( + set(outputs["rust_packages"]) & BREG_PACKAGES + ) + if (outputs["breg_contracts"] and not provisioning_only) or ( "registry-scheduling" in outputs["rust_packages"] ): self.assertTrue(outputs["casework_postgres"]) @@ -4449,6 +4455,18 @@ def test_product_provisioning_changes_select_the_tls_postgres_lane(self) -> None "crates/registry-documents/migrations/0001_documents.sql", "crates/registry-messaging/migrations/0001_messaging.sql", "crates/registry-scheduling/migrations/0001_scheduling.sql", + "crates/registry-casework/src/activation.rs", + "crates/registry-documents/src/activation.rs", + "crates/registry-messaging/src/activation.rs", + "crates/registry-scheduling/src/store/activation.rs", + "crates/registry-coordinator/src/deployment.rs", + "crates/registry-coordinator/src/store.rs", + "crates/registry-coordinator/src/cli.rs", + *( + f"crates/{package}/src/lib.rs" + for package in journeys + if package != "registry-coordinator" + ), ] for graph, workspace in (("real", self.workspace), ("edgeless", edgeless)): for path in paths: diff --git a/crates/registry-documentsctl/src/provision.rs b/crates/registry-documentsctl/src/provision.rs index 1ed7465b91..ceca495cb2 100644 --- a/crates/registry-documentsctl/src/provision.rs +++ b/crates/registry-documentsctl/src/provision.rs @@ -13,8 +13,9 @@ use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout} use registry_platform_yaml::Diagnostic; use zeroize::Zeroizing; -/// The Document Store keeps its tables in `public`, handed to the migration -/// role, and needs no extension. +/// The Document Store keeps its tables in `public`. `provision` gives the +/// migration role USAGE and CREATE on it and the runtime role USAGE, directly. +/// It needs no extension. fn product() -> ProductDatabase { ProductDatabase { product: "documents", diff --git a/crates/registry-messagingctl/src/provision.rs b/crates/registry-messagingctl/src/provision.rs index 46df660003..d5ad9e28de 100644 --- a/crates/registry-messagingctl/src/provision.rs +++ b/crates/registry-messagingctl/src/provision.rs @@ -13,8 +13,9 @@ use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout} use registry_platform_yaml::Diagnostic; use zeroize::Zeroizing; -/// Messaging keeps its tables in `public`, handed to the migration -/// role, and needs no extension. +/// Messaging keeps its tables in `public`. `provision` gives the migration role +/// USAGE and CREATE on it and the runtime role USAGE, directly. It needs no +/// extension. fn product() -> ProductDatabase { ProductDatabase { product: "messaging", diff --git a/crates/registry-platform-provision/README.md b/crates/registry-platform-provision/README.md index 56873f9640..a9570e53b5 100644 --- a/crates/registry-platform-provision/README.md +++ b/crates/registry-platform-provision/README.md @@ -16,20 +16,43 @@ name. role. - `render_script` prints the plan for an administrator to review and run with `psql`. The script holds no password and no password verifier: each login - role is followed by a `\password` line, and a statement that needs a - superuser is marked. + role is followed by a `\password` line, a statement that needs a superuser + is marked, and the script stops at the first error. A role or database name + with a control character or a backslash, a database name with `=`, the + role names `public`, `none` and `pg_*`, and the databases `postgres`, + `template0` and `template1` are refused when the plan is built, so no name + can start a `psql` meta-command or reach another database. - `verify_server_version` refuses a server below the shared PostgreSQL floor, `registry_platform_activation::MINIMUM_SERVER_VERSION_NUM`. - `sql` holds the statement builders and the identifier and literal quoting. +- `execute` and `execute_recording` run a plan against a server as an + administrator, and `verify_logins` opens a session as each product role. + They open network connections. `admin_config` accepts only a `postgres://` + URL naming one TCP host, and every connection uses TLS verified against + `caBundleRef` or the platform roots (`sslmode=verify-ca` is checked as + `verify-full`). In `Mode::Converge` the server version is checked before the + first statement, and an existing role, database, schema or extension in + another shape is refused and never altered: a role with other attributes, + role-level settings or a membership the plan did not grant, a template + database, a PostGIS installed outside the plan's schema or without the bbox + membership. `execute_recording` keeps the outcomes of the statements that + ran before a failure. Passwords enter only through `RoleCredential`, whose `Debug` prints the name. The executable text of a role statement carries a SCRAM-SHA-256 verifier computed in the client, never the password. No API in this crate prints, formats or logs a secret. -This crate builds plans only. It opens no connection. +## Features -The `test-support` feature adds `test_support`, a verified-TLS superuser -session and the two `PROVISION_TEST_DATABASE_*` variables, for the provision -tests of `registry-caseworkctl`, `registry-coordinator` and -`registry-documentsctl`. Only their dev-dependencies enable it. +- `cli` adds the shared `provision` command (`cli::run_provision`): its clap + arguments, the runner and the report. A product supplies a loader that turns + its runtime file into a `ProvisionInput`. The runner reads role and database + names and passwords from the two product URLs, opens a connection only + outside `--print-sql`, and never prints a password, a verifier or a URL. +- `schema` renders the report's JSON Schema from its Rust type. +- `test-support` adds `test_support`, a verified-TLS superuser session and the + two `PROVISION_TEST_DATABASE_*` variables, for the provision tests of the + products that use this crate. Only their dev-dependencies enable it. +- `postgres-test` runs `tests/postgres.rs` against a disposable server. Its + header names the three variables it needs. diff --git a/crates/registry-platform-provision/schema/provision-report.schema.json b/crates/registry-platform-provision/schema/provision-report.schema.json index 91864c303d..e240b01f5e 100644 --- a/crates/registry-platform-provision/schema/provision-report.schema.json +++ b/crates/registry-platform-provision/schema/provision-report.schema.json @@ -162,7 +162,8 @@ "$ref": "#/$defs/ReportNeeds" }, "outcome": { - "$ref": "#/$defs/ReportOutcome" + "$ref": "#/$defs/ReportOutcome", + "description": "`not-run` for a statement the run did not reach, the one that failed\nincluded." }, "scope": { "$ref": "#/$defs/ReportScope" @@ -264,6 +265,7 @@ "type": "array" }, "executed": { + "description": "Whether a statement could have been sent to the server: false for a\nprint-mode run and for a run that stopped before the first statement.", "type": "boolean" }, "kind": { diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs index 99f3db1dc9..f3f441a985 100644 --- a/crates/registry-platform-provision/src/cli.rs +++ b/crates/registry-platform-provision/src/cli.rs @@ -20,9 +20,9 @@ use url::Url; use zeroize::Zeroizing; use crate::{ - admin_config, execute, render_script, verify_logins, AdminConfig, AdminConfigError, Mode, - Needs, Outcome, Plan, ProductDatabase, ProvisionError, ProvisionTarget, RoleCredential, Scope, - StatementOutcome, + admin_config, execute_recording, render_script, verify_logins, AdminConfig, AdminConfigError, + Failure, Mode, Needs, Outcome, Plan, PlanError, ProductDatabase, ProvisionError, + ProvisionTarget, RoleCredential, Scope, StatementOutcome, }; pub const REPORT_API_VERSION: &str = @@ -135,6 +135,8 @@ pub struct ReportStatement { pub step: String, pub scope: ReportScope, pub needs: ReportNeeds, + /// `not-run` for a statement the run did not reach, the one that failed + /// included. pub outcome: ReportOutcome, pub sql: String, } @@ -154,6 +156,8 @@ pub struct PlatformCliDatabaseProvisionReport { pub version: String, #[serde(skip_serializing_if = "Option::is_none")] pub product: Option, + /// Whether a statement could have been sent to the server: false for a + /// print-mode run and for a run that stopped before the first statement. pub executed: bool, #[serde(skip_serializing_if = "Option::is_none")] pub role_mode: Option, @@ -169,8 +173,7 @@ pub struct PlatformCliDatabaseProvisionReport { /// Runs the plan and then checks that each product role can log in. A test /// replaces it, so the report logic needs no server. -type Backend<'a> = - &'a dyn Fn(&AdminConfig, &Plan, &ProvisionTarget) -> Result; +type Backend<'a> = &'a dyn Fn(&AdminConfig, &Plan, &ProvisionTarget) -> Result; /// The most bytes read from the administrator URL file. const MAXIMUM_ADMIN_URL_BYTES: u64 = 8192; @@ -243,17 +246,49 @@ fn refuse( } } -fn target_invalid(message: &str) -> Refusal { +fn target_invalid_with(message: &str, action: &str) -> Refusal { refuse( ReportStatus::UsageError, "platform.provision.target-invalid", "", + message, + action, + ) +} + +fn target_invalid(message: &str) -> Refusal { + target_invalid_with( message, "Correct database.migrationUrlRef and database.runtimeUrlRef in the runtime file, then \ run provision again.", ) } +/// A name the plan refuses. The action names the URL member to correct and +/// never quotes its value. +fn plan_refusal(error: &PlanError) -> Refusal { + let rule = "A role name must not hold a control character or a backslash, and must not be \ + public, none or start with pg_."; + let action = match error { + PlanError::InvalidName { + what: "database name", + } => "Change the database name, the path of database.migrationUrlRef and \ + database.runtimeUrlRef. It must not hold a control character, a backslash or =, \ + and must not be postgres, template0 or template1." + .to_owned(), + PlanError::InvalidName { + what: "migration role name", + } => format!("Change the user in the migration URL (database.migrationUrlRef). {rule}"), + PlanError::InvalidName { + what: "runtime role name", + } => format!("Change the user in the runtime URL (database.runtimeUrlRef). {rule}"), + _ => "Correct database.migrationUrlRef and database.runtimeUrlRef in the runtime file, \ + then run provision again." + .to_owned(), + }; + target_invalid_with(&error.to_string(), &action) +} + fn target_mismatch(message: String) -> Refusal { refuse( ReportStatus::DomainRefusal, @@ -290,6 +325,9 @@ fn read_admin_url(args: &ProvisionArgs) -> Result, Refusal> { let raw = match (&args.admin_url_file, &args.admin_url_env) { (Some(path), None) => { let read = std::fs::File::open(path).and_then(|file| { + if !file.metadata()?.is_file() { + return Err(std::io::Error::other("not a regular file")); + } let mut text = String::new(); file.take(MAXIMUM_ADMIN_URL_BYTES + 1) .read_to_string(&mut text) @@ -364,6 +402,12 @@ fn admin_refusal(error: AdminConfigError) -> Refusal { fn execution_refusal(tool: &str, error: &ProvisionError) -> Refusal { use ProvisionError as E; let (status, action) = match error { + E::AdminConnectFailed { sqlstate } if sqlstate.as_deref() == Some("3D000") => ( + ReportStatus::OperationalFailure, + "The database the administrator URL names does not exist. Name one that does, such \ + as postgres, then run provision again." + .to_owned(), + ), E::AdminConnectFailed { .. } => ( ReportStatus::OperationalFailure, "Check the host, port, credentials and TLS certificate of the administrator URL, \ @@ -388,6 +432,23 @@ fn execution_refusal(tool: &str, error: &ProvisionError) -> Refusal { then run provision again." .to_owned(), ), + E::RoleMembershipDiffers { .. } => ( + ReportStatus::DomainRefusal, + "Use another role name in the product URLs, or revoke the role's memberships as an \ + administrator, then run provision again." + .to_owned(), + ), + E::DatabaseIsTemplate { .. } => ( + ReportStatus::DomainRefusal, + "Use another database name in the product URLs, then run provision again.".to_owned(), + ), + E::ExtensionIncomplete { .. } => ( + ReportStatus::DomainRefusal, + "As a superuser, run every statement of the extension.postgis step, which \ + provision --print-sql prints, after dropping a PostGIS installed in another \ + schema, then run provision again." + .to_owned(), + ), E::DatabaseOwnerDiffers { .. } => ( ReportStatus::DomainRefusal, "Use another database name, or run provision as the database owner or a role that \ @@ -404,12 +465,34 @@ fn execution_refusal(tool: &str, error: &ProvisionError) -> Refusal { ReportStatus::DomainRefusal, "Upgrade the extension as a superuser, then run provision again.".to_owned(), ), - E::RoleLoginFailed { .. } => ( - ReportStatus::DomainRefusal, - "The role exists with a different password. Set its password to the one in its \ - product URL as an administrator, or correct the URL, then run provision again." - .to_owned(), - ), + E::RoleLoginFailed { sqlstate, .. } => match sqlstate.as_deref() { + Some("28P01") => ( + ReportStatus::DomainRefusal, + "The role exists with a different password. Set its password to the one in \ + its product URL as an administrator, or correct the URL, then run provision \ + again." + .to_owned(), + ), + Some("28000") => ( + ReportStatus::DomainRefusal, + "The server refused the role. Check that the role can log in and that \ + pg_hba.conf lets it connect over TLS from this host, then run provision \ + again." + .to_owned(), + ), + Some(_) => ( + ReportStatus::DomainRefusal, + "Read the PostgreSQL server log for the refused login, fix the cause, then run \ + provision again." + .to_owned(), + ), + None => ( + ReportStatus::OperationalFailure, + "Check that the server accepts connections from this host, then run provision \ + again." + .to_owned(), + ), + }, E::EffectUnconfirmed { .. } => ( ReportStatus::OperationalFailure, "Run provision again.".to_owned(), @@ -472,9 +555,12 @@ fn outcome_word(outcome: ReportOutcome) -> &'static str { } } -/// The plan's statements with the outcome of each, `not-run` when no -/// executor outcome is given. -fn report_statements(plan: &Plan, outcome: Option<&Outcome>) -> Vec { +/// The plan's statements with the outcome of each statement the executor +/// reached, and `not-run` for the rest. +fn report_statements( + plan: &Plan, + reached: &[(&'static str, StatementOutcome)], +) -> Vec { plan.statements() .iter() .enumerate() @@ -482,8 +568,8 @@ fn report_statements(plan: &Plan, outcome: Option<&Outcome>) -> Vec plan, Err(error) => { - refused(&mut report, target_invalid(&error.to_string())); + // A refused name is not repeated in the report. + report.role_mode = None; + report.database = None; + report.migration_role = None; + report.runtime_role = None; + refused(&mut report, plan_refusal(&error)); return output.refusal(&report); } }; - report.statements = report_statements(&plan, None); + report.statements = report_statements(&plan, &[]); if args.print_sql { report.ok = true; @@ -683,20 +774,34 @@ fn run_with( return output.refusal(&report); } - report.executed = true; + if admin.database() == target.database { + refused( + &mut report, + target_invalid_with( + "the administrator URL names the product database, which provision creates", + "Point the administrator URL at the postgres maintenance database or another \ + existing database, then run provision again.", + ), + ); + return output.refusal(&report); + } + match backend(&admin, &plan, &target) { Ok(outcome) => { + report.executed = true; report.ok = true; report.status = ReportStatus::Complete; - report.statements = report_statements(&plan, Some(&outcome)); + report.statements = report_statements(&plan, &outcome.statements); let written = match format { OutputFormat::Json => output.json(&report), OutputFormat::Human => write_summary(output.stdout, &report, outcome.single_role), }; output.write_failed(written) } - Err(error) => { - refused(&mut report, execution_refusal(tool, &error)); + Err(failure) => { + report.executed = failure.error.may_have_run_statements(); + report.statements = report_statements(&plan, &failure.reached); + refused(&mut report, execution_refusal(tool, &failure.error)); output.refusal(&report) } } @@ -735,12 +840,17 @@ fn write_summary( /// Converges the server, then opens a session as each product role. fn server_backend( runtime: &tokio::runtime::Runtime, -) -> impl Fn(&AdminConfig, &Plan, &ProvisionTarget) -> Result + '_ { +) -> impl Fn(&AdminConfig, &Plan, &ProvisionTarget) -> Result + '_ { move |admin, plan, target| { runtime.block_on(async { - let outcome = execute(admin, plan, Mode::Converge).await?; - verify_logins(admin, target).await?; - Ok(outcome) + let outcome = execute_recording(admin, plan, Mode::Converge).await?; + match verify_logins(admin, target).await { + Ok(()) => Ok(outcome), + Err(error) => Err(Failure { + error, + reached: outcome.statements, + }), + } }) } } @@ -978,7 +1088,7 @@ mod tests { _: &AdminConfig, plan: &Plan, _: &ProvisionTarget, - ) -> Result { + ) -> Result { Ok(Outcome { statements: plan .statements() @@ -996,11 +1106,7 @@ mod tests { }) } - fn must_not_run( - _: &AdminConfig, - _: &Plan, - _: &ProvisionTarget, - ) -> Result { + fn must_not_run(_: &AdminConfig, _: &Plan, _: &ProvisionTarget) -> Result { panic!("the backend must not run"); } @@ -1279,7 +1385,8 @@ mod tests { fn refusal_json(error: ProvisionError) -> (u8, Value) { let admin = admin_url("db.example", 5432); - let backend = move |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| Err(error.clone()); + let backend = + move |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| Err(error.clone().into()); let run = execute_run( &["--format", "json"], Some(&admin), @@ -1372,12 +1479,52 @@ mod tests { ( E::RoleLoginFailed { role: "app_runtime".to_owned(), + sqlstate: Some("28P01".to_owned()), }, "platform.provision.role-login-failed", "domain-refusal", 1, None, ), + ( + E::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: None, + }, + "platform.provision.role-login-failed", + "operational-failure", + 3, + None, + ), + ( + E::RoleMembershipDiffers { + step: "role.runtime", + role: "app_runtime".to_owned(), + }, + "platform.provision.role-membership-differs", + "domain-refusal", + 1, + Some("role.runtime"), + ), + ( + E::DatabaseIsTemplate { + database: "app".to_owned(), + }, + "platform.provision.database-is-template", + "domain-refusal", + 1, + Some("database.create"), + ), + ( + E::ExtensionIncomplete { + step: "extension.postgis", + extension: "postgis".to_owned(), + }, + "platform.provision.extension-incomplete", + "domain-refusal", + 1, + Some("extension.postgis"), + ), ( E::EffectUnconfirmed { step: "database.create", @@ -1403,7 +1550,12 @@ mod tests { assert_eq!(actual_exit, exit, "{code}"); assert_eq!(report["ok"], false, "{code}"); assert_eq!(report["status"], status, "{code}"); - assert_eq!(report["executed"], true, "{code}"); + let ran = !matches!( + code, + "platform.provision.admin-connect-failed" + | "platform.provision.unsupported-postgres" + ); + assert_eq!(report["executed"], ran, "{code}"); let diagnostics = report["diagnostics"].as_array().unwrap(); assert_eq!(diagnostics.len(), 1, "{code}"); let diagnostic = &diagnostics[0]; @@ -1418,6 +1570,116 @@ mod tests { } } + #[test] + fn a_failure_part_way_reports_what_ran_before_it() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, plan: &Plan, _: &ProvisionTarget| { + let reached = plan + .statements() + .iter() + .take(3) + .map(|statement| { + let outcome = if statement.probe.is_some() { + StatementOutcome::Created + } else { + StatementOutcome::Applied + }; + (statement.step, outcome) + }) + .collect(); + Err(Failure { + error: ProvisionError::StatementNeedsPrivilege { + step: "database.revoke-public", + needs: Needs::DatabaseOwner, + scope: Scope::Server, + database: "app".to_owned(), + }, + reached, + }) + }; + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.exit, 1); + let report = run.json(); + assert_eq!(report["executed"], true); + let outcomes: Vec<&str> = report["statements"] + .as_array() + .unwrap() + .iter() + .map(|statement| statement["outcome"].as_str().unwrap()) + .collect(); + assert_eq!(&outcomes[..3], ["created", "created", "created"]); + assert!(outcomes[3..].iter().all(|outcome| *outcome == "not-run")); + } + + #[test] + fn a_login_check_failure_keeps_the_outcomes_of_the_run_that_preceded_it() { + let admin = admin_url("db.example", 5432); + let backend = |admin: &AdminConfig, plan: &Plan, target: &ProvisionTarget| { + let outcome = created_everything(admin, plan, target)?; + Err(Failure { + error: ProvisionError::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: Some("28P01".to_owned()), + }, + reached: outcome.statements, + }) + }; + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.exit, 1); + let report = run.json(); + assert_eq!(report["executed"], true); + assert!(report["statements"] + .as_array() + .unwrap() + .iter() + .all(|statement| statement["outcome"] != "not-run")); + } + + #[test] + fn a_login_refusal_blames_the_password_only_for_a_password_failure() { + let action_for = |sqlstate: Option<&str>| { + let (_, report) = refusal_json(ProvisionError::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: sqlstate.map(str::to_owned), + }); + report["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap() + .to_owned() + }; + assert!(action_for(Some("28P01")).contains("different password")); + for other in [Some("28000"), Some("53300"), None] { + assert!( + !action_for(other).contains("different password"), + "{other:?}" + ); + } + assert!(action_for(Some("28000")).contains("pg_hba.conf")); + } + + #[test] + fn a_missing_administrator_database_gets_its_own_action() { + let (exit, report) = refusal_json(ProvisionError::AdminConnectFailed { + sqlstate: Some("3D000".to_owned()), + }); + assert_eq!(exit, 3); + let action = report["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap(); + assert!(action.contains("does not exist"), "{action}"); + assert!(!action.contains("host, port"), "{action}"); + } + #[test] fn the_privilege_refusal_names_the_statement_and_offers_print_mode() { let (_, report) = refusal_json(ProvisionError::StatementNeedsPrivilege { @@ -1442,7 +1704,7 @@ mod tests { fn a_text_refusal_goes_to_stderr_and_stdout_stays_empty() { let admin = admin_url("db.example", 5432); let backend = |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| { - Err(ProvisionError::UnsupportedPostgres) + Err(ProvisionError::UnsupportedPostgres.into()) }; let run = execute_run(&[], Some(&admin), Ok(split_input()), &backend); assert_eq!(run.exit, 1); @@ -1760,6 +2022,172 @@ mod tests { ); } + #[test] + fn a_control_character_in_a_role_name_is_refused_in_print_mode_with_no_script() { + let migration = format!("postgres://app_migration:{MIGRATION_PASSWORD}@db.example/app"); + let runtime = + format!("postgres://app_runtime%0A%5C!%20id:{RUNTIME_PASSWORD}@db.example/app"); + for format in [["--format", "human"], ["--format", "json"]] { + let mut arguments = vec!["--print-sql"]; + arguments.extend(format); + let run = execute_run( + &arguments, + None, + Ok(input_with(&migration, &runtime, owned_product())), + &must_not_run, + ); + assert_eq!(run.exit, 2, "{}", run.all_output()); + let output = run.all_output(); + for script in [ + "CREATE ROLE", + "\\password", + "\\connect", + "\\!", + "-- provision script", + ] { + assert!(!output.contains(script), "{format:?}: {output}"); + } + assert!(!output.contains(RUNTIME_PASSWORD), "{output}"); + if format[1] == "json" { + let diagnostic = first_diagnostic(&run); + assert_eq!(diagnostic["code"], "platform.provision.target-invalid"); + let action = diagnostic["suggestedAction"].as_str().unwrap(); + assert!( + action.contains("user") && action.contains("runtime"), + "{action}" + ); + assert!(!action.contains("\\!"), "{action}"); + assert!(run.json().get("runtimeRole").is_none()); + } else { + assert!( + output.contains("platform.provision.target-invalid"), + "{output}" + ); + } + } + } + + #[test] + fn each_refused_url_member_is_named_in_the_action_and_never_quoted() { + let cases = [ + ( + "postgres://app_migration%0A:pw1@db.example/app", + "postgres://app_runtime:pw2@db.example/app", + "migration URL", + ), + ( + "postgres://app_migration:pw1@db.example/app%0Ax", + "postgres://app_runtime:pw2@db.example/app%0Ax", + "database name", + ), + ( + "postgres://app_migration:pw1@db.example/host%3Dattacker", + "postgres://app_runtime:pw2@db.example/host%3Dattacker", + "database name", + ), + ]; + for (migration, runtime, member) in cases { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input_with(migration, runtime, owned_product())), + &must_not_run, + ); + assert_eq!(run.exit, 2, "{migration}"); + let diagnostic = first_diagnostic(&run); + assert_eq!(diagnostic["code"], "platform.provision.target-invalid"); + let action = diagnostic["suggestedAction"].as_str().unwrap(); + assert!(action.contains(member), "{member}: {action}"); + assert!(!run.stdout.contains("attacker"), "{}", run.stdout); + } + } + + #[test] + fn the_administrators_own_database_cannot_be_the_product_database() { + let admin = + format!("postgres://admin:{ADMIN_PASSWORD}@db.example:5432/app?sslmode=verify-full"); + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 2, "{}", run.all_output()); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.target-invalid" + ); + assert!(!run.stdout.contains(ADMIN_PASSWORD)); + } + + fn admin_file_run(contents: &[u8]) -> Run { + let directory = tempfile::tempdir().expect("scratch directory"); + let path = directory.path().join("admin.url"); + std::fs::write(&path, contents).expect("admin file"); + let path = path.display().to_string(); + let args = parse(&["--runtime-config", "r", "--admin-url-file", path.as_str()]).unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + OutputFormat::Json, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + Run { + exit, + stdout: String::from_utf8(stdout).expect("utf-8"), + stderr: String::from_utf8(stderr).expect("utf-8"), + } + } + + #[test] + fn an_unusable_administrator_file_is_a_usage_error() { + let oversized = vec![b'a'; 9000]; + let cases: [(&str, &[u8]); 4] = [ + ("larger than 8 KiB", &oversized), + ("empty", b""), + ("whitespace only", b" \n\t\n"), + ("not UTF-8", &[0xff, 0xfe, 0xfd]), + ]; + for (what, contents) in cases { + let run = admin_file_run(contents); + assert_eq!(run.exit, 2, "{what}: {}", run.all_output()); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.admin-url-invalid", + "{what}" + ); + } + } + + #[test] + fn an_administrator_path_that_is_not_a_regular_file_is_a_usage_error() { + let directory = tempfile::tempdir().expect("scratch directory"); + let path = directory.path().display().to_string(); + let args = parse(&["--runtime-config", "r", "--admin-url-file", path.as_str()]).unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + OutputFormat::Json, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + assert_eq!(exit, 2); + let report: Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!( + report["diagnostics"][0]["code"], + "platform.provision.admin-url-invalid" + ); + } + #[test] fn no_output_ever_holds_a_password_verifier_or_url() { let admin = admin_url("db.example", 5432); @@ -1767,7 +2195,8 @@ mod tests { Err(ProvisionError::StatementFailed { step: "role.migration", sqlstate: "42710".to_owned(), - }) + } + .into()) }; for format in [["--format", "human"], ["--format", "json"]] { let run = execute_run(&format, Some(&admin), Ok(split_input()), &backend); diff --git a/crates/registry-platform-provision/src/execute.rs b/crates/registry-platform-provision/src/execute.rs index 150fd48239..ad650c1e6e 100644 --- a/crates/registry-platform-provision/src/execute.rs +++ b/crates/registry-platform-provision/src/execute.rs @@ -57,9 +57,17 @@ pub enum ProvisionError { step: &'static str, role: String, }, + /// An existing product role is a member of a role the plan did not grant it. + RoleMembershipDiffers { + step: &'static str, + role: String, + }, DatabaseOwnerDiffers { database: String, }, + DatabaseIsTemplate { + database: String, + }, SchemaOwnerDiffers { step: &'static str, schema: String, @@ -69,8 +77,17 @@ pub enum ProvisionError { step: &'static str, extension: String, }, + /// The extension exists, but not in the schema or with the role + /// membership its statement block sets up. + ExtensionIncomplete { + step: &'static str, + extension: String, + }, + /// `sqlstate` is the server's answer, `None` when none came (a timeout or + /// a lost connection). RoleLoginFailed { role: String, + sqlstate: Option, }, EffectUnconfirmed { step: &'static str, @@ -88,25 +105,40 @@ impl ProvisionError { Self::UnsupportedPostgres => "platform.provision.unsupported-postgres", Self::StatementNeedsPrivilege { .. } => "platform.provision.statement-needs-privilege", Self::RoleAttributesDiffer { .. } => "platform.provision.role-attributes-differ", + Self::RoleMembershipDiffers { .. } => "platform.provision.role-membership-differs", Self::DatabaseOwnerDiffers { .. } => "platform.provision.database-owner-differs", + Self::DatabaseIsTemplate { .. } => "platform.provision.database-is-template", Self::SchemaOwnerDiffers { .. } => "platform.provision.schema-owner-differs", Self::ExtensionTooOld { .. } => "platform.provision.extension-too-old", + Self::ExtensionIncomplete { .. } => "platform.provision.extension-incomplete", Self::RoleLoginFailed { .. } => "platform.provision.role-login-failed", Self::EffectUnconfirmed { .. } => "platform.provision.effect-unconfirmed", Self::StatementFailed { .. } => "platform.provision.statement-failed", } } + /// Whether any statement could have been sent before this error. + pub fn may_have_run_statements(&self) -> bool { + !matches!( + self, + Self::AdminConnectFailed { .. } | Self::UnsupportedPostgres + ) + } + /// The step of the plan the error belongs to, the report's `path`. pub fn step(&self) -> Option<&'static str> { match self { Self::StatementNeedsPrivilege { step, .. } | Self::RoleAttributesDiffer { step, .. } + | Self::RoleMembershipDiffers { step, .. } | Self::SchemaOwnerDiffers { step, .. } | Self::ExtensionTooOld { step, .. } + | Self::ExtensionIncomplete { step, .. } | Self::EffectUnconfirmed { step } | Self::StatementFailed { step, .. } => Some(step), - Self::DatabaseOwnerDiffers { .. } => Some("database.create"), + Self::DatabaseOwnerDiffers { .. } | Self::DatabaseIsTemplate { .. } => { + Some("database.create") + } Self::AdminConnectFailed { .. } | Self::UnsupportedPostgres | Self::RoleLoginFailed { .. } => None, @@ -175,6 +207,16 @@ impl fmt::Display for ProvisionError { creates it with. It is not altered: use another name or correct the role as \ an administrator" ), + Self::RoleMembershipDiffers { role, .. } => write!( + f, + "the role \"{role}\" already exists and is a member of a role provisioning did \ + not grant it. It is not altered: use another name or revoke the membership as \ + an administrator" + ), + Self::DatabaseIsTemplate { database } => write!( + f, + "the database \"{database}\" is a template database and is not adopted" + ), Self::DatabaseOwnerDiffers { database } => write!( f, "the database \"{database}\" already exists under an owner the administrator \ @@ -191,10 +233,26 @@ impl fmt::Display for ProvisionError { f, "the extension \"{extension}\" is installed below the version this product needs" ), - Self::RoleLoginFailed { role } => write!( + Self::ExtensionIncomplete { extension, .. } => write!( + f, + "the extension \"{extension}\" exists outside the schema or without the role \ + membership its prerequisites set up" + ), + Self::RoleLoginFailed { + role, + sqlstate: None, + } => write!( f, "the role \"{role}\" cannot open a session with its configured credential" ), + Self::RoleLoginFailed { + role, + sqlstate: Some(sqlstate), + } => write!( + f, + "the role \"{role}\" cannot open a session with its configured credential \ + (SQLSTATE {sqlstate})" + ), Self::EffectUnconfirmed { step } => write!( f, "the outcome of step {step} is unknown after a timeout or a lost connection; \ @@ -231,6 +289,23 @@ fn call_error(step: &'static str, failure: CallFailure) -> ProvisionError { } } +/// Why a run stopped, with the statements that had already run. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Failure { + pub error: ProvisionError, + /// The outcome of each statement before the one that failed, in plan order. + pub reached: Vec<(&'static str, StatementOutcome)>, +} + +impl From for Failure { + fn from(error: ProvisionError) -> Self { + Self { + error, + reached: Vec::new(), + } + } +} + /// Runs every statement of `plan` as the administrator `admin`. /// /// In [`Mode::Converge`] the server version is checked against the shared @@ -242,12 +317,42 @@ pub async fn execute( plan: &Plan, mode: Mode, ) -> Result { + execute_recording(admin, plan, mode) + .await + .map_err(|failure| failure.error) +} + +/// [`execute`] that keeps the outcomes of the statements that ran before a +/// failure, so a report can say what changed on the server. +pub async fn execute_recording( + admin: &AdminConfig, + plan: &Plan, + mode: Mode, +) -> Result { + let mut statements = Vec::with_capacity(plan.statements().len()); + match run_plan(admin, plan, mode, &mut statements).await { + Ok(()) => Ok(Outcome { + statements, + single_role: plan.single_role(), + }), + Err(error) => Err(Failure { + error, + reached: statements, + }), + } +} + +async fn run_plan( + admin: &AdminConfig, + plan: &Plan, + mode: Mode, + statements: &mut Vec<(&'static str, StatementOutcome)>, +) -> Result<(), ProvisionError> { let server = admin.connect(None).await.map_err(connect_failed)?; if mode == Mode::Converge { verify_floor(&server).await?; } let mut database: Option = None; - let mut statements = Vec::with_capacity(plan.statements().len()); for statement in plan.statements() { let session = match statement.scope { Scope::Server => &server, @@ -264,10 +369,7 @@ pub async fn execute( let outcome = run_statement(session, plan, statement, mode).await?; statements.push((statement.step, outcome)); } - Ok(Outcome { - statements, - single_role: plan.single_role(), - }) + Ok(()) } async fn verify_floor(server: &Session) -> Result<(), ProvisionError> { @@ -334,12 +436,27 @@ async fn probe_is_satisfied( ) -> Result { let step = statement.step; match probe { - Probe::Role { name, login } => { + Probe::Role { + name, + login, + member_of, + } => { + // Columns 1 to 7 are attributes that must be false: the six + // flags and role-level settings. Column 8 is membership of any + // role other than `member_of` granted as the plan grants it. let row = bounded_call(session.client.query_opt( - "SELECT rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, \ - rolbypassrls, rolreplication \ - FROM pg_catalog.pg_roles WHERE rolname = $1", - &[name], + "SELECT r.rolcanlogin, r.rolsuper, r.rolcreatedb, r.rolcreaterole, \ + r.rolinherit, r.rolbypassrls, r.rolreplication, \ + r.rolconfig IS NOT NULL, \ + EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m \ + JOIN pg_catalog.pg_roles g ON g.oid = m.roleid \ + WHERE m.member = r.oid \ + AND NOT (coalesce(g.rolname = $2::text, false) \ + AND NOT m.inherit_option \ + AND m.set_option \ + AND NOT m.admin_option)) \ + FROM pg_catalog.pg_roles r WHERE r.rolname = $1", + &[name, member_of], )) .await .map_err(|failure| call_error(step, failure))?; @@ -348,7 +465,7 @@ async fn probe_is_satisfied( }; let can_login: bool = row.try_get(0).map_err(|_| unreadable(step))?; let mut others = false; - for column in 1..7 { + for column in 1..8 { let flag: bool = row.try_get(column).map_err(|_| unreadable(step))?; others |= flag; } @@ -358,6 +475,13 @@ async fn probe_is_satisfied( role: name.clone(), }); } + let other_membership: bool = row.try_get(8).map_err(|_| unreadable(step))?; + if other_membership { + return Err(ProvisionError::RoleMembershipDiffers { + step, + role: name.clone(), + }); + } Ok(true) } Probe::Database { name } => { @@ -365,7 +489,7 @@ async fn probe_is_satisfied( // what `pg_has_role(..., 'USAGE')` tests, and are held by every // superuser. let row = bounded_call(session.client.query_opt( - "SELECT pg_catalog.pg_has_role(current_user, datdba, 'USAGE') \ + "SELECT pg_catalog.pg_has_role(current_user, datdba, 'USAGE'), datistemplate \ FROM pg_catalog.pg_database WHERE datname = $1", &[name], )) @@ -375,7 +499,12 @@ async fn probe_is_satisfied( None => Ok(false), Some(row) => { let can_act: bool = row.try_get(0).map_err(|_| unreadable(step))?; - if can_act { + let template: bool = row.try_get(1).map_err(|_| unreadable(step))?; + if template { + Err(ProvisionError::DatabaseIsTemplate { + database: name.clone(), + }) + } else if can_act { Ok(true) } else { Err(ProvisionError::DatabaseOwnerDiffers { @@ -388,6 +517,7 @@ async fn probe_is_satisfied( Probe::Extension { name, minimum_version, + setup, } => { let row = bounded_call(session.client.query_opt( "SELECT extversion::text FROM pg_catalog.pg_extension WHERE extname = $1", @@ -399,15 +529,34 @@ async fn probe_is_satisfied( return Ok(false); }; let installed: String = row.try_get(0).map_err(|_| unreadable(step))?; - match minimum_version { - Some(minimum) if !version_at_least(&installed, *minimum) => { - Err(ProvisionError::ExtensionTooOld { + if let Some(minimum) = minimum_version { + if !version_at_least(&installed, *minimum) { + return Err(ProvisionError::ExtensionTooOld { step, extension: name.clone(), - }) + }); } - _ => Ok(true), } + if let Some(setup) = setup { + let row = bounded_call(session.client.query_one( + "SELECT coalesce((SELECT e.extnamespace = to_regnamespace($1::text)::oid \ + FROM pg_catalog.pg_extension e WHERE e.extname = $2), \ + false), \ + pg_catalog.pg_has_role($3::text::name, $4::text::name, 'SET')", + &[&setup.schema, name, &setup.member, &setup.role], + )) + .await + .map_err(|failure| call_error(step, failure))?; + let in_schema: bool = row.try_get(0).map_err(|_| unreadable(step))?; + let can_set: bool = row.try_get(1).map_err(|_| unreadable(step))?; + if !in_schema || !can_set { + return Err(ProvisionError::ExtensionIncomplete { + step, + extension: name.clone(), + }); + } + } + Ok(true) } Probe::Schema { name, owner } => { let row = bounded_call(session.client.query_opt( @@ -465,19 +614,27 @@ pub async fn verify_logins( roles.push(&target.runtime); } for role in roles { - let failed = || ProvisionError::RoleLoginFailed { + let failed = |sqlstate: Option| ProvisionError::RoleLoginFailed { role: role.name.clone(), + sqlstate, }; let session = admin .connect_as(&target.database, &role.name, role.password()) .await - .map_err(|_| failed())?; + .map_err(|failure| failed(failure.sqlstate))?; let row = bounded_call(session.client.query_one("SELECT current_user::text", &[])) .await - .map_err(|_| failed())?; - let current: String = row.try_get(0).map_err(|_| failed())?; + .map_err(|failure| { + failed(match failure { + CallFailure::Server { sqlstate } => Some(sqlstate), + CallFailure::Unconfirmed => None, + }) + })?; + let current: String = row + .try_get(0) + .map_err(|_| failed(Some("XX000".to_owned())))?; if current != role.name { - return Err(failed()); + return Err(failed(Some("XX000".to_owned()))); } } Ok(()) @@ -512,9 +669,16 @@ mod tests { step: "role.migration", role: "r".to_owned(), }, + ProvisionError::RoleMembershipDiffers { + step: "role.runtime", + role: "r".to_owned(), + }, ProvisionError::DatabaseOwnerDiffers { database: "d".to_owned(), }, + ProvisionError::DatabaseIsTemplate { + database: "d".to_owned(), + }, ProvisionError::SchemaOwnerDiffers { step: "schema.owned", schema: "s".to_owned(), @@ -524,8 +688,13 @@ mod tests { step: "extension.postgis", extension: "postgis".to_owned(), }, + ProvisionError::ExtensionIncomplete { + step: "extension.postgis", + extension: "postgis".to_owned(), + }, ProvisionError::RoleLoginFailed { role: "r".to_owned(), + sqlstate: Some("28P01".to_owned()), }, ProvisionError::EffectUnconfirmed { step: "role.runtime", diff --git a/crates/registry-platform-provision/src/lib.rs b/crates/registry-platform-provision/src/lib.rs index 9eca80b469..cb2fe564bf 100644 --- a/crates/registry-platform-provision/src/lib.rs +++ b/crates/registry-platform-provision/src/lib.rs @@ -25,11 +25,15 @@ pub mod sql; pub mod test_support; pub use admin::{admin_config, AdminConfig, AdminConfigError}; -pub use execute::{execute, verify_logins, Mode, Outcome, ProvisionError, StatementOutcome}; +pub use execute::{ + execute, execute_recording, verify_logins, Failure, Mode, Outcome, ProvisionError, + StatementOutcome, +}; pub use plan::{ - plan, render_script, verify_server_version, Needs, Plan, PlanError, Probe, ProductDatabase, - ProvisionTarget, RoleCredential, SchemaLayout, Scope, Spatial, Statement, UnsupportedPostgres, + plan, render_script, verify_server_version, ExtensionSetup, Needs, Plan, PlanError, Probe, + ProductDatabase, ProvisionTarget, RoleCredential, SchemaLayout, Scope, Spatial, Statement, + UnsupportedPostgres, }; #[cfg(feature = "cli")] diff --git a/crates/registry-platform-provision/src/plan.rs b/crates/registry-platform-provision/src/plan.rs index 450019d177..9fdc63236d 100644 --- a/crates/registry-platform-provision/src/plan.rs +++ b/crates/registry-platform-provision/src/plan.rs @@ -94,6 +94,10 @@ pub enum Probe { Role { name: String, login: bool, + /// The one role this plan itself grants to the role, with + /// `INHERIT FALSE, SET TRUE, ADMIN FALSE`. Membership of any other + /// role is refused: it would carry privileges the plan did not grant. + member_of: Option, }, Database { name: String, @@ -101,6 +105,9 @@ pub enum Probe { Extension { name: String, minimum_version: Option<(u32, u32)>, + /// What the same statement block sets up beside the extension. An + /// extension present without it was installed outside the plan. + setup: Option, }, Schema { name: String, @@ -108,6 +115,16 @@ pub enum Probe { }, } +/// The schema an extension must live in and the role membership the +/// extension's statement block grants. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExtensionSetup { + pub schema: String, + /// `member` must be able to `SET ROLE` to `role`. + pub member: String, + pub role: String, +} + pub struct Statement { pub step: &'static str, pub scope: Scope, @@ -197,8 +214,35 @@ pub fn verify_server_version(version_num: i32) -> Result<(), UnsupportedPostgres const MAX_NAME_BYTES: usize = 63; +/// Databases a product must never be provisioned into: PostgreSQL's own. +const RESERVED_DATABASES: [&str; 3] = ["postgres", "template0", "template1"]; + +/// A name reaches the printed `psql` script, where a line break would end a +/// meta-command and a backslash would start one, so no byte below 0x20, DEL +/// or backslash is allowed in any name. fn check_name(what: &'static str, name: &str) -> Result<(), PlanError> { - if name.is_empty() || name.len() > MAX_NAME_BYTES || name.contains('\0') { + let unsafe_byte = |byte: u8| byte < 0x20 || byte == 0x7f || byte == b'\\'; + if name.is_empty() || name.len() > MAX_NAME_BYTES || name.bytes().any(unsafe_byte) { + return Err(PlanError::InvalidName { what }); + } + Ok(()) +} + +/// `public` and `none` are keywords in a `GRANT` list, and `pg_` names belong +/// to PostgreSQL. +fn check_role_name(what: &'static str, name: &str) -> Result<(), PlanError> { + check_name(what, name)?; + let lower = name.to_ascii_lowercase(); + if lower == "public" || lower == "none" || lower.starts_with("pg_") { + return Err(PlanError::InvalidName { what }); + } + Ok(()) +} + +/// `\connect` reads a database name holding `=` as a connection string. +fn check_database_name(what: &'static str, name: &str) -> Result<(), PlanError> { + check_name(what, name)?; + if name.contains('=') || RESERVED_DATABASES.contains(&name) { return Err(PlanError::InvalidName { what }); } Ok(()) @@ -235,7 +279,11 @@ fn statement( } } -fn login_role(step: &'static str, credential: &RoleCredential) -> Statement { +fn login_role( + step: &'static str, + credential: &RoleCredential, + member_of: Option<&str>, +) -> Statement { let verifier = Zeroizing::new(postgres_protocol::password::scram_sha_256( credential.password.as_bytes(), )); @@ -247,6 +295,7 @@ fn login_role(step: &'static str, credential: &RoleCredential) -> Statement { Some(Probe::Role { name: credential.name.clone(), login: true, + member_of: member_of.map(str::to_owned), }), ); statement.executable = Zeroizing::new(sql::create_role_sql(&credential.name, &verifier)); @@ -261,9 +310,9 @@ fn login_role(step: &'static str, credential: &RoleCredential) -> Statement { /// already holds, so it runs every time. Passwords reach only the private /// executable text, as SCRAM verifiers. pub fn plan(product: &ProductDatabase, target: &ProvisionTarget) -> Result { - check_name("database name", &target.database)?; - check_name("migration role name", &target.migration.name)?; - check_name("runtime role name", &target.runtime.name)?; + check_database_name("database name", &target.database)?; + check_role_name("migration role name", &target.migration.name)?; + check_role_name("runtime role name", &target.runtime.name)?; let single_role = target.migration.name == target.runtime.name; if single_role && *target.migration.password != *target.runtime.password { return Err(PlanError::SingleRolePasswordsDiffer); @@ -278,15 +327,20 @@ pub fn plan(product: &ProductDatabase, target: &ProvisionTarget) -> Result Result Result Result { statements.push(in_database( "schema.public", - sql::public_schema_sql(migration), + sql::public_schema_sql(migration, runtime), None, )); } @@ -383,6 +439,11 @@ pub fn plan(product: &ProductDatabase, target: &ProvisionTarget) -> Result String { let mut script = format!( "-- provision script, product {}. Nothing was run.\n\ -- For a server where these objects do not exist yet. Review, then run with psql as an\n\ - -- administrator that has CREATEROLE and CREATEDB.\n\ + -- administrator that has CREATEROLE and CREATEDB. It stops at the first error.\n\ + \\set ON_ERROR_STOP on\n\ SET createrole_self_grant = {};\n", plan.product, sql::quote_literal(sql::CREATEROLE_SELF_GRANT), @@ -559,7 +621,8 @@ mod tests { role.probe, Some(Probe::Role { name: "casework_migration".to_owned(), - login: true + login: true, + member_of: None, }) ); let create = by_step("database.create"); @@ -732,6 +795,167 @@ mod tests { ); } + fn invalid(what: &'static str) -> PlanError { + PlanError::InvalidName { what } + } + + fn plan_for(target: &ProvisionTarget) -> Result { + plan(&product(SchemaLayout::PublicForMigration), target) + } + + #[test] + fn names_with_control_characters_or_backslashes_are_refused() { + for bad in ["a\nb", "a\rb", "a\x1bb", "a\x7fb", "a\\b", "a\tb"] { + let mut database = target(); + database.database = bad.to_owned(); + assert_eq!( + plan_for(&database).unwrap_err(), + invalid("database name"), + "{bad:?}" + ); + + let mut migration = target(); + migration.migration = RoleCredential::new(bad, PASSWORD_M); + assert_eq!( + plan_for(&migration).unwrap_err(), + invalid("migration role name"), + "{bad:?}" + ); + + let mut runtime = target(); + runtime.runtime = RoleCredential::new(bad, PASSWORD_R); + assert_eq!( + plan_for(&runtime).unwrap_err(), + invalid("runtime role name"), + "{bad:?}" + ); + + let mut spatial = breg_spatial(); + spatial.spatial.as_mut().unwrap().bbox_role = bad.to_owned(); + assert_eq!( + plan(&spatial, &target()).unwrap_err(), + invalid("PostGIS bbox role name"), + "{bad:?}" + ); + } + } + + #[test] + fn a_database_name_with_an_equals_sign_is_refused_but_a_role_name_may_hold_one() { + let mut database = target(); + database.database = "host=attacker.example dbname=x".to_owned(); + assert_eq!(plan_for(&database).unwrap_err(), invalid("database name")); + + let mut role = target(); + role.runtime = RoleCredential::new("app=runtime", PASSWORD_R); + assert!(plan_for(&role).is_ok()); + } + + #[test] + fn reserved_role_names_are_refused() { + for reserved in [ + "public", + "PUBLIC", + "none", + "None", + "pg_read_all_data", + "PG_x", + ] { + let mut migration = target(); + migration.migration = RoleCredential::new(reserved, PASSWORD_M); + assert_eq!( + plan_for(&migration).unwrap_err(), + invalid("migration role name"), + "{reserved}" + ); + let mut runtime = target(); + runtime.runtime = RoleCredential::new(reserved, PASSWORD_R); + assert_eq!( + plan_for(&runtime).unwrap_err(), + invalid("runtime role name"), + "{reserved}" + ); + } + let mut spatial = breg_spatial(); + spatial.spatial.as_mut().unwrap().bbox_role = "public".to_owned(); + assert_eq!( + plan(&spatial, &target()).unwrap_err(), + invalid("PostGIS bbox role name") + ); + let mut single = target(); + single.migration = RoleCredential::new("public", PASSWORD_M); + single.runtime = RoleCredential::new("public", PASSWORD_M); + assert!(plan_for(&single).is_err()); + } + + #[test] + fn the_postgres_template_and_maintenance_databases_are_refused() { + for reserved in ["postgres", "template0", "template1"] { + let mut database = target(); + database.database = reserved.to_owned(); + assert_eq!( + plan_for(&database).unwrap_err(), + invalid("database name"), + "{reserved}" + ); + } + } + + #[test] + fn the_printed_script_stops_at_the_first_error_before_anything_else() { + let script = render_script(&plan(&breg_spatial(), &target()).unwrap()); + let first = script + .lines() + .find(|line| !line.starts_with("--")) + .expect("a statement line"); + assert_eq!(first, "\\set ON_ERROR_STOP on", "{script}"); + } + + #[test] + fn the_runtime_role_gets_usage_on_public_from_the_plan() { + let plan = plan(&product(SchemaLayout::PublicForMigration), &target()).unwrap(); + let public = plan + .statements() + .iter() + .find(|statement| statement.step == "schema.public") + .unwrap(); + assert_eq!(public.probe, None); + assert_eq!(public.scope, Scope::Database); + assert_eq!( + public.printable, + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO \"casework_migration\"; \ + GRANT USAGE ON SCHEMA public TO \"casework_runtime\"" + ); + assert!(!public.printable.contains("GRANT OPTION")); + } + + #[test] + fn single_role_public_layout_grants_the_one_role_once() { + let target = ProvisionTarget { + database: "adapter".to_owned(), + migration: RoleCredential::new("adapter", PASSWORD_M), + runtime: RoleCredential::new("adapter", PASSWORD_M), + }; + let plan = plan(&product(SchemaLayout::PublicForMigration), &target).unwrap(); + let public = plan + .statements() + .iter() + .find(|statement| statement.step == "schema.public") + .unwrap(); + assert_eq!( + public.printable, + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO \"adapter\"" + ); + } + + #[test] + fn literals_with_a_backslash_are_written_as_escape_strings() { + assert_eq!(quote_literal("a\\b'c"), "E'a\\\\b''c'"); + assert_eq!(quote_literal("plain"), "'plain'"); + } + #[test] fn server_below_the_floor_is_refused() { for version in [0, 90_600, 160_999, 169_999] { @@ -817,7 +1041,7 @@ mod tests { #[test] fn breg_setup_installs_extension_and_all_owned_schemas() { let layout = SchemaLayout::Owned(breg_schemas()); - let sql = database_setup_sql("casework_migration", &layout, true); + let sql = database_setup_sql("casework_migration", "casework_runtime", &layout, true); assert!(sql.starts_with("CREATE EXTENSION btree_gist;"), "{sql}"); for schema in breg_schemas() { assert!( @@ -839,18 +1063,20 @@ mod tests { } #[test] - fn public_setup_restricts_create_and_grants_the_migration_role() { + fn public_setup_restricts_create_and_grants_both_roles() { assert_eq!( database_setup_sql( "casework_migration", + "casework_runtime", &SchemaLayout::PublicForMigration, false ), "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ - GRANT USAGE, CREATE ON SCHEMA public TO \"casework_migration\"" + GRANT USAGE, CREATE ON SCHEMA public TO \"casework_migration\"; \ + GRANT USAGE ON SCHEMA public TO \"casework_runtime\"" ); assert_eq!( - database_setup_sql("m", &SchemaLayout::CreatedByApply, false), + database_setup_sql("m", "r", &SchemaLayout::CreatedByApply, false), "" ); } diff --git a/crates/registry-platform-provision/src/sql.rs b/crates/registry-platform-provision/src/sql.rs index 0baea3347a..dd1272fe22 100644 --- a/crates/registry-platform-provision/src/sql.rs +++ b/crates/registry-platform-provision/src/sql.rs @@ -13,8 +13,15 @@ pub fn quote_identifier(value: &str) -> String { format!("\"{}\"", value.replace('"', "\"\"")) } +/// A string literal. A backslash makes it an escape string, so the text means +/// the same whatever `standard_conforming_strings` is set to. pub fn quote_literal(value: &str) -> String { - format!("'{}'", value.replace('\'', "''")) + let escaped = value.replace('\'', "''"); + if value.contains('\\') { + format!("E'{}'", escaped.replace('\\', "\\\\")) + } else { + format!("'{escaped}'") + } } /// `verifier` is a SCRAM-SHA-256 verifier, never a password. @@ -106,17 +113,33 @@ pub fn owned_schema_sql(schema: &str, owner: &str) -> String { ) } -pub fn public_schema_sql(migration: &str) -> String { - format!( +/// `public` is closed to PUBLIC's CREATE. The migration role gets USAGE and +/// CREATE, and the runtime role USAGE, directly from the administrator that +/// owns the schema, so that PUBLIC's default USAGE is not what lets the +/// runtime role resolve the product's tables. Running it again restores both. +pub fn public_schema_sql(migration: &str, runtime: &str) -> String { + let mut sql = format!( "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ GRANT USAGE, CREATE ON SCHEMA public TO {}", quote_identifier(migration) - ) + ); + if runtime != migration { + sql.push_str(&format!( + "; GRANT USAGE ON SCHEMA public TO {}", + quote_identifier(runtime) + )); + } + sql } /// Everything that runs inside the database apart from PostGIS: the one batch /// `rstack dev` configures a fresh database with. `CreatedByApply` has none. -pub fn database_setup_sql(migration: &str, layout: &SchemaLayout, btree_gist: bool) -> String { +pub fn database_setup_sql( + migration: &str, + runtime: &str, + layout: &SchemaLayout, + btree_gist: bool, +) -> String { match layout { SchemaLayout::Owned(schemas) => { let schemas = schemas @@ -130,7 +153,7 @@ pub fn database_setup_sql(migration: &str, layout: &SchemaLayout, btree_gist: bo schemas } } - SchemaLayout::PublicForMigration => public_schema_sql(migration), + SchemaLayout::PublicForMigration => public_schema_sql(migration, runtime), SchemaLayout::CreatedByApply => String::new(), } } diff --git a/crates/registry-platform-provision/tests/postgres.rs b/crates/registry-platform-provision/tests/postgres.rs index 16af51bc4f..52ceea54cd 100644 --- a/crates/registry-platform-provision/tests/postgres.rs +++ b/crates/registry-platform-provision/tests/postgres.rs @@ -14,9 +14,9 @@ //! a non-superuser holds only the attributes the test names. use registry_platform_provision::{ - admin_config, execute, plan, render_script, verify_logins, AdminConfig, AdminConfigError, Mode, - Needs, Outcome, ProductDatabase, ProvisionError, ProvisionTarget, RoleCredential, SchemaLayout, - Scope, Spatial, StatementOutcome, + admin_config, execute, execute_recording, plan, render_script, verify_logins, AdminConfig, + AdminConfigError, Mode, Needs, Outcome, ProductDatabase, ProvisionError, ProvisionTarget, + RoleCredential, SchemaLayout, Scope, Spatial, StatementOutcome, }; use rustls::pki_types::{pem::PemObject as _, CertificateDer}; use tokio_postgres::{config::SslMode, Client, Config}; @@ -44,6 +44,10 @@ fn quote(identifier: &str) -> String { format!("\"{}\"", identifier.replace('"', "\"\"")) } +fn quote_literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + fn tls(ca: &[u8]) -> MakeRustlsConnect { let provider = rustls::crypto::ring::default_provider(); if provider.install_default().is_err() { @@ -908,6 +912,8 @@ async fn existing_role_with_other_attributes_is_refused() { ("LOGIN INHERIT", "role.migration", true), ("NOLOGIN", "role.migration", true), ("LOGIN CREATEDB", "role.runtime", false), + ("LOGIN SUPERUSER", "role.runtime", false), + ("LOGIN BYPASSRLS", "role.runtime", false), ]; for (attributes, step, migration) in differing { let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; @@ -964,6 +970,355 @@ async fn existing_role_with_other_attributes_is_refused() { } } +async fn memberships(fixture: &Fixture, role: &str) -> String { + fixture + .server + .superuser + .text(&format!( + "SELECT string_agg(concat_ws('|', g.rolname, a.admin_option, a.inherit_option, \ + a.set_option), ',' ORDER BY g.rolname) \ + FROM pg_catalog.pg_auth_members a \ + JOIN pg_catalog.pg_roles g ON g.oid = a.roleid \ + JOIN pg_catalog.pg_roles m ON m.oid = a.member \ + WHERE m.rolname = '{role}' AND m.rolname = '{role}'" + )) + .await +} + +#[tokio::test] +async fn an_existing_role_that_is_a_member_of_another_role_is_refused_and_left_alone() { + let _serial = lock().await; + let cases = [ + ("pg_read_all_data", "role.runtime", false), + ("pg_execute_server_program", "role.migration", true), + ]; + for (granted, step, migration) in cases { + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let role = if migration { + fixture.migration_name() + } else { + fixture.runtime_name() + }; + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \ + GRANT {granted} TO {} WITH INHERIT TRUE", + quote(&role), + quote(&role) + )) + .await; + let before = memberships(&fixture, &role).await; + assert!(before.contains(granted), "{before}"); + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!( + error.code(), + "platform.provision.role-membership-differs", + "{granted}" + ); + assert_eq!(error.step(), Some(step)); + assert!(error.to_string().contains(&role)); + assert!(!error.to_string().contains(granted)); + assert_eq!(memberships(&fixture, &role).await, before, "left alone"); + assert!(!fixture.database_exists().await, "nothing runs after it"); + fixture + .server + .superuser + .exec(&format!("DROP ROLE IF EXISTS {}", quote(&role))) + .await; + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn an_existing_role_with_members_or_the_plans_own_grants_is_accepted() { + let _serial = lock().await; + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + fixture.provision(&product).await.unwrap(); + // The runtime role gains a member, and the migration role is already in + // the bbox role: neither is a refusal. + let member = format!("s2_member_{}", fixture.suffix); + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} NOLOGIN; GRANT {} TO {}", + quote(&member), + quote(&fixture.runtime_name()), + quote(&member) + )) + .await; + let again = fixture.provision(&product).await.unwrap(); + assert_eq!(created(&again), Vec::<&str>::new()); + fixture + .server + .superuser + .exec(&format!("DROP ROLE {}", quote(&member))) + .await; + fixture.cleanup().await; +} + +#[tokio::test] +async fn an_existing_role_with_role_level_settings_is_refused() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let role = fixture.runtime_name(); + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} LOGIN; ALTER ROLE {} SET search_path = pg_catalog", + quote(&role), + quote(&role) + )) + .await; + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.role-attributes-differ"); + assert_eq!(error.step(), Some("role.runtime")); + fixture.cleanup().await; +} + +#[tokio::test] +async fn an_existing_bbox_role_with_login_or_membership_is_refused() { + let _serial = lock().await; + let plain = "NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS"; + for (attributes, grant) in [("LOGIN", false), ("NOLOGIN", true)] { + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + let bbox = fixture.bbox_name(); + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} {attributes} {plain}", + quote(&bbox) + )) + .await; + if grant { + fixture + .server + .superuser + .exec(&format!("GRANT pg_read_all_data TO {}", quote(&bbox))) + .await; + } + let error = fixture + .provision(&fixture.spatial_product((3, 5))) + .await + .unwrap_err(); + let expected = if grant { + "platform.provision.role-membership-differs" + } else { + "platform.provision.role-attributes-differ" + }; + assert_eq!(error.code(), expected, "{attributes}"); + assert_eq!(error.step(), Some("role.spatial-bbox")); + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn an_existing_template_database_is_not_adopted() { + let _serial = lock().await; + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + fixture + .server + .superuser + .exec(&format!( + "CREATE DATABASE {} IS_TEMPLATE true", + quote(&fixture.database()) + )) + .await; + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.database-is-template"); + assert_eq!(error.step(), Some("database.create")); + assert_eq!( + fixture + .server + .superuser + .text(&format!( + "SELECT coalesce(datacl::text, '') FROM pg_catalog.pg_database \ + WHERE datname = '{}'", + fixture.database() + )) + .await, + "", + "the template database is untouched" + ); + fixture + .server + .superuser + .exec(&format!( + "ALTER DATABASE {} IS_TEMPLATE false", + quote(&fixture.database()) + )) + .await; + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_failure_part_way_returns_the_statements_that_ran() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + let plan = plan(&product, &fixture.target()).unwrap(); + let failure = execute_recording(&fixture.admin(), &plan, Mode::Converge) + .await + .unwrap_err(); + assert_eq!(failure.error.step(), Some("extension.postgis")); + let ran: Vec<_> = failure.reached.iter().map(|(step, _)| *step).collect(); + let before_postgis: Vec<_> = plan + .statements() + .iter() + .map(|statement| statement.step) + .take_while(|step| *step != "extension.postgis") + .collect(); + assert_eq!(ran, before_postgis); + assert!(failure + .reached + .iter() + .any(|(step, outcome)| *step == "role.migration" && *outcome == StatementOutcome::Created)); + fixture.cleanup().await; +} + +#[tokio::test] +async fn postgis_installed_outside_the_plan_is_named_until_the_whole_block_has_run() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + let error = fixture.provision(&product).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + + // A superuser installs only the extension, without the grants and the + // bbox membership the rest of the block sets up. + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + session + .exec( + "CREATE SCHEMA registry_spatial_ext; \ + CREATE EXTENSION postgis WITH SCHEMA registry_spatial_ext", + ) + .await; + let error = fixture.provision(&product).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.extension-incomplete"); + assert_eq!(error.step(), Some("extension.postgis")); + + // The whole printed block, then provision again. + let plan = plan(&product, &fixture.target()).unwrap(); + let block = plan + .statements() + .iter() + .find(|statement| statement.step == "extension.postgis") + .unwrap(); + session.exec(&block.printable).await; + let outcome = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&outcome, "extension.postgis"), + StatementOutcome::Present + ); + assert!( + session + .flag(&format!( + "SELECT pg_catalog.pg_has_role({}::name, {}::name, 'SET')", + quote_literal(&fixture.migration_name()), + quote_literal(&fixture.bbox_name()) + )) + .await + ); + drop(session); + fixture.cleanup().await; + + // PostGIS in the default schema is no better. + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let error = fixture.provision(&product_for(&fixture)).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + session.exec("CREATE EXTENSION postgis").await; + let error = fixture.provision(&product_for(&fixture)).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.extension-incomplete"); + drop(session); + fixture.cleanup().await; +} + +fn product_for(fixture: &Fixture) -> ProductDatabase { + fixture.spatial_product((3, 5)) +} + +#[tokio::test] +async fn provision_gives_the_runtime_role_usage_on_public_and_restores_it() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = Fixture::public_product(); + fixture.provision(&product).await.unwrap(); + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + let usage = |role: String| { + format!( + "SELECT pg_catalog.has_schema_privilege({}, 'public', 'USAGE')", + quote_literal(&role) + ) + }; + // A server whose PUBLIC lost USAGE on `public`, and a runtime role that + // lost its own. + session + .exec(&format!( + "REVOKE USAGE ON SCHEMA public FROM PUBLIC; \ + REVOKE USAGE ON SCHEMA public FROM {}", + quote(&fixture.runtime_name()) + )) + .await; + assert!(!session.flag(&usage(fixture.runtime_name())).await); + + fixture.provision(&product).await.unwrap(); + assert!(session.flag(&usage(fixture.runtime_name())).await); + assert!(session.flag(&usage(fixture.migration_name())).await); + assert!( + !session.flag(&usage("public".to_owned())).await, + "the runtime role holds USAGE directly, not through PUBLIC" + ); + let grant_option = session + .flag(&format!( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.aclexplode(nspacl) a \ + JOIN pg_catalog.pg_roles g ON g.oid = a.grantee \ + WHERE a.is_grantable AND g.rolname IN ({}, {})) \ + FROM pg_catalog.pg_namespace WHERE nspname = 'public'", + quote_literal(&fixture.migration_name()), + quote_literal(&fixture.runtime_name()) + )) + .await; + assert!(!grant_option, "no role holds a grant option on public"); + drop(session); + fixture.cleanup().await; +} + #[tokio::test] async fn existing_database_owned_by_another_role_is_refused() { let _serial = lock().await; @@ -1058,11 +1413,43 @@ async fn a_changed_password_fails_the_login_check_for_that_role() { .await .unwrap_err(); assert_eq!(error.code(), "platform.provision.role-login-failed"); + assert!(matches!( + &error, + ProvisionError::RoleLoginFailed { sqlstate: Some(state), .. } if state == "28P01" + )); assert!(error.to_string().contains(&fixture.runtime_name())); assert!(!error.to_string().contains(&fixture.migration_name())); fixture.cleanup().await; } +#[tokio::test] +async fn a_login_refused_for_another_reason_carries_that_sqlstate() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture.provision(&Fixture::public_product()).await.unwrap(); + for (alter, sqlstate) in [("NOLOGIN", "28000"), ("LOGIN CONNECTION LIMIT 0", "53300")] { + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {} {alter}", + quote(&fixture.runtime_name()) + )) + .await; + let error = verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap_err(); + assert!( + matches!( + &error, + ProvisionError::RoleLoginFailed { sqlstate: Some(state), .. } if state == sqlstate + ), + "{alter}: {error:?}" + ); + } + fixture.cleanup().await; +} + // ---- A.13 test 9 ---------------------------------------------------------- fn unquote(identifier: &str) -> String { @@ -1086,6 +1473,9 @@ async fn run_script(fixture: &Fixture, script: &str) { if pending.is_empty() && line.starts_with("--") { continue; } + if line.starts_with("\\set ") { + continue; + } if let Some(database) = line.strip_prefix("\\connect ") { session = server .session( diff --git a/crates/registry-rstack-dev/src/database.rs b/crates/registry-rstack-dev/src/database.rs index d7d88e55ab..6e47652df9 100644 --- a/crates/registry-rstack-dev/src/database.rs +++ b/crates/registry-rstack-dev/src/database.rs @@ -1690,7 +1690,8 @@ mod tests { } else { format!( "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ - GRANT USAGE, CREATE ON SCHEMA public TO {migration}" + GRANT USAGE, CREATE ON SCHEMA public TO {migration}; \ + GRANT USAGE ON SCHEMA public TO {runtime}" ) }; assert_eq!(batches.setup, expected_setup, "{label}"); @@ -1731,7 +1732,8 @@ mod tests { } #[test] - fn casework_setup_gives_only_migration_role_public_schema_creation() { + fn casework_setup_gives_the_runtime_role_usage_on_public_and_only_the_migration_role_creation() + { let names = Names::new(RUN_ID, "casework"); let sql = Batches::new(&names, false, false, "migration-secret", "runtime-secret") .unwrap() @@ -1744,11 +1746,15 @@ mod tests { "GRANT USAGE, CREATE ON SCHEMA public TO {}", quote_identifier(&names.migration_role) ))); - assert!(!sql.contains(&names.runtime_role)); + assert!(sql.ends_with(&format!( + "GRANT USAGE ON SCHEMA public TO {}", + quote_identifier(&names.runtime_role) + ))); + assert_eq!(sql.matches(&names.runtime_role).count(), 1, "{sql}"); } #[test] - fn messaging_setup_gives_only_migration_role_public_schema_creation() { + fn messaging_setup_gives_the_runtime_role_no_public_schema_creation() { let names = Names::new(RUN_ID, "messaging"); let sql = Batches::new(&names, false, false, "migration-secret", "runtime-secret") .unwrap() @@ -1757,7 +1763,10 @@ mod tests { sql.starts_with("REVOKE CREATE ON SCHEMA public FROM PUBLIC;"), "{sql}" ); - assert!(!sql.contains(&names.runtime_role)); + assert!(!sql.contains(&format!( + "CREATE ON SCHEMA public TO {}", + quote_identifier(&names.runtime_role) + ))); assert_eq!( names.database, format!("rstack_{RUN_ID}_messaging"), diff --git a/crates/registry-schedulingctl/src/provision.rs b/crates/registry-schedulingctl/src/provision.rs index ce31dd05fe..b31f2fa7de 100644 --- a/crates/registry-schedulingctl/src/provision.rs +++ b/crates/registry-schedulingctl/src/provision.rs @@ -13,8 +13,9 @@ use registry_scheduling::config::{startup_report, RuntimeConfig}; use registry_scheduling_core::SCHEDULING_RUNTIME_KIND; use zeroize::Zeroizing; -/// Scheduling keeps its tables in `public`, handed to the migration -/// role, and needs no extension. +/// Scheduling keeps its tables in `public`. `provision` gives the migration role +/// USAGE and CREATE on it and the runtime role USAGE, directly. It needs no +/// extension. fn product() -> ProductDatabase { ProductDatabase { product: "scheduling", diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index b92af2ce05..88c1de8d21 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -277,8 +277,9 @@ REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public The names come from your URLs. Add `--format json` for a report of each statement and its outcome. -`provision` grants the runtime role nothing beyond `CONNECT`. `apply`, in the next section, grants -it its access to the schema and the Messaging tables and sequences. The runtime requires TLS on +`provision` grants the runtime role `CONNECT` on the database and `USAGE` on the `public` schema, +and running `provision` again restores that grant. `apply`, in the next section, grants it its +access to the Messaging tables and sequences. It does not restore `USAGE` on `public`. The runtime requires TLS on its database connection and refuses one it cannot verify; `database.caBundleRef` names the CA bundle when a private CA fronts PostgreSQL. diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index f5c30bbbc1..4d7b7411b9 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -181,10 +181,11 @@ REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public The names come from your URLs. Add `--format json` for a report of each statement and its outcome. -`provision` grants the runtime role nothing beyond `CONNECT`. `apply` grants it exactly what serving -needs: usage on the schema, read and write on the Scheduling tables, usage and select on the outbox -identity sequence, and read on the activation ledgers. It reissues the grants on every run, so a -table a later migration adds is covered. The runtime requires TLS on its database connection and +`provision` grants the runtime role `CONNECT` on the database and `USAGE` on the `public` schema, +and running `provision` again restores that grant. `apply` grants it the rest of what serving needs: +read and write on the Scheduling tables, usage and select on the outbox identity sequence, and read +on the activation ledgers. It reissues those grants on every run, so a table a later migration adds +is covered, but it does not restore `USAGE` on `public`. The runtime requires TLS on its database connection and refuses one it cannot verify; `database.caBundleRef` names the CA bundle when a private CA fronts PostgreSQL. diff --git a/docs/site/src/content/docs/reference/errors.mdx b/docs/site/src/content/docs/reference/errors.mdx index 81d79c1b71..de8b7d1182 100644 --- a/docs/site/src/content/docs/reference/errors.mdx +++ b/docs/site/src/content/docs/reference/errors.mdx @@ -110,15 +110,18 @@ These products differ: - BReg answers 503 with a problem body (`runtime.not_ready`). - OID4VCI answers 503 with `{"status":"not_ready"}`. -- Coordinator answers `{"ready":true}`. -- Scheduling serves `/readyz` under its deployment health contract. -- Casework, Messaging, and Documents answer without a body. +- Casework and Scheduling answer 200 with the shared body `{"status":"ready"}`, and `/health` with `{"status":"ok"}`. +- Coordinator answers 200 with `{"ready":true,"status":"ready"}` and 503 with `{"ready":false}`. +- Scheduling also serves `/readyz`, a bodyless probe on the same readiness test, under its deployment health contract. +- Messaging and Documents answer without a body. {/* Evidence: crates/registry-breg/src/problem.rs RuntimeNotReady; crates/registry-evidence-oid4vci/src/service.rs not_ready; + crates/registry-platform-httputil/src/probe.rs READY_BODY; + crates/registry-casework/src/http.rs ready; crates/registry-coordinator/src/http.rs ready; - crates/registry-scheduling/src/http.rs readyz. */} -{/* TODO[evidence]: the generic `{"status":"ready"}` / `{"status":"not-ready"}` body and the bodyless Casework, Messaging, and Documents readiness answers have no single code anchor. */} + crates/registry-scheduling/src/http.rs ready, readyz. */} +{/* TODO[evidence]: the generic `{"status":"not-ready"}` body and the bodyless Messaging and Documents readiness answers have no single code anchor. */} ## Idempotency and retries diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index aab94d6573..25f7cbec8f 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5432,7 +5432,7 @@ "description": "Registry Coordinator runtime configuration JSON Schema.", "source": { "path": "crates/registry-coordinator/src/runtime.rs", - "sha256": "b819cb03b63fd52ba179f2ed4062c2c26ec1da3dd57278abe3819db21d6898ad" + "sha256": "5a9e84b169d847669e97d8d53073ddbb98928c92470ee167f9020df98120fd6b" }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", @@ -5540,7 +5540,7 @@ "description": "Registry Document Store event data JSON Schemas, one per event family.", "source": { "path": "crates/registry-documents/src/schema.rs", - "sha256": "819d4b5c92e5a318e75e3d89c0e38d65bb53632c6ff1dbcc7f2fa1cd627c310a" + "sha256": "980b91e5598a527abac734928b06c7290c2b4c4482589c9dd832127f0bc2f9bc" }, "artifact": { "path": "products/documents/generated/events/document-grant-changed.schema.json", @@ -5558,7 +5558,7 @@ "description": "Registry Document Store event data JSON Schemas, one per event family.", "source": { "path": "crates/registry-documents/src/schema.rs", - "sha256": "819d4b5c92e5a318e75e3d89c0e38d65bb53632c6ff1dbcc7f2fa1cd627c310a" + "sha256": "980b91e5598a527abac734928b06c7290c2b4c4482589c9dd832127f0bc2f9bc" }, "artifact": { "path": "products/documents/generated/events/document-version-ready.schema.json", @@ -5576,7 +5576,7 @@ "description": "Registry Document Store event data JSON Schemas, one per event family.", "source": { "path": "crates/registry-documents/src/schema.rs", - "sha256": "819d4b5c92e5a318e75e3d89c0e38d65bb53632c6ff1dbcc7f2fa1cd627c310a" + "sha256": "980b91e5598a527abac734928b06c7290c2b4c4482589c9dd832127f0bc2f9bc" }, "artifact": { "path": "products/documents/generated/events/document-version-rejected.schema.json", @@ -5594,7 +5594,7 @@ "description": "Registry Document Store project JSON Schema.", "source": { "path": "crates/registry-documents/src/schema.rs", - "sha256": "819d4b5c92e5a318e75e3d89c0e38d65bb53632c6ff1dbcc7f2fa1cd627c310a" + "sha256": "980b91e5598a527abac734928b06c7290c2b4c4482589c9dd832127f0bc2f9bc" }, "artifact": { "path": "products/documents/generated/project/project.schema.json", @@ -5612,11 +5612,11 @@ "description": "Registry Document Store runtime configuration JSON Schema.", "source": { "path": "crates/registry-documents/src/schema.rs", - "sha256": "819d4b5c92e5a318e75e3d89c0e38d65bb53632c6ff1dbcc7f2fa1cd627c310a" + "sha256": "980b91e5598a527abac734928b06c7290c2b4c4482589c9dd832127f0bc2f9bc" }, "artifact": { "path": "products/documents/generated/runtime/runtime.schema.json", - "sha256": "93ad66566ca8cd15468565ae01f966a85ce5b8f6f00588babde370d155190402", + "sha256": "c132d0dea03c4d33a9387b5e0ddfb5b9dc7b6384287c7133e3c06d51114716ce", "mediaType": "application/schema+json" } }, @@ -5972,7 +5972,7 @@ "description": "Registry Messaging project, template, and HTTP provider authoring JSON Schema.", "source": { "path": "crates/registry-messaging/src/schema.rs", - "sha256": "c9ac98430ca6c4b4cf404688dda544d196aa624cc9dfb56cf737a3e2c8b8b359" + "sha256": "b098b5a7aaef9607076c971ce3bb2fd55e4100233f89e7cedf82083171788e37" }, "artifact": { "path": "products/messaging/generated/authoring/project.schema.json", @@ -5990,7 +5990,7 @@ "description": "Registry Messaging project, template, and HTTP provider authoring JSON Schema.", "source": { "path": "crates/registry-messaging/src/schema.rs", - "sha256": "c9ac98430ca6c4b4cf404688dda544d196aa624cc9dfb56cf737a3e2c8b8b359" + "sha256": "b098b5a7aaef9607076c971ce3bb2fd55e4100233f89e7cedf82083171788e37" }, "artifact": { "path": "products/messaging/generated/authoring/provider.schema.json", @@ -6008,11 +6008,11 @@ "description": "Registry Messaging runtime configuration JSON Schema.", "source": { "path": "crates/registry-messaging/src/schema.rs", - "sha256": "c9ac98430ca6c4b4cf404688dda544d196aa624cc9dfb56cf737a3e2c8b8b359" + "sha256": "b098b5a7aaef9607076c971ce3bb2fd55e4100233f89e7cedf82083171788e37" }, "artifact": { "path": "products/messaging/generated/runtime/runtime.schema.json", - "sha256": "3c5429e7eedfcaf3ff2d79b7979f8996fafbfc93edc454e98acf09715810fb18", + "sha256": "daa1af1db5b235398feaa98417f8cf682a60703557065df61552d0579d97819a", "mediaType": "application/schema+json" } }, @@ -6026,7 +6026,7 @@ "description": "Registry Messaging project, template, and HTTP provider authoring JSON Schema.", "source": { "path": "crates/registry-messaging/src/schema.rs", - "sha256": "c9ac98430ca6c4b4cf404688dda544d196aa624cc9dfb56cf737a3e2c8b8b359" + "sha256": "b098b5a7aaef9607076c971ce3bb2fd55e4100233f89e7cedf82083171788e37" }, "artifact": { "path": "products/messaging/generated/authoring/template.schema.json", @@ -6098,11 +6098,11 @@ "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions.", "source": { "path": "crates/registry-platform-provision/src/cli.rs", - "sha256": "76bb9ff03c5acfde5c92823721ded6f3587b5185fef95cd4c80c159bbc04be69" + "sha256": "097c8da77b747a79f756b5ab511c296a0b1868e1650ebb8826dfb3b981e02164" }, "artifact": { "path": "crates/registry-platform-provision/schema/provision-report.schema.json", - "sha256": "6b3a5f1f63ac5bc66ce1d84142cb4004f62cb47e130c57685cdc2fc5d1ec6d15", + "sha256": "e0e39e826b35c83161ea544805d6b33a18bd1365033fd497022cefe05f30b0bb", "mediaType": "application/schema+json" } }, diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 3e6f2790cb..0874bfbdb9 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -39,6 +39,25 @@ and the crypto stack. A service that passes its trace id to `record_refusal!` enables the feature. +- `registry-platform-provision` is the one provisioning plan for every + database-backed tool, with the `provision` command behind its `cli` feature + (`cli::run_provision`). From the two product URLs it creates the migration + and runtime login roles, an isolated database closed to `PUBLIC`, the + product's schema layout and the optional `btree_gist` and PostGIS + extensions. It can run as an administrator over verified TLS, converging by + object, or print a `psql` script that holds no password and stops at the + first error. It refuses an existing role with other attributes, role-level + settings or a membership it did not grant, a template database, a PostGIS + installed outside its schema or without the bbox membership, a role name + that is `public`, `none` or starts with `pg_`, a name with a control + character or backslash, and the `postgres`, `template0` and `template1` + databases. It grants the runtime role `USAGE` on `public` directly, so + running `provision` again restores it. A run that stops part-way reports + the statements that ran. `registry-platform-activation` exports + `MINIMUM_SERVER_VERSION_NUM`, the PostgreSQL 17 floor the plan and the + activation ledger share. `rstack dev` provisions its databases from the + same plan. + - A `test-support` feature in `registry-platform-provision` gives the product provision tests one verified-TLS superuser session, so they run against a TLS-only PostgreSQL server. It is enabled only by dev-dependencies. From de101283232c087ed65788a098b28773b8af6b51 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:42:02 +0100 Subject: [PATCH 039/136] fix: count each refusal under its own check in five runtimes fix(documents): count grant refusals by ownership and test the loader refusals A caller that sees a document and does not hold custody of it is counted under ownership when it lists or issues grants, as it is when it downloads or requests erasure. A custodian without grant authority is counted under operation. A token with no client id counts under token-client. A verifier that cannot reach its key source still answers 503 and is recorded by the request refused line and the counter, not a warning per request. No answer changes. The refusal golden file covers a client the verifier admits and no access profile lists, and a new suite covers the key-source refusal. documentsctl provision has tests for a missing or non-UTF-8 runtime secret, a missing CA bundle secret and a runtime file the runtime refuses, and a dotted client id gets the right pointer in the assertion-issuer refusal. The operate page says provision grants the runtime role USAGE on public and restores it, and the security invariant matrix names the coverage check's refusal and tests. fix(casework): count only real refusals, each under the check that refused it An absence that conceals nothing, such as the task grant key set route when task grants are not configured, is no longer counted as a refusal. A concealed target keeps the authentication check it hid, and revoking an inactive template counts under operation. Every 401 or 403 answer names a check, and the PostgreSQL suites assert the check each refusal records. No answer changes. caseworkctl provision has tests for the runtime file refusals it shares with the runtime and asserts that split-role apply stays split. The operate page documents provision after the package it reads, and says provision grants the runtime role USAGE on public and restores it. The security page and the changelog describe the counting as the code does. fix(breg): count task grant and batch refusals under their own checks An expired task grant counts under task-grant-expired, a grant bound to another client or resource under task-grant-binding, a grant token with no iat, an iat ahead of the clock or an exp not after iat under task-grant-claims, and a lifetime over 900 seconds under task-grant-lifetime. A batch of Proposal review contexts still answers 200 and counts each concealed item once. No answer changes. A static key set the shared rule refuses keeps the startup.oidc.refused code, and the startup log and bregctl doctor name the rule once and, for a rule about one key, the key's position. The refusal golden files cover expired, misbound and future-dated grants, an unreachable key source, a malformed actor kind or act claim and an unadmitted token type, and the malformed-token corpus runs through the router with its counter asserted. The security and monitoring pages name the answers that are not counted. fix(coordinator): count key-source failures and refuse a mismatched runtime role A signed event delivery that Coordinator cannot verify because its own signing key is unreadable, missing or too short counts under key-source-unavailable, as does a receiver key that cannot be used. The two recovery refusals count under operation and token-claims. The answers are unchanged. A static key set that startup refuses names the rule it broke in the access.configuration message. When the runtime file has a deployment block, coordinatorctl provision refuses a runtime URL whose user is not deployment.runtimeRole before it connects, with coordinator.runtime-config.runtime-role-mismatch. The operate page gives the shared probe bodies and says the runtime role name must match, and the metrics test asserts the credential, scope and access-profile checks against a real service. fix(render): count and log each authentication refusal under its own check Render and the MCP edge name the check behind each refusal more precisely, with no change to any status, header or body a caller receives. - Render answers a repeated or non-ASCII Authorization header, a value shorter than the scheme, and a token for the wrong client with the same 401 as before, now pinned in the golden refusal set. A refusal whose audit entry cannot be written is answered as an audit failure and is not counted. A static key set Render refuses at startup names the reason in the render.runtime-invalid detail. - The MCP edge counts a token with an empty subject under token-claims and pins the Retry-After value it already sent. An unreachable key set is one line with failed_check key-source-unavailable, and a request the gateway cannot admit because of its own fault writes at most one error line a minute. - The BReg MCP gateway and the review page now also accept the IPv4-mapped loopback form under development-loopback. Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/api/proposals.rs | 7 +- crates/registry-breg/src/auth.rs | 181 +++++++++++------ crates/registry-breg/src/correlation.rs | 21 +- crates/registry-breg/src/runtime_config.rs | 3 +- crates/registry-breg/src/startup.rs | 20 +- .../tests/authentication_refusals.rs | 156 ++++++++++++++- .../tests/golden/authentication_refusals.json | 148 ++++++++++++++ crates/registry-breg/tests/http_auth.rs | 3 +- .../registry-breg/tests/postgres_proposal.rs | 53 +++++ crates/registry-breg/tests/runtime_config.rs | 17 ++ crates/registry-breg/tests/startup_http.rs | 22 ++- crates/registry-bregctl/src/doctor.rs | 29 +++ crates/registry-casework/src/assignment.rs | 6 +- crates/registry-casework/src/clocks.rs | 2 +- crates/registry-casework/src/config.rs | 4 +- crates/registry-casework/src/http.rs | 79 +++++++- .../src/http/source_credentials.rs | 10 +- crates/registry-casework/src/service.rs | 3 + crates/registry-casework/src/store.rs | 4 + crates/registry-casework/src/task_grants.rs | 8 +- .../src/task_grants/http_tests.rs | 67 ++++++- .../src/task_grants/lock_order_tests.rs | 5 +- .../registry-casework/tests/refusal_golden.rs | 55 ++++-- .../tests/review_acceptance_postgres.rs | 21 +- .../tests/review_directory_postgres.rs | 25 ++- .../tests/review_postgres.rs | 43 ++-- .../support/authority_closure_regressions.rs | 2 +- .../independent_staffing_activation.rs | 8 +- .../registry-caseworkctl/tests/provision.rs | 148 ++++++++++++++ crates/registry-coordinator/src/access.rs | 27 ++- .../registry-coordinator/src/event_trigger.rs | 3 + .../src/event_trigger_tests.rs | 32 +++ crates/registry-coordinator/src/http.rs | 9 + crates/registry-coordinator/src/provision.rs | 32 ++- .../src/store/recovery.rs | 61 +++++- .../tests/deployment_postgres.rs | 21 +- .../tests/provision_cli.rs | 184 ++++++++++++++++-- .../tests/provision_postgres.rs | 4 + .../tests/static_key_set.rs | 88 +++++++++ crates/registry-documents-core/src/project.rs | 3 + .../tests/actor_kind_all.rs | 20 ++ crates/registry-documents/Cargo.toml | 5 + crates/registry-documents/src/auth.rs | 36 +++- crates/registry-documents/src/config.rs | 15 +- crates/registry-documents/src/http.rs | 2 +- crates/registry-documents/src/runtime.rs | 6 +- crates/registry-documents/src/service.rs | 58 ++++-- .../registry-documents/src/service/grants.rs | 10 +- .../tests/golden/refusals.json | 14 ++ .../tests/refusal_golden.rs | 42 +++- .../tests/refusal_key_source.rs | 87 +++++++++ .../registry-documents/tests/support/mod.rs | 13 +- .../tests/provision_cli.rs | 110 ++++++++++- .../tests/provision_postgres.rs | 6 + .../src/compatibility_tests/inbound.rs | 4 +- crates/registry-mcp-edge/src/inbound.rs | 45 ++++- .../src/inbound/refusal_tests.rs | 61 +++++- .../tests/golden/refusals.json | 17 +- crates/registry-render/src/auth.rs | 103 ++++++++-- crates/registry-render/src/metrics.rs | 5 +- crates/registry-render/src/server.rs | 144 +++++++++++--- .../tests/golden/authentication_refusals.json | 60 ++++++ crates/registry-render/tests/serve.rs | 4 + .../src/content/docs/configure/breg-mcp.mdx | 10 +- .../src/content/docs/operate/breg-monitor.mdx | 22 ++- .../src/content/docs/operate/casework.mdx | 113 +++++------ .../src/content/docs/operate/coordinator.mdx | 14 +- .../src/content/docs/operate/documents.mdx | 37 ++-- docs/site/src/content/docs/security/breg.mdx | 16 +- .../src/content/docs/security/casework.mdx | 14 +- .../src/content/docs/security/coordinator.mdx | 12 +- .../src/content/docs/security/documents.mdx | 2 +- .../site/src/content/docs/security/render.mdx | 6 +- products/breg/CHANGELOG.md | 38 ++-- products/casework/CHANGELOG.md | 24 ++- .../contracts/security-invariant-matrix.yaml | 2 +- .../contracts/security-test-traceability.yaml | 2 +- products/coordinator/CHANGELOG.md | 13 ++ products/documents/CHANGELOG.md | 22 ++- .../contracts/recorded-decisions.yaml | 25 +++ .../contracts/security-invariant-matrix.yaml | 7 +- .../scripts/check_database_test_isolation.py | 2 + products/platform/CHANGELOG.md | 13 +- products/render/CHANGELOG.md | 6 +- 84 files changed, 2463 insertions(+), 418 deletions(-) create mode 100644 crates/registry-coordinator/tests/static_key_set.rs create mode 100644 crates/registry-documents-core/tests/actor_kind_all.rs create mode 100644 crates/registry-documents/tests/refusal_key_source.rs diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index 98dfbdf74a..94c904c8da 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -1321,7 +1321,12 @@ pub(super) async fn review_context_batch( }; items.push(json!({"id":id,"status":"visible","context":context})); } - StatusCode::NOT_FOUND => items.push(json!({"id":id,"status":"concealed"})), + StatusCode::NOT_FOUND => { + // The batch answers 200, so each concealed item records its + // own refusal here. + crate::correlation::record_noted_refusal(&response, &correlation); + items.push(json!({"id":id,"status":"concealed"})); + } _ => return response, } } diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index a23c2a03a7..070d676254 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -17,8 +17,8 @@ use registry_platform_authcommon::{ parse_bearer_token, validate_compact_access_token, BearerParseError, FailedCheck, }; use registry_platform_oidc::{ - actor_kind, grant_claims, is_access_token_typ_pair, Audience, ClaimNames, JwksFetcher, - OidcError, TokenVerifier, TokenVerifierConfig, + actor_kind, grant_claims, is_access_token_typ_pair, Audience, ClaimError, ClaimNames, + GrantContextError, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, }; use serde_json::Value; use thiserror::Error; @@ -364,20 +364,26 @@ impl RegistryAuthenticator { .duration_since(UNIX_EPOCH) .map_err(|_| invalid_claims(FailedCheck::TokenTime))? .as_secs(); - let grant = grant_claims(&verified.claims, &self.contextual_claims, now) - .map_err(|_| invalid_claims(FailedCheck::TaskGrantClaims))?; + let grant = + grant_claims(&verified.claims, &self.contextual_claims, now).map_err(|error| { + invalid_claims(match error { + ClaimError::Expired => FailedCheck::TaskGrantExpired, + _ => FailedCheck::TaskGrantClaims, + }) + })?; if let Some(grant) = &grant { grant .verify_context(&verified, &self.audience) - .map_err(|_| invalid_claims(FailedCheck::TaskGrantClaims))?; - if !task_grant_token_lifetime_is_short( - verified.claims.iat, - verified.claims.exp, - now, - self.leeway, - ) { - return Err(invalid_claims(FailedCheck::TaskGrantLifetime)); - } + .map_err(|error| { + invalid_claims(match error { + GrantContextError::ClientMismatch | GrantContextError::ResourceMismatch => { + FailedCheck::TaskGrantBinding + } + _ => FailedCheck::TaskGrantClaims, + }) + })?; + task_grant_token_lifetime(verified.claims.iat, verified.claims.exp, now, self.leeway) + .map_err(invalid_claims)?; } let grant_subjects = if grant.is_some() { bounded_identity(claims.get("identity")) @@ -432,25 +438,34 @@ impl RegistryAuthenticator { } } -/// A task-grant token must carry `iat` and `exp`, be issued for between 1 and -/// [`MAX_TASK_GRANT_TOKEN_LIFETIME_SECONDS`], and carry an `iat` no later than -/// `now` plus the verifier's clock leeway, so its issued lifetime also bounds -/// the time it is honoured from this clock. -fn task_grant_token_lifetime_is_short( +/// A task-grant token must carry `iat` and `exp`, with `exp` after `iat` and +/// `iat` no later than `now` plus the verifier's clock leeway. A token that +/// fails any of those is a malformed grant token (`TaskGrantClaims`). One that +/// is well formed but issued for more than +/// [`MAX_TASK_GRANT_TOKEN_LIFETIME_SECONDS`] is refused as `TaskGrantLifetime`, +/// so its issued lifetime also bounds the time it is honoured from this clock. +fn task_grant_token_lifetime( issued_at: Option, expires_at: Option, now: u64, leeway: Duration, -) -> bool { +) -> Result<(), FailedCheck> { let latest_issued_at = now .checked_add(leeway.as_secs()) .and_then(|latest| i64::try_from(latest).ok()); - issued_at - .zip(expires_at) - .zip(latest_issued_at) - .filter(|((issued_at, _), latest_issued_at)| issued_at <= latest_issued_at) - .and_then(|((issued_at, expires_at), _)| expires_at.checked_sub(issued_at)) - .is_some_and(|lifetime| (1..=MAX_TASK_GRANT_TOKEN_LIFETIME_SECONDS).contains(&lifetime)) + let (Some(issued_at), Some(expires_at), Some(latest_issued_at)) = + (issued_at, expires_at, latest_issued_at) + else { + return Err(FailedCheck::TaskGrantClaims); + }; + let lifetime = expires_at.saturating_sub(issued_at); + if issued_at > latest_issued_at || lifetime < 1 { + return Err(FailedCheck::TaskGrantClaims); + } + if lifetime > MAX_TASK_GRANT_TOKEN_LIFETIME_SECONDS { + return Err(FailedCheck::TaskGrantLifetime); + } + Ok(()) } fn admit_refusal_warning(last_warning: &Mutex>, now: Instant) -> bool { @@ -1086,35 +1101,94 @@ mod tests { )); } + /// Every 401 the service answers carries the failed check. The two + /// constructors that note one are the only non-test sites that build a 401 + /// or name `ProblemCode::AuthenticationRefused`, so a new site cannot + /// answer 401 without a check unless it is added to this list on purpose. + #[test] + fn only_the_noting_constructors_build_a_401() { + fn visit(dir: &std::path::Path, found: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("source directory is readable") { + let path = entry.expect("directory entry is readable").path(); + if path.is_dir() { + visit(&path, found); + continue; + } + let name = path.to_string_lossy().into_owned(); + if !name.ends_with(".rs") + || name.contains("tests") + || name.ends_with("/problem.rs") + || name.ends_with("/compiler.rs") + { + continue; + } + let text = std::fs::read_to_string(&path).expect("source file is readable"); + let production = text + .split("#[cfg(test)]\nmod tests {") + .next() + .unwrap_or_default(); + for needle in [ + "StatusCode::UNAUTHORIZED", + "ProblemCode::AuthenticationRefused", + ] { + for _ in production.matches(needle) { + found.push(format!( + "{needle} in {}", + path.file_name().expect("file name").to_string_lossy() + )); + } + } + } + } + let mut found = Vec::new(); + visit( + &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), + &mut found, + ); + found.sort(); + assert_eq!( + found, + [ + "ProblemCode::AuthenticationRefused in mod.rs", + "StatusCode::UNAUTHORIZED in auth.rs", + ] + ); + } + #[test] fn task_grant_tokens_must_be_issued_for_at_most_fifteen_minutes() { let issued = 1_800_000_000; let now = 1_800_000_000; let leeway = Duration::from_secs(60); - assert!(task_grant_token_lifetime_is_short( - Some(issued), - Some(issued + 900), - now, - leeway - )); - assert!(task_grant_token_lifetime_is_short( - Some(issued), - Some(issued + 1), - now, - leeway - )); + assert_eq!( + task_grant_token_lifetime(Some(issued), Some(issued + 900), now, leeway), + Ok(()) + ); + assert_eq!( + task_grant_token_lifetime(Some(issued), Some(issued + 1), now, leeway), + Ok(()) + ); for (issued_at, expires_at) in [ (Some(issued), Some(issued + 901)), (Some(issued - 604_200), Some(issued + 600)), + (Some(i64::MIN), Some(i64::MAX)), + ] { + assert_eq!( + task_grant_token_lifetime(issued_at, expires_at, now, leeway), + Err(FailedCheck::TaskGrantLifetime), + "iat {issued_at:?} and exp {expires_at:?} are too long" + ); + } + for (issued_at, expires_at) in [ (None, Some(issued + 600)), (Some(issued), None), (Some(issued), Some(issued)), (Some(issued + 1), Some(issued)), - (Some(i64::MIN), Some(i64::MAX)), ] { - assert!( - !task_grant_token_lifetime_is_short(issued_at, expires_at, now, leeway), - "iat {issued_at:?} and exp {expires_at:?} are refused" + assert_eq!( + task_grant_token_lifetime(issued_at, expires_at, now, leeway), + Err(FailedCheck::TaskGrantClaims), + "iat {issued_at:?} and exp {expires_at:?} are malformed" ); } } @@ -1125,29 +1199,22 @@ mod tests { let leeway = Duration::from_secs(60); let at = |offset: i64| i64::try_from(now).expect("test clock fits i64") + offset; for issued_at in [at(86_400), at(61)] { - assert!( - !task_grant_token_lifetime_is_short( - Some(issued_at), - Some(issued_at + 900), - now, - leeway - ), + assert_eq!( + task_grant_token_lifetime(Some(issued_at), Some(issued_at + 900), now, leeway), + Err(FailedCheck::TaskGrantClaims), "iat {issued_at} later than now plus leeway is refused" ); } for issued_at in [at(59), at(60)] { - assert!( - task_grant_token_lifetime_is_short( - Some(issued_at), - Some(issued_at + 900), - now, - leeway - ), + assert_eq!( + task_grant_token_lifetime(Some(issued_at), Some(issued_at + 900), now, leeway), + Ok(()), "iat {issued_at} within the leeway is accepted" ); } - assert!( - !task_grant_token_lifetime_is_short(Some(at(0)), Some(at(900)), u64::MAX, leeway), + assert_eq!( + task_grant_token_lifetime(Some(at(0)), Some(at(900)), u64::MAX, leeway), + Err(FailedCheck::TaskGrantClaims), "a clock that cannot bound iat refuses the token" ); } diff --git a/crates/registry-breg/src/correlation.rs b/crates/registry-breg/src/correlation.rs index 5855fea092..5415a5dffd 100644 --- a/crates/registry-breg/src/correlation.rs +++ b/crates/registry-breg/src/correlation.rs @@ -445,13 +445,7 @@ pub(crate) fn finish_response( ); } correlation.apply_trace(response.headers_mut()); - if let Some(note) = response.extensions().get::().copied() { - record_refusal!( - crate::metrics::process_refusal_recorder(), - note, - trace_id = correlation.trace_id() - ); - } + record_noted_refusal(&response, correlation); let status = status_class(response.status()); let problem_code = problem.as_ref().map_or("none", |problem| problem.code); @@ -468,6 +462,19 @@ pub(crate) fn finish_response( response } +/// Count and log the refusal a response carries, if any. A handler that folds +/// several refused items into one answer calls this for each item, because the +/// folded answer is not itself a refusal. +pub(crate) fn record_noted_refusal(response: &Response, correlation: &RequestCorrelation) { + if let Some(note) = response.extensions().get::().copied() { + record_refusal!( + crate::metrics::process_refusal_recorder(), + note, + trace_id = correlation.trace_id() + ); + } +} + pub(crate) fn method_name(method: &axum::http::Method) -> &'static str { match *method { axum::http::Method::GET => "GET", diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 21537ce20f..bf3db8a915 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -366,7 +366,8 @@ pub enum RuntimeConfigError { UnsafePackageRoot, #[error("runtime configuration contains an invalid OIDC binding")] InvalidOidc, - #[error("the static OIDC key set was refused: {0}")] + // The cause is the remedy `diagnostics` reports, so the message does not repeat it. + #[error("the static OIDC key set was refused")] InvalidStaticJwks(StaticJwksError), #[error("the OIDC leeway must be a whole number of seconds from 0 to 300000 milliseconds")] InvalidOidcLeeway, diff --git a/crates/registry-breg/src/startup.rs b/crates/registry-breg/src/startup.rs index 5abf5a734b..3c6e9cccb2 100644 --- a/crates/registry-breg/src/startup.rs +++ b/crates/registry-breg/src/startup.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Startup ordering gate for one verified Registry package. +pub use registry_platform_oidc::StaticJwksError; use std::collections::BTreeMap; use std::future::Future; use std::net::SocketAddr; @@ -150,6 +151,10 @@ pub enum StartupError { ExternalProjectionRoleMode, #[error("the Registry OIDC key source was refused")] Oidc, + /// The shared static key set rule refused the pinned key set. The cause + /// names the rule and the key's position, never a key value. + #[error("the Registry OIDC key source was refused")] + StaticKeySet(StaticJwksError), #[error("the Registry authentication profile was refused")] Authentication, /// The project names clients that `authentication.oidc.allowedClients` @@ -737,6 +742,18 @@ impl OperationalEvent { message = record.message ); } + Self::StoppedWithError(StartupError::StaticKeySet(cause)) => { + let error = record + .error + .expect("stopped-with-error records have a closed error"); + let reason = cause.to_string(); + tracing::error!( + target: "registry_breg::startup", + error, + reason = reason.as_str(), + message = record.message + ); + } Self::StoppedWithError(StartupError::DatabaseConnection(_)) => { let error = record .error @@ -870,7 +887,7 @@ impl StartupError { Self::Cursor => "the Registry cursor profile was refused", Self::ExternalSources => "the external source binding list or the external projection store was refused", Self::ExternalProjectionRoleMode => "indexed external projections require separate migration and runtime PostgreSQL roles", - Self::Oidc => "the Registry OIDC key source was refused", + Self::Oidc | Self::StaticKeySet(_) => "the Registry OIDC key source was refused", Self::Authentication => "the Registry authentication profile was refused", Self::AuthenticationClientsUnlisted => { "the project names clients that authentication.oidc.allowedClients does not list; list each client named in requesterClients, trusted actors, or consent recipients there" @@ -2288,6 +2305,7 @@ pub fn map_runtime_config_error(error: RuntimeConfigError) -> StartupError { RuntimeConfigError::InvalidAudit => StartupError::Audit, RuntimeConfigError::InvalidCursor => StartupError::Cursor, RuntimeConfigError::InvalidOidc => StartupError::Oidc, + RuntimeConfigError::InvalidStaticJwks(cause) => StartupError::StaticKeySet(cause), other => StartupError::RuntimeConfig(other), } } diff --git a/crates/registry-breg/tests/authentication_refusals.rs b/crates/registry-breg/tests/authentication_refusals.rs index a33012650a..318323b357 100644 --- a/crates/registry-breg/tests/authentication_refusals.rs +++ b/crates/registry-breg/tests/authentication_refusals.rs @@ -218,6 +218,27 @@ impl Harness { Self { app, idp } } + /// A harness whose key source cannot be reached: the issuer's key set URL + /// names a loopback port nothing listens on. + async fn key_source_outage() -> Self { + let registry = compiled(PROJECT); + let idp = MockIdp::start().await; + let unreachable = Arc::new(JwksFetcher::new_with_fetch_url_policy( + "http://127.0.0.1:9/jwks.json".to_owned(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::dev(), + )); + let authenticator = RegistryAuthenticator::new( + ®istry, + oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]), + unreachable, + AuthorityClaimConfig::new("registry_principal", None), + ) + .expect("authentication config is valid"); + let app = authenticated_router(Arc::new(service(registry)), Arc::new(authenticator)); + Self { app, idp } + } + async fn contextual() -> Self { let registry = compiled(CONTEXTUAL_PROJECT); let idp = MockIdp::start().await; @@ -502,6 +523,7 @@ async fn observe( let content_type = header("content-type"); let cache_control = header("cache-control"); let www_authenticate = header("www-authenticate"); + let retry_after = header("retry-after"); let bytes = to_bytes(response.into_body(), 1024 * 1024) .await .expect("response body"); @@ -534,6 +556,7 @@ async fn observe( "contentType": content_type, "cacheControl": cache_control, "wwwAuthenticate": www_authenticate, + "retryAfter": retry_after, "body": body, }), counted, @@ -549,9 +572,17 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir let plain = Harness::plain().await; let valid = plain.idp.mint_token(valid_claims()); + // Change a character in the middle of the signature. The last character + // of a base64url Ed25519 signature carries padding bits, so changing it + // can make the token fail to decode instead of failing the signature. let mut tampered = valid.clone(); - tampered.pop(); - tampered.push(if valid.ends_with('A') { 'B' } else { 'A' }); + let position = tampered.len() - 10; + let replacement = if &valid[position..=position] == "A" { + "B" + } else { + "A" + }; + tampered.replace_range(position..=position, replacement); let now = unix_now(); let mut wrong_audience = valid_claims(); wrong_audience["aud"] = json!("urn:example:another-resource"); @@ -568,6 +599,8 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir .remove("registry_actor_kind"); let mut object_principal = valid_claims(); object_principal["registry_principal"] = json!({"value": PRINCIPAL}); + let mut malformed_actor_kind = valid_claims(); + malformed_actor_kind["registry_actor_kind"] = json!(["service"]); let bearer = |token: &str| format!("Bearer {token}"); for (name, check, request) in [ @@ -632,6 +665,31 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir "actor-kind", read_request(&record, &[&bearer(&plain.token(no_actor_kind))]), ), + ( + "actor-kind-is-not-a-string", + "actor-kind", + read_request(&record, &[&bearer(&plain.token(malformed_actor_kind))]), + ), + ( + "token-type-is-not-admitted", + "token-type", + read_request( + &record, + &[&bearer(&sign_ed25519_compact_jwt( + fixtures::ED25519_PRIVATE_JWK, + "canary+type", + "registry-platform-testing-ed25519-1", + { + let mut claims = valid_claims(); + claims["iss"] = json!(plain.idp.issuer()); + claims["iat"] = json!(now); + claims["nbf"] = json!(now); + claims["exp"] = json!(now + 900); + claims + }, + ))], + ), + ), ( "principal-claim-is-an-object", "token-claims", @@ -666,6 +724,7 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir .as_object_mut() .expect("claims are an object") .remove("azp"); + let act_not_an_object = contextual.token(standing_agent_claims(json!("not-an-object"))); let mut long_grant = delegated_grant_claims(now); long_grant["iat"] = json!(now); long_grant["exp"] = json!(now + 901); @@ -673,12 +732,27 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir partial_grant["iat"] = json!(now); partial_grant["exp"] = json!(now + 600); partial_grant["registry_grant_bounds"] = json!("not-an-object"); + let mut expired_grant = delegated_grant_claims(now); + expired_grant["registry_grant_exp"] = json!(now - 1); + let mut other_client_grant = delegated_grant_claims(now); + other_client_grant["registry_grant_client"] = json!("other-client"); + let mut other_resource_grant = delegated_grant_claims(now); + other_resource_grant["registry_grant_resource"] = json!("urn:example:other-resource"); + let mut future_issued_grant = delegated_grant_claims(now); + future_issued_grant["iat"] = json!(now + 600); + future_issued_grant["nbf"] = json!(now); + future_issued_grant["exp"] = json!(now + 1200); for (name, check, request) in [ ( "actor-is-not-the-trusted-actor", "delegation", read_request(&agent_path, &[&bearer(&untrusted_actor)]), ), + ( + "act-claim-is-not-an-object", + "delegation", + read_request(&agent_path, &[&bearer(&act_not_an_object)]), + ), ( "actor-without-a-matched-client", "token-client", @@ -697,10 +771,51 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir "task-grant-claims", read_request(&grant_path, &[&bearer(&contextual.token(partial_grant))]), ), + ( + "task-grant-expired", + "task-grant-expired", + read_request(&grant_path, &[&bearer(&contextual.token(expired_grant))]), + ), + ( + "task-grant-bound-to-another-client", + "task-grant-binding", + read_request( + &grant_path, + &[&bearer(&contextual.token(other_client_grant))], + ), + ), + ( + "task-grant-bound-to-another-resource", + "task-grant-binding", + read_request( + &grant_path, + &[&bearer(&contextual.token(other_resource_grant))], + ), + ), + ( + "task-grant-token-issued-in-the-future", + "task-grant-claims", + read_request( + &grant_path, + &[&bearer(&contextual.token(future_issued_grant))], + ), + ), ] { observed.push(observe(name, check, &contextual.app, request).await); } + let outage = Harness::key_source_outage().await; + let outage_token = outage.token(valid_claims()); + observed.push( + observe( + "key-source-unreachable", + "key-source-unavailable", + &outage.app, + read_request(&record, &[&bearer(&outage_token)]), + ) + .await, + ); + let completions = completion_app(); for (name, check, request) in [ ( @@ -721,6 +836,11 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir request }, ), + ( + "review-completion-with-an-unparseable-bearer", + "credential-malformed", + completion_request(Some("Bearer completion-secret"), Some("registry-a")), + ), ( "review-completion-without-recipient", "credential-missing", @@ -826,4 +946,36 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir used.len() >= 14, "the cases cover every authentication check" ); + + // The shared malformed-token corpus goes through the router. The counter + // has no budget, so every token counts once under `credential-malformed`, + // whatever the log line budget admits. + let corpus = registry_platform_testing::malformed_access_token_fixtures(); + let captured = CapturedLogs::default(); + let before = refusal_counts().await; + for token in &corpus { + let response = plain + .app + .clone() + .oneshot(read_request(&record, &[&bearer(token)])) + .with_subscriber(captured.subscriber()) + .await + .expect("router responds"); + assert_eq!(response.status().as_u16(), 401); + } + let after = refusal_counts().await; + let counted = |label: &str| { + after.get(label).copied().unwrap_or(0) - before.get(label).copied().unwrap_or(0) + }; + assert_eq!( + counted("credential-malformed"), + u64::try_from(corpus.len()).expect("corpus length fits"), + "each malformed token counts once" + ); + let log_text = captured + .events() + .iter() + .map(Value::to_string) + .collect::(); + assert!(!log_text.contains("canary"), "the corpus reached the log"); } diff --git a/crates/registry-breg/tests/golden/authentication_refusals.json b/crates/registry-breg/tests/golden/authentication_refusals.json index 72591b6a59..ea4c422cd4 100644 --- a/crates/registry-breg/tests/golden/authentication_refusals.json +++ b/crates/registry-breg/tests/golden/authentication_refusals.json @@ -1,4 +1,18 @@ { + "act-claim-is-not-an-object": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, "actor-is-not-the-trusted-actor": { "body": { "code": "authentication.refused", @@ -9,6 +23,21 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "actor-kind-is-not-a-string": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -22,6 +51,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -35,6 +65,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -48,6 +79,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -61,6 +93,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -74,6 +107,21 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "key-source-unreachable": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -87,6 +135,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -100,6 +149,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -113,6 +163,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -126,6 +177,21 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "review-completion-with-an-unparseable-bearer": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -139,6 +205,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -152,6 +219,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -165,6 +233,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -178,6 +247,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -191,6 +261,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -204,6 +275,35 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-bound-to-another-client": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-bound-to-another-resource": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -217,6 +317,21 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-expired": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -230,6 +345,21 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-token-issued-in-the-future": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -243,6 +373,21 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "token-type-is-not-admitted": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing or refused.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -256,6 +401,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -269,6 +415,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null }, @@ -282,6 +429,7 @@ }, "cacheControl": "no-store", "contentType": "application/problem+json", + "retryAfter": null, "status": 401, "wwwAuthenticate": null } diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index 563e270002..baac93a793 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -72,7 +72,8 @@ async fn compact_token_admission_refuses_malformed_credentials_and_writes_no_lin } } // The counted refusal and its one bounded line belong to the request - // boundary, which `tests/authentication_refusals.rs` drives. + // boundary, which `tests/authentication_refusals.rs` drives with this + // same corpus. assert_eq!(captured.text(), "", "admission writes no line of its own"); } diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index a9a0b159ad..18868d63c6 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -70,6 +70,32 @@ async fn application_queue_age(fixture: &client_http::ClientFixture) -> f64 { .parse() .unwrap() } +/// The refusal counter, read the way an operator reads it: from the metrics +/// listener. The recorder is process-wide, so a test that shares its process +/// with others asserts a rise of at least what it caused. +async fn refusal_count(check: &str) -> u64 { + use tower::util::ServiceExt; + let response = registry_breg::metrics::metrics_app(std::sync::Arc::new( + registry_breg::metrics::Metrics::without_pool_for_test(), + )) + .oneshot( + axum::http::Request::builder() + .uri("/metrics") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let bytes = axum::body::to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .unwrap(); + let prefix = format!("breg_request_refusals_total{{check=\"{check}\"}} "); + std::str::from_utf8(&bytes) + .unwrap() + .lines() + .find_map(|line| line.strip_prefix(prefix.as_str())) + .map_or(0, |value| value.parse().unwrap()) +} fn registry_source(automatic: bool) -> Value { let source = json!({"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", "project":{"id":"proposal-test","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://proposal.example.test"}, @@ -6373,6 +6399,33 @@ async fn review_context_projects_an_omitted_optional_input_as_null() { batch["items"][1], json!({"id": missing, "status":"concealed"}) ); + // Each concealed item counts once under its own check, though the batch + // answers 200. Other tests share the recorder, so the rise is a lower + // bound that one note per response could not reach. + let before = refusal_count("visibility").await; + let unknown = (0..3) + .map(|_| uuid::Uuid::new_v4().to_string()) + .collect::>(); + let response = reqwest::Client::new() + .get(format!( + "{}/v1/proposals/review-context", + fixture.http.base_url + )) + .query(&[("accessProfile", "clerk"), ("ids", &unknown.join(","))]) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::OK); + let batch: Value = response.json().await.unwrap(); + assert!(batch["items"] + .as_array() + .unwrap() + .iter() + .all(|item| item["status"] == "concealed")); + assert!( + refusal_count("visibility").await - before >= 3, + "each concealed batch item counts under visibility" + ); let before = fixture.audit_capture.entries().len(); let excessive = (0..101) .map(|_| uuid::Uuid::new_v4().to_string()) diff --git a/crates/registry-breg/tests/runtime_config.rs b/crates/registry-breg/tests/runtime_config.rs index 71723b30fe..e0dde018f3 100644 --- a/crates/registry-breg/tests/runtime_config.rs +++ b/crates/registry-breg/tests/runtime_config.rs @@ -3567,6 +3567,23 @@ async fn a_private_member_in_a_static_key_set_is_named_in_the_startup_refusal() assert!(rendered.contains("/authentication/oidc"), "{rendered}"); assert!(rendered.contains("private-key member \"d\""), "{rendered}"); assert!(!rendered.contains("private-canary"), "{rendered}"); + assert_eq!( + rendered.matches("private-key member").count(), + 1, + "the cause appears once: {rendered}" + ); + + // The startup surfaces keep the key-source class and carry the rule. + let startup = registry_breg::startup::map_runtime_config_error(error); + let registry_breg::startup::StartupError::StaticKeySet(cause) = &startup else { + panic!("a refused static key set is a key-source startup refusal: {startup:?}"); + }; + assert!(cause.to_string().contains("private-key member \"d\"")); + let record = registry_breg::startup::OperationalEvent::StoppedWithError(startup).record(); + assert_eq!( + record.error(), + Some("the Registry OIDC key source was refused") + ); } #[tokio::test] diff --git a/crates/registry-breg/tests/startup_http.rs b/crates/registry-breg/tests/startup_http.rs index ca3ed08f9e..0a265994cf 100644 --- a/crates/registry-breg/tests/startup_http.rs +++ b/crates/registry-breg/tests/startup_http.rs @@ -35,7 +35,9 @@ use registry_breg::startup::{ }; use registry_breg::{compile_project, parse_project_yaml, CompileProfile, CompiledRegistry}; use registry_platform_crypto::PrivateJwk; -use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifierConfig}; +use registry_platform_oidc::{ + JwksFetcher, JwksFetcherConfig, StaticJwksError, TokenVerifierConfig, +}; use registry_platform_testing::{fixtures, jwks_from_private_jwk, sign_ed25519_compact_jwt}; use serde_json::{json, Value}; use tower::ServiceExt as _; @@ -507,7 +509,7 @@ async fn request_operational_log_has_only_closed_value_free_fields() { /// A description the audit writer gives for a torn audit file. const AUDIT_DESTINATION_REASON: &str = "the audit file could not be opened: audit file has an incomplete final entry; archive it and restart with a fresh path"; -fn startup_errors() -> [StartupError; 40] { +fn startup_errors() -> [StartupError; 41] { [ // The wrapped cause never changes the rendered operational message: it // only lets `bregctl doctor` name it. Any `RuntimeConfigError` variant @@ -553,6 +555,10 @@ fn startup_errors() -> [StartupError; 40] { StartupError::ExternalSources, StartupError::ExternalProjectionRoleMode, StartupError::Oidc, + StartupError::StaticKeySet(StaticJwksError::PrivateKeyMember { + key: 0, + member: "d", + }), StartupError::Authentication, StartupError::AuthenticationClientsUnlisted, StartupError::EventDestinations, @@ -833,7 +839,9 @@ fn expected_startup_error(error: StartupError) -> &'static str { StartupError::ExternalProjectionRoleMode => { "indexed external projections require separate migration and runtime PostgreSQL roles" } - StartupError::Oidc => "the Registry OIDC key source was refused", + StartupError::Oidc | StartupError::StaticKeySet(_) => { + "the Registry OIDC key source was refused" + } StartupError::Authentication => "the Registry authentication profile was refused", StartupError::AuthenticationClientsUnlisted => { "the project names clients that authentication.oidc.allowedClients does not list; list each client named in requesterClients, trusted actors, or consent recipients there" @@ -1054,6 +1062,14 @@ async fn every_operational_event_renders_exact_closed_value_free_json_fields() { OperationalEvent::StoppedWithError(StartupError::AuditDestination(reason)) => { Some(reason.clone()) } + OperationalEvent::StoppedWithError(StartupError::StaticKeySet(cause)) => { + let reason = cause.to_string(); + assert!( + reason.contains("private-key member \"d\""), + "the reason names the rule: {reason}" + ); + Some(reason) + } _ => None, }; let (level, target, message, error, code) = expected_operational_event(event); diff --git a/crates/registry-bregctl/src/doctor.rs b/crates/registry-bregctl/src/doctor.rs index b9e5933b86..dcf42d1c59 100644 --- a/crates/registry-bregctl/src/doctor.rs +++ b/crates/registry-bregctl/src/doctor.rs @@ -246,6 +246,15 @@ fn startup_diagnostic(error: StartupError) -> Diagnostic { if let StartupError::PackageEnvelopeRefused(cause) = error { return diagnostic("startup.package.refused", "package", &cause); } + // The shared key set rule names the rule and the key's position, never a + // key value. + if let StartupError::StaticKeySet(cause) = error { + return diagnostic( + "startup.oidc.refused", + "authentication.oidc", + &format!("the OIDC key set was refused: {cause}"), + ); + } // The writer's own refusal names the rule and the recovery step, and // never a path or a secret. if let StartupError::AuditDestination(reason) = error { @@ -261,6 +270,7 @@ fn startup_diagnostic(error: StartupError) -> Diagnostic { } StartupError::PackageRefused(_) | StartupError::PackageEnvelopeRefused(_) + | StartupError::StaticKeySet(_) | StartupError::AuditDestination(_) => { unreachable!("handled above") } @@ -1030,6 +1040,25 @@ mod tests { .all(|diagnostic| diagnostic.message.contains("; next: "))); } + #[test] + fn a_refused_static_key_set_keeps_the_key_source_code_and_names_the_rule() { + let diagnostic = startup_diagnostic(StartupError::StaticKeySet( + registry_breg::startup::StaticJwksError::PrivateKeyMember { + key: 0, + member: "d", + }, + )); + assert_eq!(diagnostic.code, "startup.oidc.refused"); + assert_eq!(diagnostic.path, "authentication.oidc"); + assert!( + diagnostic + .message + .contains("key 0 carries the private-key member \"d\""), + "{}", + diagnostic.message + ); + } + #[test] fn authentication_dependency_refusals_name_the_causes_an_operator_checks() { let key_source = startup_diagnostic(StartupError::Oidc); diff --git a/crates/registry-casework/src/assignment.rs b/crates/registry-casework/src/assignment.rs index a4ca903ea2..37ec0319ba 100644 --- a/crates/registry-casework/src/assignment.rs +++ b/crates/registry-casework/src/assignment.rs @@ -573,7 +573,7 @@ impl PostgresStore { &[&id], ) .await? - .ok_or(StoreError::NotFound)?; + .ok_or(StoreError::Absent)?; let record = absence_from_row(row)?; if record.person != input.person { return Err(StoreError::Invalid); @@ -619,7 +619,7 @@ impl PostgresStore { if absence_id.is_some() { let changed=transaction.execute("UPDATE casework_absences SET person_issuer=$2,person_subject=$3,starts_at=$4,ends_at=$5,cover_issuer=$6,cover_subject=$7,revision=$8 WHERE absence_id=$1",&[&id,&input.person.issuer,&input.person.subject,&input.from,&input.until,&input.cover.issuer,&input.cover.subject,&next]).await?; if changed != 1 { - return Err(StoreError::NotFound); + return Err(StoreError::Absent); } } else { transaction.execute("INSERT INTO casework_absences(absence_id,person_issuer,person_subject,starts_at,ends_at,cover_issuer,cover_subject,revision) VALUES($1,$2,$3,$4,$5,$6,$7,$8)",&[&id,&input.person.issuer,&input.person.subject,&input.from,&input.until,&input.cover.issuer,&input.cover.subject,&next]).await?; @@ -714,7 +714,7 @@ impl PostgresStore { if actual != expected_directory_revision { return Err(StoreError::Conflict); } - let row=transaction.query_opt("SELECT absence_id,person_issuer,person_subject,starts_at,ends_at,cover_issuer,cover_subject,revision FROM casework_absences WHERE absence_id=$1 FOR UPDATE",&[&absence_id]).await?.ok_or(StoreError::NotFound)?; + let row=transaction.query_opt("SELECT absence_id,person_issuer,person_subject,starts_at,ends_at,cover_issuer,cover_subject,revision FROM casework_absences WHERE absence_id=$1 FOR UPDATE",&[&absence_id]).await?.ok_or(StoreError::Absent)?; let record = absence_from_row(row)?; if !can_manage_person(&transaction, actor, &record.person).await? { return Err(StoreError::Forbidden(FailedCheck::Operation)); diff --git a/crates/registry-casework/src/clocks.rs b/crates/registry-casework/src/clocks.rs index 02cb6f7e21..c36a22dbed 100644 --- a/crates/registry-casework/src/clocks.rs +++ b/crates/registry-casework/src/clocks.rs @@ -123,7 +123,7 @@ impl PostgresStore { &[&holiday_set, &revision], ) .await? - .ok_or(StoreError::NotFound)?; + .ok_or(StoreError::Absent)?; serde_json::from_value(row.get(0)).map_err(StoreError::Json) } } diff --git a/crates/registry-casework/src/config.rs b/crates/registry-casework/src/config.rs index b2efe6488d..16bbb92740 100644 --- a/crates/registry-casework/src/config.rs +++ b/crates/registry-casework/src/config.rs @@ -1397,7 +1397,7 @@ impl RuntimeConfig { findings.push(RuntimeConfigError::InvalidReviewCompletionDestination { path: segments.join("."), pointer: pointer_to(&segments), - reason: "must be an https URL with a host, or an http URL on 127.0.0.1 or [::1], without userinfo, query, or fragment", + reason: "must be an https URL with a host, or an http URL on a loopback literal (127.0.0.0/8, ::1 or ::ffff:127.0.0.0/104), without userinfo, query, or fragment", }); } } @@ -3529,7 +3529,7 @@ impl RuntimeConfigError { "Configure exactly one of bearerTokenRef and auth.secretRef, and name in auth.header only a header the runtime does not reserve." } Self::InvalidReviewCompletionDestination { .. } => { - "Give the destination a non-empty id and an https URL with a host, or an http URL on 127.0.0.1 or [::1] for local development." + "Give the destination a non-empty id and an https URL with a host, or an http URL on a loopback literal (127.0.0.0/8, ::1 or ::ffff:127.0.0.0/104) for local development." } Self::UnconfiguredReviewCompletionDestination => { "Add a reviewCompletionDestinations entry for each destination casework.yaml trustedProducers.PRODUCER_ID.completion.destinationId names." diff --git a/crates/registry-casework/src/http.rs b/crates/registry-casework/src/http.rs index 3de5a34dda..a6189d2f84 100644 --- a/crates/registry-casework/src/http.rs +++ b/crates/registry-casework/src/http.rs @@ -1700,6 +1700,9 @@ pub enum HttpError { /// A target that is absent or that the caller may not see, answered /// alike. NotFound(FailedCheck), + /// An absence that conceals nothing. It answers like `NotFound` and is + /// not recorded as a refusal. + Absent, PreconditionFailed, PreconditionRequired, IdempotencyKeyReused, @@ -1726,9 +1729,9 @@ pub enum HttpError { Internal, Validation(ReviewValidationError), } -// A refused operation carries the check its producer named. An absent or -// concealed target is recorded as `visibility`, unless the producer named the -// check that hid it. +// A refused operation carries the check its producer named. A concealed +// target is recorded as `visibility`, unless the producer named the check that +// hid it. An absence that conceals nothing records no check. impl From for HttpError { fn from(e: StoreError) -> Self { match e { @@ -1737,6 +1740,7 @@ impl From for HttpError { StoreError::CursorInvalid => Self::CursorInvalid, StoreError::IdempotencyExpired => Self::IdempotencyExpired, StoreError::NotFound => Self::NotFound(FailedCheck::Visibility), + StoreError::Absent => Self::Absent, StoreError::Forbidden(check) => Self::Forbidden(check), StoreError::Conflict => Self::PreconditionFailed, StoreError::AlreadyClaimed | StoreError::NotHolder => Self::ReviewTaskNotHeld, @@ -1757,6 +1761,7 @@ impl From for HttpError { match e { ServiceError::Store(e) => e.into(), ServiceError::NotFound(check) => Self::NotFound(check), + ServiceError::Absent => Self::Absent, ServiceError::Forbidden(check) => Self::Forbidden(check), ServiceError::ReviewValidation(e) => Self::Validation(e), ServiceError::Configuration => Self::Internal, @@ -1843,7 +1848,8 @@ impl HttpError { Self::ReviewDistinctApproverRequired | Self::ReviewInitiatorExcluded => { Some(FailedCheck::SeparationOfDuties) } - Self::PreconditionFailed + Self::Absent + | Self::PreconditionFailed | Self::PreconditionRequired | Self::IdempotencyKeyReused | Self::IdempotencyExpired @@ -1883,7 +1889,6 @@ impl HttpError { | FailedCheck::TaskGrantClaims | FailedCheck::TokenAudience | FailedCheck::TokenClaims - | FailedCheck::TokenTime | FailedCheck::Delegation | FailedCheck::Scope | FailedCheck::ActorKind @@ -1907,7 +1912,7 @@ impl HttpError { } }, Self::Forbidden(_) => ProblemCode::OperationNotAuthorized, - Self::NotFound(_) => ProblemCode::RequestNotFound, + Self::NotFound(_) | Self::Absent => ProblemCode::RequestNotFound, Self::PreconditionFailed => ProblemCode::PreconditionFailed, Self::PreconditionRequired => ProblemCode::PreconditionRequired, Self::IdempotencyKeyReused => ProblemCode::IdempotencyKeyReused, @@ -2853,6 +2858,7 @@ mod tests { answer(|| HttpError::ReviewDistinctApproverRequired), ) .route("/excluded", answer(|| HttpError::ReviewInitiatorExcluded)) + .route("/absent", answer(|| HttpError::Absent)) .route("/invalid", answer(|| HttpError::Invalid)) .route("/outage", answer(|| HttpError::ServiceUnavailable)), None, @@ -2907,6 +2913,12 @@ mod tests { Some(check) ); } + assert_eq!(HttpError::from(StoreError::Absent).failed_check(), None); + assert_eq!(HttpError::from(ServiceError::Absent).failed_check(), None); + assert_eq!( + HttpError::from(StoreError::NotFound).failed_check(), + Some(FailedCheck::Visibility) + ); assert_eq!( HttpError::from(ReviewRuntimeError::NotHeldByReader).failed_check(), Some(FailedCheck::Ownership) @@ -2974,6 +2986,7 @@ mod tests { StatusCode::SERVICE_UNAVAILABLE ); assert_eq!(refused(&app, "/unrouted").await, StatusCode::NOT_FOUND); + assert_eq!(refused(&app, "/absent").await, StatusCode::NOT_FOUND); let counted: u64 = FailedCheck::ALL .iter() .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) @@ -2981,6 +2994,60 @@ mod tests { assert_eq!(counted, 0); } + /// Every answer that refuses a caller's credential or authority carries a + /// check, so the operator's counter sees it. A variant that answers 401 or + /// 403 and names no check fails here. + #[test] + fn every_unauthorized_or_forbidden_answer_names_a_check() { + use registry_casework_core::AbsenceError; + let check = FailedCheck::Operation; + let answers = [ + HttpError::AuthenticationRefused(check), + HttpError::ProfileNotAuthorized(check), + HttpError::ProfileNotHuman(check), + HttpError::DelegatedStaff(AuthenticationError::Refused(check)), + HttpError::DelegatedStaff(AuthenticationError::Claims(check)), + HttpError::DelegatedStaff(AuthenticationError::Profile(check)), + HttpError::DelegatedStaff(AuthenticationError::NotHuman(check)), + HttpError::Forbidden(check), + HttpError::NotFound(check), + HttpError::Absent, + HttpError::PreconditionFailed, + HttpError::PreconditionRequired, + HttpError::IdempotencyKeyReused, + HttpError::IdempotencyExpired, + HttpError::Invalid, + HttpError::LimitOutOfRange, + HttpError::ServiceUnavailable, + HttpError::SourceProfileNotApplicable, + HttpError::SourceProfileRequired, + HttpError::SourceBadGateway, + HttpError::SourceVersionMismatch, + HttpError::SourceVersionUnavailable, + HttpError::ReviewDistinctApproverRequired, + HttpError::ReviewInitiatorExcluded, + HttpError::ReviewInitiatorRequired, + HttpError::ReviewResultExpired, + HttpError::ReviewSubmissionConflict, + HttpError::ReviewTaskNotHeld, + HttpError::ReviewPolicyMismatch, + HttpError::ReviewQueryTooBroad, + HttpError::CursorInvalid, + HttpError::CursorExpired, + HttpError::Absence(AbsenceError::SelfCover), + HttpError::Internal, + ]; + for answer in answers { + let status = answer.problem().status(); + if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN { + assert!( + answer.failed_check().is_some(), + "{answer:?} answers {status} and names no check" + ); + } + } + } + #[tokio::test] async fn a_refusal_logs_one_value_free_line_with_its_check_remedy_and_trace() { use registry_platform_testing::CapturedDiagnosticLogs; diff --git a/crates/registry-casework/src/http/source_credentials.rs b/crates/registry-casework/src/http/source_credentials.rs index f6613f56fd..a94277ff8b 100644 --- a/crates/registry-casework/src/http/source_credentials.rs +++ b/crates/registry-casework/src/http/source_credentials.rs @@ -129,10 +129,12 @@ fn conceal_target_error(target: Target, error: HttpError) -> HttpError { (Target::Task(_) | Target::Request(_), HttpError::NotFound(check)) => { HttpError::NotFound(check) } - ( - Target::Task(_) | Target::Request(_), - HttpError::AuthenticationRefused(_) | HttpError::SourceProfileNotApplicable, - ) => HttpError::NotFound(FailedCheck::Visibility), + (Target::Task(_) | Target::Request(_), HttpError::AuthenticationRefused(check)) => { + HttpError::NotFound(check) + } + (Target::Task(_) | Target::Request(_), HttpError::SourceProfileNotApplicable) => { + HttpError::NotFound(FailedCheck::Visibility) + } (_, error) => error, } } diff --git a/crates/registry-casework/src/service.rs b/crates/registry-casework/src/service.rs index 5bda92e684..6ea716557e 100644 --- a/crates/registry-casework/src/service.rs +++ b/crates/registry-casework/src/service.rs @@ -78,6 +78,9 @@ pub enum ServiceError { Configuration, #[error("the requested review task was not found")] NotFound(FailedCheck), + /// An absence that conceals nothing and is not counted as a refusal. + #[error("the requested resource was not found")] + Absent, #[error("the caller is not authorized")] Forbidden(FailedCheck), #[error(transparent)] diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index a52d472c11..9c8ea30b0e 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -756,6 +756,10 @@ pub enum StoreError { AuditUnavailable, #[error("the requested resource was not found")] NotFound, + /// A record the caller named is absent and the answer conceals nothing, + /// so it is not a refusal the operator counts. + #[error("the requested resource was not found")] + Absent, #[error("the caller is not authorized for this operation")] Forbidden(FailedCheck), #[error("the expected revision is no longer current")] diff --git a/crates/registry-casework/src/task_grants.rs b/crates/registry-casework/src/task_grants.rs index f1d5eaa3fc..b4fa83a2a6 100644 --- a/crates/registry-casework/src/task_grants.rs +++ b/crates/registry-casework/src/task_grants.rs @@ -595,8 +595,10 @@ impl PostgresStore { let Some(kind) = membership_kind(actor.role) else { return Err(StoreError::Forbidden(FailedCheck::Operation)); }; - if !template_active(&transaction, &grant.template).await? - || !grant.template.eligible_profiles.contains(&actor.profile_id) + if !template_active(&transaction, &grant.template).await? { + return Err(StoreError::Forbidden(FailedCheck::Operation)); + } + if !grant.template.eligible_profiles.contains(&actor.profile_id) || !transaction .query_one( "SELECT EXISTS( @@ -853,7 +855,7 @@ impl crate::CaseworkService { pub(crate) fn task_jwks(&self) -> Result { self.task_authority .as_ref() - .ok_or(crate::ServiceError::NotFound(FailedCheck::Visibility))? + .ok_or(crate::ServiceError::Absent)? .jwks() .map_err(Into::into) } diff --git a/crates/registry-casework/src/task_grants/http_tests.rs b/crates/registry-casework/src/task_grants/http_tests.rs index bace8c3ab7..acc799d00d 100644 --- a/crates/registry-casework/src/task_grants/http_tests.rs +++ b/crates/registry-casework/src/task_grants/http_tests.rs @@ -1093,6 +1093,71 @@ async fn eligible_officer_can_revoke_without_holding_the_task_or_reading_the_sou .unwrap(); } +#[tokio::test] +async fn a_revoke_refusal_names_the_template_or_the_profile_that_refused_it() { + let f = fixture(900).await; + let holder = token("human", "human-client", "human", "casework:staff"); + let base = format!("/v1/review-tasks/{}/task-grants", f.review_task); + let (status, grant) = request( + &f, + "POST", + &base, + &holder, + true, + Some(json!({"templateId":"summary","templateVersion":"1"})), + Some("approval-for-refused-revocation"), + ) + .await; + assert_eq!(status, StatusCode::OK, "{grant}"); + let grant_id = Uuid::parse_str(grant["id"].as_str().unwrap()).unwrap(); + let actor = |subject: &str| ActorContext { + principal: IssuerPrincipal { + issuer: ISSUER.into(), + subject: subject.into(), + }, + profile_id: "staff".into(), + role: CaseworkActsAs::Staff, + }; + let db = f.store.client().await.unwrap(); + db.execute( + "INSERT INTO casework_memberships(team_id,issuer,subject,membership_kind) VALUES('team',$1,'revoker','staff')", + &[&ISSUER], + ) + .await + .unwrap(); + db.execute( + "UPDATE casework_meta SET directory_revision=directory_revision+1", + &[], + ) + .await + .unwrap(); + assert!( + matches!( + f.store + .invalidate_review_task_grant(grant_id, "revoked", Some(&actor("outsider"))) + .await, + Err(StoreError::Forbidden(FailedCheck::AccessProfile)) + ), + "a caller outside the eligible team is refused under access-profile" + ); + db.execute("UPDATE casework_task_templates SET active=false", &[]) + .await + .unwrap(); + assert!( + matches!( + f.store + .invalidate_review_task_grant(grant_id, "revoked", Some(&actor("revoker"))) + .await, + Err(StoreError::Forbidden(FailedCheck::Operation)) + ), + "an inactive template is refused under operation" + ); + f.admin + .batch_execute(&format!("DROP SCHEMA {} CASCADE", f.schema)) + .await + .unwrap(); +} + #[tokio::test] async fn review_task_grants_bind_holder_revision_subject_and_revocation() { let f = fixture(900).await; @@ -1848,7 +1913,7 @@ async fn review_task_grant_approval_recovers_a_lost_response_after_the_task_revi f.store .approve_review_task_grant(&actor, "lost-response", grant) .await, - Err(StoreError::Forbidden(_)) + Err(StoreError::Forbidden(FailedCheck::AccessProfile)) )); f.admin diff --git a/crates/registry-casework/src/task_grants/lock_order_tests.rs b/crates/registry-casework/src/task_grants/lock_order_tests.rs index ac11aa9904..84ab0abb8a 100644 --- a/crates/registry-casework/src/task_grants/lock_order_tests.rs +++ b/crates/registry-casework/src/task_grants/lock_order_tests.rs @@ -303,7 +303,10 @@ async fn grant_approval_and_decision_lock_request_before_task_without_deadlock() ); assert_eq!(decision_status, StatusCode::NO_CONTENT); assert!( - matches!(approval_result, Err(StoreError::Forbidden(_))), + matches!( + approval_result, + Err(StoreError::Forbidden(FailedCheck::AccessProfile)) + ), "the queued approval must recheck and refuse the terminal task" ); } diff --git a/crates/registry-casework/tests/refusal_golden.rs b/crates/registry-casework/tests/refusal_golden.rs index 03ed463da0..3194762413 100644 --- a/crates/registry-casework/tests/refusal_golden.rs +++ b/crates/registry-casework/tests/refusal_golden.rs @@ -486,9 +486,6 @@ fn golden_path() -> PathBuf { #[tokio::test] async fn authentication_and_profile_refusals_match_the_checked_in_answers() { let idp = MockIdp::start().await; - let root = tempfile::tempdir().expect("temporary directory"); - let recorder = Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")); - let app = app(&idp, root.path(), Arc::clone(&recorder)); let mut observed = Vec::new(); let cases = cases(&idp); let tokens: Vec = cases @@ -496,26 +493,31 @@ async fn authentication_and_profile_refusals_match_the_checked_in_answers() { .flat_map(|case| case.headers.iter().map(|(_, value)| value.clone())) .collect(); for case in &cases { - let before = recorder - .counter() - .get(&[case.check]) - .expect("the check is declared"); + // A recorder per case keeps each log line inside its check's budget + // of five lines a minute, however many cases share a check. + let root = tempfile::tempdir().expect("temporary directory"); + let recorder = Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")); + let app = app(&idp, root.path(), Arc::clone(&recorder)); let logs = CapturedDiagnosticLogs::default(); observed.push(observe(&app, case).with_subscriber(logs.subscriber()).await); assert_eq!( recorder.counter().get(&[case.check]), - Some(before + 1), + Some(1), "{} counts once under {}", case.name, case.check ); + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, 1, "{} counts under no other check", case.name); assert_one_value_free_line(case, &logs, &tokens); } - let counted: u64 = FailedCheck::ALL - .iter() - .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) - .sum(); - assert_eq!(counted, cases.len() as u64, "no refusal counted twice"); + let root = tempfile::tempdir().expect("temporary directory"); + let recorder = Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")); + let app = app(&idp, root.path(), Arc::clone(&recorder)); + assert_absence_is_not_counted(&app, &recorder).await; idp.stop().await; let observed = Value::Array(observed); let rendered = format!("{}\n", serde_json::to_string_pretty(&observed).unwrap()); @@ -532,6 +534,33 @@ async fn authentication_and_profile_refusals_match_the_checked_in_answers() { ); } +/// A plain absence conceals nothing, so it is neither counted nor logged as a +/// refusal. The task grant key set route is unauthenticated and answers 404 +/// when task grants are not configured. +async fn assert_absence_is_not_counted(app: &axum::Router, recorder: &RefusalRecorder) { + let logs = CapturedDiagnosticLogs::default(); + let observed = observe( + app, + &case( + "jwks-without-task-grants", + "visibility", + "GET", + "/.well-known/jwks.json", + vec![], + ), + ) + .with_subscriber(logs.subscriber()) + .await; + assert_eq!(observed["status"], 404); + assert_eq!(observed["body"]["code"], "request.not-found"); + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, 0, "an absence records no refusal"); + assert_eq!(logs.text(), "", "an absence writes no refusal line"); +} + /// The one line a refusal wrote names the check, carries a trace id, and /// holds no credential, claim or profile a caller sent. fn assert_one_value_free_line(case: &Case, logs: &CapturedDiagnosticLogs, tokens: &[String]) { diff --git a/crates/registry-casework/tests/review_acceptance_postgres.rs b/crates/registry-casework/tests/review_acceptance_postgres.rs index 6a79fc3ec6..3e9e03b638 100644 --- a/crates/registry-casework/tests/review_acceptance_postgres.rs +++ b/crates/registry-casework/tests/review_acceptance_postgres.rs @@ -4,6 +4,7 @@ use async_trait::async_trait; use chrono::{TimeDelta, Utc}; use registry_casework::*; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::{SecretProvider, SecretResolver}; use serde_json::{json, Value}; use std::{ @@ -348,7 +349,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { "reviewer-create" ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let accepted = f.create("notice").await; assert!(f.request("notice").policy.matches(&accepted.policy)); @@ -370,7 +371,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { accepted.request_id ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)) )); assert!(matches!( f.service @@ -383,7 +384,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { "producer-claim" ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); } #[tokio::test] @@ -520,7 +521,7 @@ async fn current_policy_selection_recovers_before_updates_and_requires_live_auth revoked .create_review_request(&producer, request, "current-policy") .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)) )); assert_eq!( f.db.query_one("SELECT count(*) FROM casework_review_requests", &[]) @@ -582,7 +583,7 @@ async fn concurrent_current_policy_acceptance_freezes_one_binding_and_refuses_in f.service .create_review_request(&producer, wrong_subject, "incompatible-subject") .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); } @@ -632,7 +633,9 @@ async fn submitted_two_stage_review_pins_policy_receipts_and_terminal_feed() { "same-reviewer" ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) )); let held = f.claim(second, "b").await; f.service @@ -1204,7 +1207,7 @@ async fn source_visibility_and_directory_authority_are_both_live_at_caseload_app } ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(before, f.holders().await); } @@ -1471,7 +1474,7 @@ async fn admission_namespace_cannot_substitute_the_pinned_provider_namespace() { "wrong-namespace" ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!( f.db.query_one("SELECT count(*) FROM casework_review_requests", &[]) @@ -1655,7 +1658,7 @@ async fn clock_recompute_uses_pinned_calendar_and_fences_changed_holiday_inputs( } ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); } diff --git a/crates/registry-casework/tests/review_directory_postgres.rs b/crates/registry-casework/tests/review_directory_postgres.rs index 203eab3d5c..84dcdb184a 100644 --- a/crates/registry-casework/tests/review_directory_postgres.rs +++ b/crates/registry-casework/tests/review_directory_postgres.rs @@ -2,6 +2,7 @@ use chrono::{TimeDelta, Utc}; use registry_casework::{CaseworkService, DatabaseConfig, PostgresStore, ServiceError, StoreError}; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::{SecretProvider, SecretResolver}; use serde_json::json; use std::{collections::BTreeSet, env}; @@ -527,7 +528,9 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden(_))) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); let bulk_a = (0..100) @@ -553,7 +556,9 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden(_))) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); let staff_absence_people = fixture .service @@ -583,7 +588,9 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden(_))) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); let revision = fixture .service @@ -743,7 +750,9 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden(_))) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); let unrelated_supervisor = actor("unrelated", CaseworkActsAs::Supervisor, "supervisor"); let empty = fixture @@ -1006,7 +1015,9 @@ async fn supervisor_cannot_record_cover_from_an_unsupervised_shared_team() { "unsupervised-shared-cover", ) .await, - Err(ServiceError::Store(StoreError::Forbidden(_))) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); } @@ -1166,7 +1177,9 @@ async fn absence_update_preserves_owner_and_delete_replay_rechecks_current_autho "delete-own-absence", ) .await, - Err(ServiceError::Store(StoreError::Forbidden(_))) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); } diff --git a/crates/registry-casework/tests/review_postgres.rs b/crates/registry-casework/tests/review_postgres.rs index a337636b75..eb0c242bbc 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -19,6 +19,7 @@ use registry_casework::{ ReviewRuntimeError, ReviewTaskDecisionRequest, RuntimeError, StoreError, }; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::{SecretProvider, SecretResolver}; use serde_json::json; use sha2::{Digest, Sha256}; @@ -1995,7 +1996,7 @@ async fn recovery_pins_policy_and_terminal_settlement_emits_atomically() { .service_v1 .review_accountability(&fixture.reviewer_b, accountability_event) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let result = fixture @@ -4325,7 +4326,7 @@ async fn accountability_receipts_pin_selected_outcomes_through_independent_reten service .review_accountability(&fixture.reviewer_b, *event) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let outsider = actor("outside-team", CaseworkActsAs::Supervisor, "supervisor"); assert!(matches!( @@ -4692,7 +4693,7 @@ async fn own_decisions_filter_authors_scope_and_continue_past_hidden_source_cand source .own_review_decisions(&fixture.producer, None, "", None, None, 1) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert!(matches!( source @@ -4705,7 +4706,7 @@ async fn own_decisions_filter_authors_scope_and_continue_past_hidden_source_cand 1 ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let wrong_profile = actor("reviewer-a", CaseworkActsAs::Staff, "not-pinned"); assert!(source @@ -7187,7 +7188,9 @@ async fn prior_stage_identity_and_invalid_structured_result_emit_nothing() { "claim-excluded-secondary", ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) )); assert_eq!( count_for_request( @@ -7419,7 +7422,7 @@ async fn claim_and_decide_require_current_exact_queue_membership() { "nonmember-claim", ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let assigned = fixture @@ -7484,7 +7487,7 @@ async fn claim_and_decide_require_current_exact_queue_membership() { "removed-holder-decision", ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!( count_for_request( @@ -7547,7 +7550,7 @@ async fn delegation_requires_the_selected_profile_in_pinned_deciding_profiles() "delegate-ineligible-profile", ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let unchanged = fixture .service_v1 @@ -7674,7 +7677,7 @@ async fn delegation_requires_membership_matching_the_selected_role_in_a_mixed_st "delegate-cross-role-membership", ) .await, - Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); let persisted = fixture .database @@ -7755,7 +7758,7 @@ async fn delegation_requires_membership_matching_the_selected_role_in_a_mixed_st "delegate-exact-role-membership", ) .await, - Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; assert_eq!( @@ -7816,7 +7819,7 @@ async fn assignment_requires_a_selected_supervisor_profile_despite_directory_mem "assign-staff-scoped-supervisor", ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let unchanged = fixture .service_v1 @@ -7875,7 +7878,7 @@ async fn assignment_requires_a_selected_supervisor_profile_despite_directory_mem "assign-supervisor-scoped", ) .await, - Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.supervisor, "supervisor", true).await; assert_eq!( @@ -7954,7 +7957,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "claim-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, project("1")); @@ -8042,7 +8045,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "release-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, project("1")); @@ -8166,7 +8169,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "decide-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, answer_project(false)); @@ -11516,7 +11519,9 @@ async fn review_task_coordination_preserves_exclusions_drafts_history_and_absenc "assign-initiator", ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) )); let assigned = fixture .service_v1 @@ -11557,7 +11562,9 @@ async fn review_task_coordination_preserves_exclusions_drafts_history_and_absenc "delegate-initiator", ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) )); let delegated = fixture .service_v1 @@ -12019,7 +12026,7 @@ async fn staffing_diagnostic_is_disclosed_and_clears_when_responsibility_resumes 100 ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); // A diagnostic adds no authority. Concealed work matches unknown work for diff --git a/crates/registry-casework/tests/support/authority_closure_regressions.rs b/crates/registry-casework/tests/support/authority_closure_regressions.rs index 5565751833..4e389402a7 100644 --- a/crates/registry-casework/tests/support/authority_closure_regressions.rs +++ b/crates/registry-casework/tests/support/authority_closure_regressions.rs @@ -283,7 +283,7 @@ async fn assignment_roles_stay_pinned_and_activation_refuses_changed_deciding_au let before = f.holders().await; assert!(matches!( assign(&service, task, "supervisor", "wrong-role").await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(f.holders().await, before); let candidate = ActivationCandidate { diff --git a/crates/registry-casework/tests/support/independent_staffing_activation.rs b/crates/registry-casework/tests/support/independent_staffing_activation.rs index a1ffcd90a7..e7d26eaf58 100644 --- a/crates/registry-casework/tests/support/independent_staffing_activation.rs +++ b/crates/registry-casework/tests/support/independent_staffing_activation.rs @@ -25,7 +25,7 @@ async fn caseload_target_membership_must_match_the_pinned_deciding_profiles() { movement("supervisor", CaseworkActsAs::Supervisor), ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(before, f.holders().await); @@ -43,7 +43,7 @@ async fn caseload_target_membership_must_match_the_pinned_deciding_profiles() { movement("supervisor", CaseworkActsAs::Supervisor), ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); // Explicit supervisor eligibility is supported for newly admitted work. @@ -92,7 +92,7 @@ async fn caseload_refuses_active_absence_and_rechecks_scheduled_absence_at_apply f.service .preview_review_caseload(&supervisor, None, "", movement("b", CaseworkActsAs::Staff)) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(before, f.holders().await); @@ -123,7 +123,7 @@ async fn caseload_refuses_active_absence_and_rechecks_scheduled_absence_at_apply } ) .await, - Err(ReviewRuntimeError::Forbidden(_)) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(before, f.holders().await); } diff --git a/crates/registry-caseworkctl/tests/provision.rs b/crates/registry-caseworkctl/tests/provision.rs index f539fed0e2..de6c3ce497 100644 --- a/crates/registry-caseworkctl/tests/provision.rs +++ b/crates/registry-caseworkctl/tests/provision.rs @@ -194,6 +194,142 @@ fn print_sql_with_a_global_json_format_reports_without_executing() { assert!(!text.contains(MIGRATION_PASSWORD) && !text.contains(RUNTIME_PASSWORD)); } +/// Runs `provision --print-sql` with a JSON report and returns the exit code, +/// the report, and everything the command wrote, for a leak check. +fn refused_print(runtime: &Path) -> (Option, Value, String) { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + runtime.to_str().unwrap(), + "--print-sql", + ]); + let written = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|_| panic!("a JSON report on stdout: {written}")); + (output.status.code(), report, written) +} + +fn assert_loader_refusal( + (code, report, written): &(Option, Value, String), + diagnostic_code: &str, + pointer: &str, +) { + assert_eq!(*code, Some(1), "{written}"); + assert_eq!(report["ok"], false, "{written}"); + assert_eq!( + report["diagnostics"][0]["code"], diagnostic_code, + "{written}" + ); + let location = report["diagnostics"][0]["path"] + .as_str() + .unwrap_or_default(); + assert!(location.ends_with(pointer), "{location} in {written}"); + for private in [MIGRATION_PASSWORD, RUNTIME_PASSWORD, "postgresql://"] { + assert!(!written.contains(private), "the refusal leaks {private}"); + } +} + +#[test] +fn a_missing_runtime_url_secret_is_refused_without_printing_a_password() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + fs::remove_file(deployment.root.join("secrets/runtime-url")).unwrap(); + assert_loader_refusal( + &refused_print(&deployment.runtime), + "casework.runtime.secret-unavailable", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn a_missing_migration_url_secret_is_refused_without_printing_a_password() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + fs::remove_file(deployment.root.join("secrets/migration-url")).unwrap(); + assert_loader_refusal( + &refused_print(&deployment.runtime), + "casework.runtime.secret-unavailable", + "/database/migrationUrlRef", + ); +} + +#[test] +fn a_runtime_url_secret_that_is_not_text_is_refused() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + let file = deployment.root.join("secrets/runtime-url"); + fs::write(&file, [0xff, 0xfe, 0xfd]).unwrap(); + assert_loader_refusal( + &refused_print(&deployment.runtime), + "casework.runtime.secret-unavailable", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn a_missing_ca_bundle_secret_is_refused() { + let (migration, runtime) = offline_urls(); + let ca = tempfile::NamedTempFile::new().unwrap(); + fs::write(ca.path(), "not a bundle, never parsed here").unwrap(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: Some(ca.path()), + plaintext: false, + bind: "127.0.0.1:8100", + }); + fs::remove_file(deployment.root.join("secrets/ca")).unwrap(); + assert_loader_refusal( + &refused_print(&deployment.runtime), + "casework.runtime.secret-unavailable", + "/database/caBundleRef", + ); +} + +#[test] +fn a_runtime_file_that_does_not_load_is_refused_with_its_own_code() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + fs::write(&deployment.runtime, "kind: NotARuntimeConfig\n").unwrap(); + let (code, report, written) = refused_print(&deployment.runtime); + assert_eq!(code, Some(1), "{written}"); + assert_eq!(report["ok"], false, "{written}"); + assert_eq!( + report["diagnostics"][0]["code"], "config.missing-envelope", + "{written}" + ); +} + #[test] fn both_administrator_flags_are_a_usage_error() { let output = ctl(&[ @@ -375,10 +511,22 @@ mod served { assert!(!text.contains(private), "the report leaks a password"); } + // Apply records single-role mode and still succeeds, so only these + // fields show that provisioning left the two roles split. let applied = ctl_ok(&["apply", "--runtime-config", runtime_file]); assert_eq!(applied["ok"], true, "{applied}"); + assert!( + applied["singleRoleStatement"].is_null(), + "apply recorded single-role mode: {applied}" + ); + assert_eq!(applied["activation"]["roleMode"], "split", "{applied}"); let status = ctl_ok(&["status", "--runtime-config", runtime_file]); assert_eq!(status["ok"], true, "{status}"); + assert!( + status["singleRoleStatement"].is_null(), + "status reports single-role mode: {status}" + ); + assert_eq!(status["activation"]["roleMode"], "split", "{status}"); // A second provision finds everything present and creates nothing. let again = ctl_ok(&[ diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index 20e8818842..c441bb1011 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -7,8 +7,8 @@ use registry_platform_config::{ }; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifier, - TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, }; use serde::{Deserialize, Deserializer, Serialize}; use std::{ @@ -315,7 +315,17 @@ impl AccessConfig { .resolve(document_ref) .map_err(|_| refused())?; Arc::new(JwksFetcher::new_static( - parse_static_jwks(value.expose_secret()).map_err(|_| refused())?, + parse_static_jwks(value.expose_secret()).map_err(|error| match error { + // The text names the key position and member, never key material. + OidcError::StaticKeySet(_) => CoordinatorError::new( + "access.configuration", + error.to_string(), + ) + .suggest( + "Correct the document that deployment.authentication.jwksSource.documentRef names.", + ), + _ => refused(), + })?, JwksFetcherConfig::defaults(), )) } @@ -465,9 +475,11 @@ impl Authenticator { pub async fn authenticate(&self, token: &str) -> Result { registry_platform_authcommon::validate_compact_access_token(token) .map_err(|_| unauthenticated(FailedCheck::CredentialMalformed))?; - let verified = self.verifier.verify(token).await.map_err(|error| { - use registry_platform_oidc::OidcError; - match error { + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| match error { OidcError::Transport(_) | OidcError::BoundedRead(_) | OidcError::FetchUrl(_) @@ -483,8 +495,7 @@ impl Authenticator { ) .failing(FailedCheck::KeySourceUnavailable), _ => unauthenticated(error.failed_check()), - } - })?; + })?; if !self.assertion_issuers && verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { return Err(unauthenticated(FailedCheck::TokenAssertionIssuer)); } diff --git a/crates/registry-coordinator/src/event_trigger.rs b/crates/registry-coordinator/src/event_trigger.rs index 1fd94b6cf4..a6d238ddc8 100644 --- a/crates/registry-coordinator/src/event_trigger.rs +++ b/crates/registry-coordinator/src/event_trigger.rs @@ -297,6 +297,8 @@ pub fn verify_delivery( ReceiverError::Stale | ReceiverError::InvalidDeliveryTime => { FailedCheck::DeliveryFreshness } + // A key the receiver cannot use is its own fault, not the sender's. + ReceiverError::InvalidKey => FailedCheck::KeySourceUnavailable, _ => FailedCheck::DeliverySignature, }) })?; @@ -495,6 +497,7 @@ fn source_unavailable() -> CoordinatorError { "event-source-unavailable", "the configured event source authentication is unavailable", ) + .failing(FailedCheck::KeySourceUnavailable) } fn configuration(field: &str, advice: &str) -> CoordinatorError { CoordinatorError::new( diff --git a/crates/registry-coordinator/src/event_trigger_tests.rs b/crates/registry-coordinator/src/event_trigger_tests.rs index b745c786c5..c6bdee9a45 100644 --- a/crates/registry-coordinator/src/event_trigger_tests.rs +++ b/crates/registry-coordinator/src/event_trigger_tests.rs @@ -392,6 +392,38 @@ fn a_refused_delivery_names_the_check_that_failed() { } } +#[test] +fn a_verification_key_the_receiver_cannot_use_is_its_own_key_fault() { + let value = event(); + let (body, headers) = signed(&value, TARGET, 1, "delivery"); + let error = verify_delivery( + &source(), + "registry", + &trigger(), + "record-saved", + &Method::POST, + TARGET, + &headers, + &body, + b"short", + SystemTime::now(), + ) + .err() + .expect("a key shorter than the signature minimum is refused"); + assert_eq!(error.code, "event-unauthenticated"); + assert_eq!(error.check, Some(FailedCheck::KeySourceUnavailable)); +} + +#[test] +fn an_event_key_outage_answers_503_and_counts_as_a_key_source_outage() { + let response = event_problem(source_unavailable()); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + response.extensions().get::().map(|n| n.check), + Some(FailedCheck::KeySourceUnavailable) + ); +} + #[test] fn an_event_refusal_carries_its_check_in_the_response_extensions() { for check in [ diff --git a/crates/registry-coordinator/src/http.rs b/crates/registry-coordinator/src/http.rs index 2e973d55f7..45340ff341 100644 --- a/crates/registry-coordinator/src/http.rs +++ b/crates/registry-coordinator/src/http.rs @@ -432,6 +432,15 @@ mod readiness_tests { use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::Notify; + #[test] + fn the_probe_bodies_keep_the_shared_status_member_and_name_their_own() { + assert_eq!(live_body().to_string(), r#"{"live":true,"status":"ok"}"#); + assert_eq!( + ready_body().to_string(), + r#"{"ready":true,"status":"ready"}"# + ); + } + #[tokio::test(start_paused = true)] async fn live_binding_readiness_refreshes_success_and_failure_at_the_fixed_deadline() { let cache = BindingReadiness::default(); diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs index 916cfe8023..f39098962b 100644 --- a/crates/registry-coordinator/src/provision.rs +++ b/crates/registry-coordinator/src/provision.rs @@ -3,8 +3,9 @@ //! //! The shared runner reads the role names, database and passwords from the //! two URLs this module resolves out of the runtime file, so nothing is -//! written twice. `apply` creates the schema the runtime file's `namespace` -//! names, so provisioning gives the migration role `CREATE` on the database +//! written twice. When the file has a deployment block, its `runtimeRole` +//! must be the runtime URL's user. `apply` creates the schema the runtime +//! file's `namespace` names, so provisioning gives the migration role `CREATE` on the database //! and the runtime role `CONNECT`, and leaves every other grant to `apply`. use std::path::Path; @@ -23,6 +24,9 @@ use crate::runtime::RuntimeConfig; /// The diagnostic code the runtime file's own refusals carry. const RUNTIME_CONFIG_REFUSED: &str = "coordinator.runtime-config.refused"; +/// The runtime URL logs in as a role other than `deployment.runtimeRole`. +const RUNTIME_ROLE_MISMATCH: &str = "coordinator.runtime-config.runtime-role-mismatch"; + /// Runs the verb. The shared runner owns a runtime of its own, so it runs off /// the service's executor threads. pub(crate) async fn run(args: ProvisionArgs, format: OutputFormat) -> ExitCode { @@ -66,6 +70,9 @@ fn load(path: &Path) -> Result> { &database.runtime_url_ref, "/database/runtimeUrlRef", )?; + if let Some(deployment) = &runtime.deployment { + require_runtime_role(&runtime_url, &deployment.runtime_role)?; + } let ca_pem = match &database.ca_bundle_ref { Some(reference) => Some( secret_text(&resolver, reference, "/database/caBundleRef")? @@ -87,6 +94,27 @@ fn load(path: &Path) -> Result> { }) } +/// `apply` grants to `deployment.runtimeRole` and the service requires its +/// connection to log in as that role, so a runtime URL naming another user +/// would provision a role neither of them uses. The diagnostic names the +/// configured role, never the URL. +fn require_runtime_role(runtime_url: &str, expected: &str) -> Result<(), Box> { + let user = runtime_url + .trim() + .parse::() + .ok() + .and_then(|config| config.get_user().map(str::to_owned)); + if user.as_deref() == Some(expected) { + return Ok(()); + } + Err(Box::new(Diagnostic::error( + RUNTIME_ROLE_MISMATCH, + "/database/runtimeUrlRef", + format!("the runtime database URL does not log in as deployment.runtimeRole ({expected})"), + "Use the runtimeRole as the user of the URL database.runtimeUrlRef names, or change deployment.runtimeRole to the URL's user.", + ))) +} + fn secret_text( resolver: &SecretResolver, reference: &str, diff --git a/crates/registry-coordinator/src/store/recovery.rs b/crates/registry-coordinator/src/store/recovery.rs index eb7010f1ac..d97e6ed601 100644 --- a/crates/registry-coordinator/src/store/recovery.rs +++ b/crates/registry-coordinator/src/store/recovery.rs @@ -3,6 +3,7 @@ use super::*; use crate::protocol::{AdapterSet, ReconciliationOutcome}; use registry_platform_audit::AuditRequest; +use registry_platform_authcommon::FailedCheck; use serde_json::json; use std::future::Future; @@ -74,20 +75,27 @@ pub struct ProposalWaitsByTurn { pub unobserved: i64, } +/// The bound the authenticator already puts on every identity it admits. +fn bounded_identity(actor: &Actor) -> Result<()> { + if [&actor.issuer, &actor.subject, &actor.client_id] + .iter() + .any(|v| v.is_empty() || v.len() > 512) + { + return Err(refused( + "access.denied", + "verified bounded caller identity is required", + ) + .failing(FailedCheck::TokenClaims)); + } + Ok(()) +} + impl Store { pub fn audit_writer(&self) -> AuditWriter { self.security.audit.clone() } pub(super) fn owner(&self, actor: &Actor) -> Result { - if [&actor.issuer, &actor.subject, &actor.client_id] - .iter() - .any(|v| v.is_empty() || v.len() > 512) - { - return Err(refused( - "access.denied", - "verified bounded caller identity is required", - )); - } + bounded_identity(actor)?; Ok(self.security.keys.commitment( "owner", &[ @@ -127,7 +135,8 @@ impl Store { return Err(refused( "access.denied", "this operation requires the configured operator policy", - )); + ) + .failing(FailedCheck::Operation)); } Ok(()) } @@ -1154,3 +1163,35 @@ impl Store { }).await } } + +#[cfg(test)] +mod tests { + use super::*; + + fn actor(subject: &str, operator: bool) -> Actor { + Actor { + issuer: "https://issuer.example.test".to_owned(), + subject: subject.to_owned(), + client_id: "client".to_owned(), + operator, + } + } + + #[test] + fn a_caller_without_the_operator_policy_is_refused_under_operation() { + let error = Store::operator(&actor("subject", false)).unwrap_err(); + assert_eq!(error.code, "access.denied"); + assert_eq!(error.check, Some(FailedCheck::Operation)); + assert!(Store::operator(&actor("subject", true)).is_ok()); + } + + #[test] + fn an_identity_outside_the_bound_is_refused_under_token_claims() { + for subject in ["", &"s".repeat(513)] { + let error = bounded_identity(&actor(subject, false)).unwrap_err(); + assert_eq!(error.code, "access.denied"); + assert_eq!(error.check, Some(FailedCheck::TokenClaims)); + } + assert!(bounded_identity(&actor(&"s".repeat(512), false)).is_ok()); + } +} diff --git a/crates/registry-coordinator/tests/deployment_postgres.rs b/crates/registry-coordinator/tests/deployment_postgres.rs index d4720a5869..fe1f05279d 100644 --- a/crates/registry-coordinator/tests/deployment_postgres.rs +++ b/crates/registry-coordinator/tests/deployment_postgres.rs @@ -4835,6 +4835,14 @@ async fn the_metrics_listener_counts_closed_series_and_leaves_the_gauge_stale_in .await .unwrap(); assert_eq!(unadmitted.status(), 403); + // A verified client whose subject its policy does not list. + let unlisted = http + .get(format!("{origin}/v1/runs?limit=10")) + .bearer_auth(f.token("producer-a", "unlisted-subject", "coordinator:start")) + .send() + .await + .unwrap(); + assert_eq!(unlisted.status(), 403); let application = "00000000-0000-4000-8000-0000000000aa"; let (status, run) = start_run( &http, @@ -4855,12 +4863,22 @@ async fn the_metrics_listener_counts_closed_series_and_leaves_the_gauge_stale_in ), ( "coordinator_authentication_refusals_total{reason=\"policy\"}", - 1, + 2, ), ( "coordinator_authentication_refusals_total{reason=\"unavailable\"}", 0, ), + // The request counter names the failed check of each refusal. + ( + "coordinator_request_refusals_total{check=\"credential-malformed\"}", + 1, + ), + ("coordinator_request_refusals_total{check=\"scope\"}", 1), + ( + "coordinator_request_refusals_total{check=\"access-profile\"}", + 1, + ), ("coordinator_runs_admitted_total", 1), ("coordinator_dispatch_jobs{state=\"pending\"}", 1), ] { @@ -4872,6 +4890,7 @@ async fn the_metrics_listener_counts_closed_series_and_leaves_the_gauge_stale_in application, "owner-a", "producer-a", + "unlisted-subject", ] { assert!( !body.contains(caller_text), diff --git a/crates/registry-coordinator/tests/provision_cli.rs b/crates/registry-coordinator/tests/provision_cli.rs index bb05e9bfbf..b5a5e41692 100644 --- a/crates/registry-coordinator/tests/provision_cli.rs +++ b/crates/registry-coordinator/tests/provision_cli.rs @@ -7,6 +7,11 @@ const RUNTIME: &str = include_str!("../../../products/coordinator/examples/single-flow-runtime.yaml"); const MIGRATION_PASSWORD: &str = "migration-password-canary"; const RUNTIME_PASSWORD: &str = "runtime-password-canary"; +const ADMIN_URL_VARIABLE: &str = "COORDINATOR_TEST_ADMIN_URL"; +/// Nothing listens here, so a command that reached the connection step would +/// fail with a connection error instead of the loader's refusal. +const ADMIN_URL: &str = + "postgres://admin:admin-password-canary@127.0.0.1:1/postgres?sslmode=verify-full"; /// A runtime file the loader accepts, whose database references resolve from /// the environment the command is given. @@ -31,22 +36,62 @@ fn runtime_file(directory: &Path) -> std::path::PathBuf { path } -fn provision(runtime: &Path, extra: &[&str]) -> std::process::Output { - Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) +fn database_url(user: &str, password: &str) -> String { + format!("postgres://{user}:{password}@db.example.org:5432/coordinator") +} + +/// Runs `provision` with the given database URLs in the environment. `None` +/// leaves the variable unset, so its secret reference cannot resolve. +fn provision_with( + runtime: &Path, + extra: &[&str], + migration_url: Option, + runtime_url: Option, +) -> std::process::Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_coordinatorctl")); + command .arg("provision") .arg("--runtime-config") .arg(runtime) .args(extra) - .env( - "COORDINATOR_MIGRATION_URL", - format!("postgres://coordinator_migration:{MIGRATION_PASSWORD}@db.example.org:5432/coordinator"), - ) - .env( - "COORDINATOR_DATABASE_URL", - format!("postgres://coordinator_runtime:{RUNTIME_PASSWORD}@db.example.org:5432/coordinator"), - ) - .output() - .unwrap() + .env_remove("COORDINATOR_MIGRATION_URL") + .env_remove("COORDINATOR_DATABASE_URL") + .env(ADMIN_URL_VARIABLE, ADMIN_URL); + if let Some(url) = migration_url { + command.env("COORDINATOR_MIGRATION_URL", url); + } + if let Some(url) = runtime_url { + command.env("COORDINATOR_DATABASE_URL", url); + } + command.output().unwrap() +} + +fn provision(runtime: &Path, extra: &[&str]) -> std::process::Output { + provision_with( + runtime, + extra, + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + Some(database_url("coordinator_runtime", RUNTIME_PASSWORD)), + ) +} + +/// Asserts a loader refusal: exit 1, nothing on stdout, the code and the +/// pointer on stderr, and no password or URL anywhere. +fn assert_refused(output: &std::process::Output, code: &str, pointer: &str) { + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stdout}{stderr}"); + assert!(stdout.is_empty(), "a refusal prints no plan: {stdout}"); + assert!(stderr.contains(code), "{stderr}"); + assert!(stderr.contains(pointer), "{stderr}"); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + "admin-password-canary", + "postgres://", + ] { + assert!(!stderr.contains(secret), "stderr leaked a secret"); + } } #[test] @@ -110,3 +155,118 @@ fn an_administrator_source_is_required_unless_printing() { "the refusal names the flags: {stderr}" ); } + +#[test] +fn a_runtime_url_user_that_is_not_the_deployment_runtime_role_is_refused_before_connecting() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + // With an administrator URL that could not connect, only the loader's + // refusal explains exit 1 with this code. + let output = provision_with( + &runtime, + &["--admin-url-env", ADMIN_URL_VARIABLE], + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + Some(database_url("coord_rt", RUNTIME_PASSWORD)), + ); + assert_refused( + &output, + "coordinator.runtime-config.runtime-role-mismatch", + "/database/runtimeUrlRef", + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("coordinator_runtime"), + "the refusal names the configured role: {stderr}" + ); + assert!( + !stderr.contains("coord_rt:") && !stderr.contains("@db.example.org"), + "the refusal does not echo the URL: {stderr}" + ); + + let printed = provision_with( + &runtime, + &["--print-sql"], + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + Some(database_url("coord_rt", RUNTIME_PASSWORD)), + ); + assert_refused( + &printed, + "coordinator.runtime-config.runtime-role-mismatch", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn an_unreadable_runtime_url_secret_is_refused_without_a_password() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision_with( + &runtime, + &["--print-sql"], + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + None, + ); + assert_refused( + &output, + "coordinator.runtime-config.refused", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn an_unreadable_migration_url_secret_is_refused_without_a_password() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision_with( + &runtime, + &["--print-sql"], + None, + Some(database_url("coordinator_runtime", RUNTIME_PASSWORD)), + ); + assert_refused( + &output, + "coordinator.runtime-config.refused", + "/database/migrationUrlRef", + ); +} + +#[test] +fn a_certificate_authority_file_that_is_not_text_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let root_pem = directory.path().join("secrets/postgres-root.pem"); + fs::write(&root_pem, [0xff, 0xfe, 0xfd]).unwrap(); + let output = provision(&runtime, &["--print-sql"]); + assert_refused( + &output, + "coordinator.runtime-config.refused", + "/database/caBundleRef", + ); +} + +#[test] +fn a_missing_certificate_authority_file_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + fs::remove_file(directory.path().join("secrets/postgres-root.pem")).unwrap(); + let output = provision(&runtime, &["--print-sql"]); + assert_refused( + &output, + "coordinator.runtime-config.refused", + "/database/caBundleRef", + ); +} + +#[test] +fn a_runtime_file_the_service_would_refuse_is_refused_with_its_own_diagnostic() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + fs::write(&runtime, "kind: NotARuntimeFile\n").unwrap(); + let output = provision(&runtime, &["--print-sql"]); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stdout}{stderr}"); + assert!(stdout.is_empty(), "{stdout}"); + assert!(!stderr.is_empty()); + assert!(!stderr.contains("postgres://")); +} diff --git a/crates/registry-coordinator/tests/provision_postgres.rs b/crates/registry-coordinator/tests/provision_postgres.rs index f4c4073e0f..dbf678250a 100644 --- a/crates/registry-coordinator/tests/provision_postgres.rs +++ b/crates/registry-coordinator/tests/provision_postgres.rs @@ -284,6 +284,10 @@ async fn run(superuser_url: String, ca_pem: Vec, owner_password: String, nam let workflows = Arc::new(deployment::load_workflows(deployment::config(&runtime).unwrap()).unwrap()); let store = deployment::open(&runtime, false).await.unwrap(); + // The serving check the service runs at startup and on every `/ready`. + deployment::check_serving(&store, &runtime, workflows.digest()) + .await + .unwrap(); let authenticator = Arc::new( deployment::config(&runtime) .unwrap() diff --git a/crates/registry-coordinator/tests/static_key_set.rs b/crates/registry-coordinator/tests/static_key_set.rs new file mode 100644 index 0000000000..8994e2485d --- /dev/null +++ b/crates/registry-coordinator/tests/static_key_set.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The static key set behind `deployment.authentication.jwksSource` loads +//! through the authenticator the server builds, and a refused set names the +//! key file's own problem at startup. +use registry_coordinator::access::{AccessConfig, Action, ClientPolicy}; +use registry_platform_config::{ + FileSecretProviderConfig, JwksSource, OidcIssuerConfig, SecretProvidersConfig, +}; +use registry_platform_testing::TokenSigner; +use registry_platform_yaml::Url; +use serde_json::{json, Value}; +use std::{collections::BTreeMap, fs, os::unix::fs::PermissionsExt}; + +const KEY_FILE: &str = "issuer-keys.json"; + +/// The corpus signer's public keys a static document may hold: RSA and EC +/// only, so its EdDSA key is left out. +fn public_keys() -> Value { + let mut keys = TokenSigner::new().public_key_set(); + keys["keys"] + .as_array_mut() + .unwrap() + .retain(|key| key["kty"] != "OKP"); + keys +} + +async fn build(document: &Value) -> Result<(), registry_coordinator::CoordinatorError> { + let root = tempfile::tempdir().unwrap(); + let root_path = root.path().canonicalize().unwrap(); + let file = root_path.join(KEY_FILE); + fs::write(&file, document.to_string()).unwrap(); + fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap(); + let secrets = SecretProvidersConfig { + file: Some(FileSecretProviderConfig { root: root_path }), + environment: None, + }; + let access = AccessConfig { + issuer: OidcIssuerConfig { + issuer: Url::new("https://issuer.example.test".to_owned()).unwrap(), + audience: "urn:coordinator:test".to_owned(), + jwks_source: JwksSource::Static { + document_ref: format!("secret:file/{KEY_FILE}"), + }, + allow_insecure_http: false, + }, + assertion_issuers: BTreeMap::new(), + scope_claim: "scope".to_owned(), + policies: BTreeMap::from([( + "journey-app".to_owned(), + ClientPolicy { + subjects: vec!["subject".to_owned()], + required_scopes: vec!["coordinator:start".to_owned()], + workflows: vec!["follow-up".to_owned()], + actions: vec![Action::Start], + operator: false, + }, + )]), + }; + access.authenticator(&secrets, false).await.map(|_| ()) +} + +#[tokio::test] +async fn a_public_key_set_with_an_ext_member_loads() { + let mut keys = public_keys(); + keys["keys"][0]["ext"] = json!(true); + build(&keys).await.expect("a public key set with ext loads"); +} + +#[tokio::test] +async fn a_key_set_holding_a_private_member_is_refused_with_the_key_files_own_text() { + let mut keys = public_keys(); + keys["keys"][0]["d"] = json!("AQAB"); + let error = match build(&keys).await { + Ok(()) => panic!("a key set with a private member is refused"), + Err(error) => error, + }; + assert_eq!(error.code, "access.configuration"); + assert!( + error.message.contains("static key set"), + "the refusal names the key set, not the issuer or policies: {}", + error.message + ); + assert!( + !error.message.contains("AQAB"), + "the refusal carries no key material: {}", + error.message + ); +} diff --git a/crates/registry-documents-core/src/project.rs b/crates/registry-documents-core/src/project.rs index 874f22232b..87ac3882cb 100644 --- a/crates/registry-documents-core/src/project.rs +++ b/crates/registry-documents-core/src/project.rs @@ -345,6 +345,9 @@ pub enum ActorKind { } impl ActorKind { + /// Every actor kind, so a caller that sweeps the kinds follows a new one. + pub const ALL: [Self; 2] = [Self::Service, Self::Human]; + /// The spelling the project and the store use. #[must_use] pub const fn as_str(self) -> &'static str { diff --git a/crates/registry-documents-core/tests/actor_kind_all.rs b/crates/registry-documents-core/tests/actor_kind_all.rs new file mode 100644 index 0000000000..16b0f28327 --- /dev/null +++ b/crates/registry-documents-core/tests/actor_kind_all.rs @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `ActorKind::ALL` lists every actor kind. + +use registry_documents_core::ActorKind; + +/// An exhaustive match: a new kind fails to compile here until it is handled, +/// which is the reminder to list it in `ActorKind::ALL`. +fn listed(kind: ActorKind) -> bool { + match kind { + ActorKind::Service | ActorKind::Human => ActorKind::ALL.contains(&kind), + } +} + +#[test] +fn every_actor_kind_is_listed_once() { + assert!(listed(ActorKind::Service)); + assert!(listed(ActorKind::Human)); + assert_eq!(ActorKind::ALL.len(), 2); +} diff --git a/crates/registry-documents/Cargo.toml b/crates/registry-documents/Cargo.toml index b502e88031..7ab3e3cf1c 100644 --- a/crates/registry-documents/Cargo.toml +++ b/crates/registry-documents/Cargo.toml @@ -57,6 +57,11 @@ name = "refusal_golden" path = "tests/refusal_golden.rs" required-features = ["postgres-test"] +[[test]] +name = "refusal_key_source" +path = "tests/refusal_key_source.rs" +required-features = ["postgres-test"] + [features] default = [] postgres-test = [] diff --git a/crates/registry-documents/src/auth.rs b/crates/registry-documents/src/auth.rs index 394b7973c9..661cededf5 100644 --- a/crates/registry-documents/src/auth.rs +++ b/crates/registry-documents/src/auth.rs @@ -106,18 +106,19 @@ impl DocumentsAuthenticator { /// that wants another actor kind: when no kind reaches past the profile /// lookup, the client has no profile. fn profile_check(&self, facts: &VerifiedTokenFacts<'_>) -> FailedCheck { + if facts.client_id.is_none() { + return FailedCheck::TokenClient; + } if self.profiles.missing_scope(facts).is_some() { return FailedCheck::Scope; } - let profile_exists = [ActorKind::Human, ActorKind::Service] - .into_iter() - .any(|kind| { - let probe = VerifiedTokenFacts { - actor_kind: ActorKindClaim::Present(kind), - ..*facts - }; - !matches!(self.profiles.resolve(&probe), Err(AccessRefusal::Profile)) - }); + let profile_exists = ActorKind::ALL.into_iter().any(|kind| { + let probe = VerifiedTokenFacts { + actor_kind: ActorKindClaim::Present(kind), + ..*facts + }; + !matches!(self.profiles.resolve(&probe), Err(AccessRefusal::Profile)) + }); if profile_exists { FailedCheck::ActorKind } else { @@ -386,6 +387,23 @@ pub(crate) mod tests { assert_eq!(refused_check(absent).await, FailedCheck::ActorKind); } + #[test] + fn a_token_with_no_client_id_is_a_token_client_refusal() { + let claims = serde_json::Map::new(); + let facts = VerifiedTokenFacts { + issuer: Some(ISSUER), + subject: Some("citizen-1"), + client_id: None, + scopes: &[], + actor_kind: ActorKindClaim::Absent, + claims: &claims, + }; + assert_eq!( + authenticator().profile_check(&facts), + FailedCheck::TokenClient + ); + } + #[tokio::test] async fn a_client_no_profile_lists_is_not_a_missing_actor_kind() { // With no actor kind either, the profile lookup still fails first. diff --git a/crates/registry-documents/src/config.rs b/crates/registry-documents/src/config.rs index 487e1b004a..5558cdd50d 100644 --- a/crates/registry-documents/src/config.rs +++ b/crates/registry-documents/src/config.rs @@ -944,7 +944,7 @@ impl RuntimeConfig { .map(|client| { Finding::new( ASSERTION_ISSUER_CLIENT_NOT_ALLOWED_CODE, - &dotted_pointer(&format!("authentication.oidc.assertionIssuers.{client}")), + &format!("/authentication/oidc/assertionIssuers/{}", escape(client)), format!( "authentication.oidc.assertionIssuers names {client}, which no access profile of the project lists as a requester client" ), @@ -1497,6 +1497,19 @@ pub(crate) mod tests { ); } + #[test] + fn an_assertion_issuer_client_with_dots_is_reported_at_its_own_pointer() { + let text = from_package_runtime().replace( + "allowedClients: from-package\n", + "allowedClients: from-package\n assertionIssuers:\n com.example.portal: [https://assertions.example.test]\n", + ); + let config = parse(&text).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + ["documents.runtime.assertion-issuer-client-not-allowed /authentication/oidc/assertionIssuers/com.example.portal"] + ); + } + #[test] fn assertion_issuer_client_outside_an_explicit_list_is_refused() { let text = STARTER_RUNTIME.replace( diff --git a/crates/registry-documents/src/http.rs b/crates/registry-documents/src/http.rs index 27cdc5b94e..e2527d7fc5 100644 --- a/crates/registry-documents/src/http.rs +++ b/crates/registry-documents/src/http.rs @@ -861,7 +861,7 @@ mod tests { "only a scope refusal carries a remedy" ); } - let plain = refusal_response(ServiceError::Problem(ProblemCode::RequestInvalid)); + let plain = refusal_response(ServiceError::from(ProblemCode::RequestInvalid)); assert!(plain.extensions().get::().is_none()); } diff --git a/crates/registry-documents/src/runtime.rs b/crates/registry-documents/src/runtime.rs index 24077f3be5..48d6f68822 100644 --- a/crates/registry-documents/src/runtime.rs +++ b/crates/registry-documents/src/runtime.rs @@ -397,6 +397,9 @@ async fn prepare_with( )), None => None, }; + let admitted = config + .admitted_clients(&project) + .map_err(|finding| RuntimeConfigError::Refused(vec![finding]))?; // The sweep changes what the instances already serving release, so it // runs only once every step that could refuse this start has succeeded. let suspended = sweep_bindings(&store, verifier.binding_digest()) @@ -411,9 +414,6 @@ async fn prepare_with( "versions verified under another verifier binding were suspended for verification again" ); } - let admitted = config - .admitted_clients(&project) - .map_err(|finding| RuntimeConfigError::Refused(vec![finding]))?; let authenticator = Arc::new(DocumentsAuthenticator::new( config.verifier_profile(&admitted), keys, diff --git a/crates/registry-documents/src/service.rs b/crates/registry-documents/src/service.rs index a406aa0e11..d737abe19b 100644 --- a/crates/registry-documents/src/service.rs +++ b/crates/registry-documents/src/service.rs @@ -278,13 +278,36 @@ impl RefusalCode { } } +/// A problem code that is not a refusal of authority. The only way to build +/// one is [`PlainProblem::new`], which refuses a code [`RefusalCode::of`] +/// maps, so a refusal cannot be answered without the check it failed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct PlainProblem(ProblemCode); + +impl PlainProblem { + /// `problem` as a plain problem, or `None` when it is a refusal code. + #[must_use] + pub fn new(problem: ProblemCode) -> Option { + match RefusalCode::of(problem) { + None => Some(Self(problem)), + Some(_) => None, + } + } + + /// The problem the caller is answered with. + #[must_use] + pub const fn problem(self) -> ProblemCode { + self.0 + } +} + /// Why an operation answered a problem. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ServiceError { /// A problem that is not a refusal of authority: validation, a conflict, - /// an idempotency answer, or an outage. A code for which - /// [`RefusalCode::of`] answers `Some` is built as `Refused`. - Problem(ProblemCode), + /// an idempotency answer, or an outage. A refusal code is built as + /// `Refused`. + Problem(PlainProblem), /// A refusal of authority, with the check it failed. Refused { code: RefusalCode, @@ -338,7 +361,7 @@ impl ServiceError { #[must_use] pub const fn problem(&self) -> ProblemCode { match self { - Self::Problem(problem) => *problem, + Self::Problem(problem) => problem.problem(), Self::Refused { code, .. } => code.problem(), Self::KeySourceUnavailable => ProblemCode::ServiceUnavailable, } @@ -362,16 +385,14 @@ impl From for ServiceError { /// it is logged and answered `service.unavailable`, never as a refusal /// the operator cannot account for. fn from(problem: ProblemCode) -> Self { - match RefusalCode::of(problem) { - None => Self::Problem(problem), - Some(_) => { - tracing::error!( - code = problem.code(), - "a refusal was built without the check it failed" - ); - Self::Problem(ProblemCode::ServiceUnavailable) - } + if let Some(plain) = PlainProblem::new(problem) { + return Self::Problem(plain); } + tracing::error!( + code = problem.code(), + "a refusal was built without the check it failed" + ); + Self::Problem(PlainProblem(ProblemCode::ServiceUnavailable)) } } @@ -388,7 +409,7 @@ fn custody_refusal(problem: ProblemCode) -> ServiceError { /// Log a failure the caller is answered `service.unavailable` for. fn unavailable(stage: &'static str, error: &dyn std::fmt::Display) -> ServiceError { tracing::error!(stage, error = %error, "a document operation failed"); - ServiceError::Problem(ProblemCode::ServiceUnavailable) + ServiceError::Problem(PlainProblem(ProblemCode::ServiceUnavailable)) } fn timestamp(value: DateTime) -> String { @@ -1859,10 +1880,13 @@ mod tests { for problem in ProblemCode::ALL { let error = ServiceError::from(*problem); match RefusalCode::of(*problem) { - None => assert_eq!(error, ServiceError::Problem(*problem)), + None => assert_eq!( + error, + ServiceError::Problem(PlainProblem::new(*problem).unwrap()) + ), Some(_) => assert_eq!( error, - ServiceError::Problem(ProblemCode::ServiceUnavailable), + ServiceError::from(ProblemCode::ServiceUnavailable), "{problem:?}" ), } @@ -1913,7 +1937,7 @@ mod tests { ); assert_eq!( custody_refusal(ProblemCode::DocumentPolicyUnknown), - ServiceError::Problem(ProblemCode::DocumentPolicyUnknown) + ServiceError::from(ProblemCode::DocumentPolicyUnknown) ); } diff --git a/crates/registry-documents/src/service/grants.rs b/crates/registry-documents/src/service/grants.rs index 44b4f2d221..f55bb9c6f6 100644 --- a/crates/registry-documents/src/service/grants.rs +++ b/crates/registry-documents/src/service/grants.rs @@ -148,7 +148,15 @@ impl DocumentService { access.standing.may_list_grants() }; if !allowed { - return Err(ServiceError::not_authorized(FailedCheck::Operation)); + // A caller that sees the document and does not hold custody of it + // is refused because the document belongs to another caller. A + // custodian is refused because its profile has no grant authority. + let check = if access.standing.custodian { + FailedCheck::Operation + } else { + FailedCheck::Ownership + }; + return Err(ServiceError::not_authorized(check)); } Ok(record) } diff --git a/crates/registry-documents/tests/golden/refusals.json b/crates/registry-documents/tests/golden/refusals.json index aac6cbc2de..8afc5cadaf 100644 --- a/crates/registry-documents/tests/golden/refusals.json +++ b/crates/registry-documents/tests/golden/refusals.json @@ -42,6 +42,20 @@ }, "status": 401 }, + "client-no-profile-lists": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, "download-by-a-stranger": { "body": { "code": "resource.not-found", diff --git a/crates/registry-documents/tests/refusal_golden.rs b/crates/registry-documents/tests/refusal_golden.rs index 8bf1980383..9820e50435 100644 --- a/crates/registry-documents/tests/refusal_golden.rs +++ b/crates/registry-documents/tests/refusal_golden.rs @@ -29,8 +29,8 @@ use registry_platform_authcommon::FailedCheck; use serde_json::{json, Value}; use support::{ pdf, request, reservation, token, token_with, Answer, Api, Deployment, FakeVerifier, Principal, - APP, APPROVE, CITIZEN, DATABASE_STORAGE, DISABLED_VERIFIER, OTHER_APP, READER, STRANGER, - TEST_AUDIENCE, TEST_ISSUER, + APP, APPROVE, CITIZEN, DATABASE_STORAGE, DISABLED_VERIFIER, OTHER_APP, PARTNER_SERVICE, READER, + STRANGER, TEST_AUDIENCE, TEST_ISSUER, }; use tower::ServiceExt as _; use tracing::instrument::WithSubscriber as _; @@ -135,6 +135,7 @@ struct World { document: String, version: String, upload_path: String, + missing: String, } async fn world() -> World { @@ -171,6 +172,7 @@ async fn world() -> World { document, version, upload_path, + missing: Uuid::new_v4().to_string(), } } @@ -181,7 +183,7 @@ fn claims(name: &str, value: Value) -> Value { fn fixtures(world: &World) -> Vec { let document = &world.document; let version = &world.version; - let missing = Uuid::new_v4().to_string(); + let missing = world.missing.clone(); let reserve = |policy: &str, custodian: &str| { support::reservation_body( policy, @@ -268,6 +270,15 @@ fn fixtures(world: &World) -> Vec { "/v1/documents", signed(claims("scope", json!("documents:read"))), ), + // The verifier admits this client and no access profile of the + // starter project lists it. + Fixture::as_principal( + "client-no-profile-lists", + FailedCheck::AccessProfile, + Method::GET, + "/v1/documents", + PARTNER_SERVICE, + ), Fixture::get( "another-actor-kind", FailedCheck::ActorKind, @@ -337,7 +348,7 @@ fn fixtures(world: &World) -> Vec { ), Fixture::as_principal( "grants-listed-by-the-reserving-system", - FailedCheck::Operation, + FailedCheck::Ownership, Method::GET, &format!("/v1/documents/{document}/grants"), APP, @@ -354,7 +365,7 @@ fn fixtures(world: &World) -> Vec { ), Fixture::as_principal( "grant-issued-by-the-reserving-system", - FailedCheck::Operation, + FailedCheck::Ownership, Method::POST, &format!("/v1/documents/{document}/grants"), APP, @@ -588,16 +599,30 @@ async fn every_refusal_is_counted_and_logged_under_the_check_it_failed() { "reader-1", "someone-else", "not-a-token", + "partner-service", + CITIZEN.subject, + &world.document, + &world.version, + &world.missing, ] { assert!(!text.contains(canary), "{canary} reached the log\n{text}"); } assert!(!logged.is_empty()); } +/// The sum of every series of `documents_request_refusals_total`. +async fn counted_in_total(prepared: &Prepared) -> u64 { + let mut total = 0; + for check in FailedCheck::ALL { + total += counted(prepared, check).await; + } + total +} + #[tokio::test] async fn a_request_that_is_not_refused_is_not_counted() { let world = world().await; - let before = counted(&world.prepared, FailedCheck::Visibility).await; + let before = counted_in_total(&world.prepared).await; let read = world.api.read(CITIZEN, &world.document).await; assert_eq!(read.status, 200); let listed = world.api.get(CITIZEN, "/v1/documents").await; @@ -613,9 +638,6 @@ async fn a_request_that_is_not_refused_is_not_counted() { ) .await; assert!(unsupported.status >= 400); - assert_eq!( - counted(&world.prepared, FailedCheck::Visibility).await, - before - ); + assert_eq!(counted_in_total(&world.prepared).await, before); drop(world.deployment); } diff --git a/crates/registry-documents/tests/refusal_key_source.rs b/crates/registry-documents/tests/refusal_key_source.rs new file mode 100644 index 0000000000..327a057b74 --- /dev/null +++ b/crates/registry-documents/tests/refusal_key_source.rs @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! A key source that does not answer. The caller is answered +//! `service.unavailable` with `Retry-After`, never a 401, and the operator's +//! counter records `key-source-unavailable`. The database is named by +//! `DOCUMENTS_TEST_DATABASE_URL`. + +mod support; + +use axum::body::Body; +use axum::http::Request; +use registry_documents::runtime::{prepare_with_verifier, Prepared}; +use registry_platform_authcommon::FailedCheck; +use support::{ + Api, Deployment, FakeVerifier, APPROVE, CITIZEN, DATABASE_STORAGE, DISABLED_VERIFIER, +}; +use tower::ServiceExt as _; + +/// The count `documents_request_refusals_total` holds for `check`. +async fn counted(prepared: &Prepared, check: FailedCheck) -> u64 { + let response = prepared + .metrics_app() + .expect("a metrics listener is configured") + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), 200); + let text = String::from_utf8( + axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(), + ) + .unwrap(); + let prefix = format!( + "documents_request_refusals_total{{check=\"{}\"}} ", + check.as_str() + ); + text.lines() + .find_map(|line| line.strip_prefix(&prefix)) + .unwrap_or_else(|| panic!("no series for {}\n{text}", check.as_str())) + .parse() + .unwrap() +} + +#[tokio::test] +async fn an_unreachable_key_source_answers_unavailable_and_counts_the_check() { + let mut deployment = Deployment::new(DATABASE_STORAGE, DISABLED_VERIFIER).await; + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + deployment.configure(&format!("metricsListener:\n bind: 127.0.0.1:{port}\n")); + // Nothing listens on the discard port, so every key fetch fails. + deployment.fetch_keys_from("http://127.0.0.1:9/jwks"); + deployment.migrate().await; + let prepared = prepare_with_verifier( + &deployment.runtime, + FakeVerifier::new("refusal-key-source", APPROVE), + ) + .await + .expect("the runtime prepares without reaching the key source"); + let api = Api::new(&prepared); + let before = counted(&prepared, FailedCheck::KeySourceUnavailable).await; + let answer = api.get(CITIZEN, "/v1/documents").await; + assert_eq!( + answer.status, + 503, + "{}", + String::from_utf8_lossy(&answer.body) + ); + assert_eq!(answer.headers["retry-after"], "5"); + assert_eq!(answer.headers["content-type"], "application/problem+json"); + assert_eq!(answer.json()["code"], "service.unavailable"); + assert!(answer.headers.get("www-authenticate").is_none()); + assert_eq!( + counted(&prepared, FailedCheck::KeySourceUnavailable).await, + before + 1 + ); + drop(deployment); +} diff --git a/crates/registry-documents/tests/support/mod.rs b/crates/registry-documents/tests/support/mod.rs index 39411d1594..84b8d99019 100644 --- a/crates/registry-documents/tests/support/mod.rs +++ b/crates/registry-documents/tests/support/mod.rs @@ -67,6 +67,7 @@ pub struct Deployment { extra: String, hooks_url: String, allowed_clients: String, + jwks_source: String, } impl Deployment { @@ -126,6 +127,7 @@ impl Deployment { allowed_clients: "[civil-registry-app, citizen-portal, case-portal, partner-portal, partner-service]" .to_owned(), + jwks_source: "type: static\n documentRef: secret:file/jwks.json".to_owned(), }; deployment.secret("runtime-database-url", runtime_url.unwrap_or(&scoped_url)); deployment.secret("migration-database-url", &scoped_url); @@ -191,6 +193,13 @@ impl Deployment { self.write_runtime(); } + /// Name the issuer's key set by `uri` in place of the static key set, so a + /// refusal to verify can be driven by a key source that does not answer. + pub fn fetch_keys_from(&mut self, uri: &str) { + self.jwks_source = format!("type: uri\n uri: {uri}"); + self.write_runtime(); + } + /// Append `block`, top-level runtime keys, to the runtime document. pub fn configure(&mut self, block: &str) { self.extra = block.to_owned(); @@ -224,8 +233,7 @@ authentication: scopeClaim: scope allowedClients: {allowed_clients} jwksSource: - type: static - documentRef: secret:file/jwks.json + {jwks_source} audit: destination: file path: {audit} @@ -249,6 +257,7 @@ destinations: extra = self.extra, hooks_url = self.hooks_url, allowed_clients = self.allowed_clients, + jwks_source = self.jwks_source, ); std::fs::write(&self.runtime, document).unwrap(); } diff --git a/crates/registry-documentsctl/tests/provision_cli.rs b/crates/registry-documentsctl/tests/provision_cli.rs index 204f0cec6e..0d8a7dd217 100644 --- a/crates/registry-documentsctl/tests/provision_cli.rs +++ b/crates/registry-documentsctl/tests/provision_cli.rs @@ -114,9 +114,10 @@ fn print_sql_writes_the_script_and_no_password() { let stderr = String::from_utf8(output.stderr).unwrap(); assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); assert!(stderr.is_empty(), "{stderr}"); - for name in ["documents_migration", "documents_runtime", "documents"] { + for name in ["documents_migration", "documents_runtime"] { assert!(stdout.contains(name), "the script names {name}: {stdout}"); } + assert!(stdout.contains("CREATE DATABASE \"documents\""), "{stdout}"); assert!(stdout.contains("CREATE ROLE"), "{stdout}"); assert!(stdout.contains("\\password"), "{stdout}"); for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { @@ -197,4 +198,111 @@ fn both_administrator_flags_are_refused() { ); assert!(output.stdout.is_empty(), "{arguments:?}"); } + // A missing administrator flag is a usage error of the provision verb, + // not clap's answer to an unknown verb. + let stderr = + String::from_utf8(ctl(&["provision", "--runtime-config", &runtime]).stderr).unwrap(); + assert!(stderr.contains("--admin-url"), "{stderr}"); + assert!(!stderr.contains("unrecognized subcommand"), "{stderr}"); + let stderr = String::from_utf8( + ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "DOCUMENTS_ADMIN_URL", + ]) + .stderr, + ) + .unwrap(); + assert!( + stderr.contains("conflicting use of --admin-url-file"), + "{stderr}" + ); +} + +/// The first diagnostic of a refused `provision --print-sql` over `runtime`, +/// after checking the exit status and that no password reached either stream. +fn loader_refusal(runtime: &str) -> serde_json::Value { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(1), "{stdout}{stderr}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!( + !stdout.contains(secret) && !stderr.contains(secret), + "a refusal holds no password" + ); + } + let report: serde_json::Value = + serde_json::from_str(&stdout).unwrap_or_else(|error| panic!("{error}: {stdout}{stderr}")); + report["diagnostics"][0].clone() +} + +#[test] +fn a_missing_database_secret_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!( + diagnostic["path"], "/database/runtimeUrlRef", + "{diagnostic}" + ); +} + +#[test] +fn a_database_secret_that_is_not_text_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let secret = directory.path().join("secrets/migration-database-url"); + std::fs::write(&secret, [0xff, 0xfe, 0xfd]).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!( + diagnostic["path"], "/database/migrationUrlRef", + "{diagnostic}" + ); +} + +#[test] +fn a_missing_ca_bundle_secret_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let text = std::fs::read_to_string(&runtime) + .unwrap() + .replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/database-ca\n", + ); + std::fs::write(&runtime, text).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!(diagnostic["path"], "/database/caBundleRef", "{diagnostic}"); +} + +#[test] +fn a_runtime_file_the_runtime_refuses_is_refused_with_its_diagnostic() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let text = std::fs::read_to_string(&runtime).unwrap().replace( + "allowedClients: [civil-registry-app]", + "allowedClients: unrestricted", + ); + std::fs::write(&runtime, text).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!( + diagnostic["code"], "documents.runtime.allowed-clients-required", + "{diagnostic}" + ); } diff --git a/crates/registry-documentsctl/tests/provision_postgres.rs b/crates/registry-documentsctl/tests/provision_postgres.rs index 1cd7c60b54..87da3f1be9 100644 --- a/crates/registry-documentsctl/tests/provision_postgres.rs +++ b/crates/registry-documentsctl/tests/provision_postgres.rs @@ -257,6 +257,12 @@ async fn provision_then_apply_then_serve_with_split_roles() { admin_file.to_str().unwrap(), ]); assert_eq!(code, 0, "a second run converges: {again:#}"); + for statement in again["statements"].as_array().unwrap() { + assert_ne!( + statement["outcome"], "created", + "a second run creates nothing: {statement}" + ); + } let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); assert_eq!(code, 0, "{applied:#}"); diff --git a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs index 8092ac3f02..963bf9334e 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs @@ -480,7 +480,7 @@ async fn every_refusal_is_a_problem_document() { ), ]; for (refusal, status, title, code, challenged) in cases { - let response = server.refusal_response(refusal); + let response = server.refuse(refusal); assert_eq!(response.status().as_u16(), status, "{code}"); assert_eq!( response.headers().get(header::CONTENT_TYPE), @@ -566,7 +566,7 @@ async fn an_unreachable_key_set_is_the_operators_failure() { ); let logs = logs.text(); assert!( - logs.contains("the access-token key set is unavailable"), + logs.contains("\"failed_check\":\"key-source-unavailable\""), "{logs}" ); assert!(!logs.contains("citizen-a"), "{logs}"); diff --git a/crates/registry-mcp-edge/src/inbound.rs b/crates/registry-mcp-edge/src/inbound.rs index 776f086098..31a6b30fa4 100644 --- a/crates/registry-mcp-edge/src/inbound.rs +++ b/crates/registry-mcp-edge/src/inbound.rs @@ -1,6 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 -use std::{collections::HashSet, fmt, sync::Arc, time::Duration}; +use std::{ + collections::HashSet, + fmt, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; use axum::{ body::Body, @@ -29,6 +34,10 @@ use crate::server::{problem, METADATA_PREFIX}; const MAXIMUM_TOKEN_LIFETIME: Duration = Duration::from_secs(86_400); +/// The least time between two log lines for a request the gateway could not +/// admit because of its own fault. +const ADMIT_FAULT_LOG_WINDOW: Duration = Duration::from_secs(60); + /// Complete product-neutral inbound resource-server settings. #[derive(Clone, Debug)] pub struct ResourceServerOptions { @@ -251,6 +260,8 @@ pub struct ResourceServer { scope_challenge: String, metadata: Value, refusals: Arc, + /// When the gateway last logged that it could not admit a request. + admit_fault_logged: Mutex>, } #[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] @@ -308,6 +319,7 @@ impl ResourceServer { scope_challenge, metadata, refusals, + admit_fault_logged: Mutex::new(None), }) } @@ -336,10 +348,7 @@ impl ResourceServer { let token = bearer_token(headers)?; let verified = match self.verifier.verify(token).await { Ok(verified) => verified, - Err(error) if is_key_source_failure(&error) => { - tracing::warn!("the access-token key set is unavailable"); - return Err(Refusal::KeySource); - } + Err(error) if is_key_source_failure(&error) => return Err(Refusal::KeySource), Err(error) => return Err(Refusal::InvalidToken(error.failed_check())), }; let caller = self.caller(&verified, token)?; @@ -391,17 +400,36 @@ impl ResourceServer { } /// Counts and logs the refusal, then builds its answer. - fn refuse(&self, refusal: Refusal) -> Response { + pub(crate) fn refuse(&self, refusal: Refusal) -> Response { match refusal.failed_check() { Some(check) => record_refusal!(self.refusals, RefusalNote::new(check)), // The gateway could not derive a pseudonym or run its limiter. // That is a fault of this service, not a check a caller failed. - None => tracing::error!("the gateway could not admit a request"), + None => { + if self.admit_fault_due(Instant::now()) { + tracing::error!("the gateway could not admit a request"); + } + } } self.refusal_response(refusal) } - pub(crate) fn refusal_response(&self, refusal: Refusal) -> Response { + /// True at most once per `ADMIT_FAULT_LOG_WINDOW`, so a limiter that has + /// reached its capacity cannot write a line for every request. + fn admit_fault_due(&self, now: Instant) -> bool { + let mut last = self + .admit_fault_logged + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if last.is_some_and(|logged| now.saturating_duration_since(logged) < ADMIT_FAULT_LOG_WINDOW) + { + return false; + } + *last = Some(now); + true + } + + fn refusal_response(&self, refusal: Refusal) -> Response { let (status, challenge) = match refusal { Refusal::Missing(_) => (StatusCode::UNAUTHORIZED, Some(self.challenge.clone())), Refusal::InvalidToken(_) => ( @@ -489,6 +517,7 @@ fn limiter(options: TokenBucketOptions) -> Result Option { match self { Self::Missing(check) | Self::InvalidToken(check) => Some(check), diff --git a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs index abced72916..70b9d0ba3b 100644 --- a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs +++ b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs @@ -289,6 +289,12 @@ async fn drive() -> Run { bearer(&issue("another-host", RESOURCE, SCOPE, now() + 300)), ) .await; + run.observe( + "empty-subject", + &fresh(), + bearer(&auth.issue_access_token(CLIENT, "", RESOURCE, SCOPE, now() + 300)), + ) + .await; run.observe( "expired", &fresh(), @@ -362,13 +368,10 @@ async fn summarise(response: axum::response::Response) -> Value { header::RETRY_AFTER, ] { if let Some(value) = response.headers().get(&name) { - // The delay depends on the clock, so only its presence is frozen. - let text = if name == header::RETRY_AFTER { - "present".to_owned() - } else { - value.to_str().expect("ASCII header").to_owned() - }; - readable.insert(name.as_str().to_owned(), text); + readable.insert( + name.as_str().to_owned(), + value.to_str().expect("ASCII header").to_owned(), + ); } } let bytes = axum::body::to_bytes(response.into_body(), 1 << 20) @@ -391,7 +394,7 @@ async fn every_refusal_answers_exactly_as_the_golden_file_records() { } /// The check each refusal counts, one request each. -const COUNTED: [(&str, &str); 15] = [ +const COUNTED: [(&str, &str); 16] = [ ("no-authorization-header", "credential-missing"), ("non-bearer-scheme", "credential-missing"), ("bearer-without-token", "credential-malformed"), @@ -401,6 +404,7 @@ const COUNTED: [(&str, &str); 15] = [ ("not-a-jwt", "credential-malformed"), ("wrong-audience", "token-audience"), ("client-not-allowed", "token-client"), + ("empty-subject", "token-claims"), ("expired", "token-time"), ("scope-missing", "scope"), ("host-not-admitted", "host-origin"), @@ -418,6 +422,37 @@ async fn each_refusal_counts_once_under_its_check() { } } +#[tokio::test(flavor = "current_thread")] +async fn a_refused_host_writes_one_line_with_its_check() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + + let logs = CapturedDiagnosticLogs::default(); + let auth = authorization().await; + let (app, _) = application(&auth, auth.jwks_uri(), 100); + let response = app + .oneshot( + Request::post("/mcp") + .header(header::HOST, "attacker.example.test") + .body(Body::empty()) + .expect("request"), + ) + .with_subscriber(logs.subscriber()) + .await + .expect("response"); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let text = logs.text(); + let lines: Vec<&str> = text + .lines() + .filter(|line| line.contains("request refused")) + .collect(); + assert_eq!(lines.len(), 1, "{text}"); + assert!( + lines[0].contains("\"failed_check\":\"host-origin\""), + "{text}" + ); +} + #[tokio::test(flavor = "current_thread")] async fn a_refusal_writes_one_line_with_its_check_and_no_caller_value() { use registry_platform_testing::CapturedDiagnosticLogs; @@ -444,3 +479,13 @@ async fn a_refusal_writes_one_line_with_its_check_and_no_caller_value() { assert!(!text.contains(canary), "{canary} reached the log: {text}"); } } + +#[tokio::test(flavor = "current_thread")] +async fn the_admit_fault_line_is_due_once_per_window() { + let auth = authorization().await; + let (_, server) = application(&auth, auth.jwks_uri(), 100); + let start = std::time::Instant::now(); + assert!(server.admit_fault_due(start)); + assert!(!server.admit_fault_due(start + Duration::from_secs(59))); + assert!(server.admit_fault_due(start + Duration::from_secs(61))); +} diff --git a/crates/registry-mcp-edge/tests/golden/refusals.json b/crates/registry-mcp-edge/tests/golden/refusals.json index 6b9a6a6e00..08cc728546 100644 --- a/crates/registry-mcp-edge/tests/golden/refusals.json +++ b/crates/registry-mcp-edge/tests/golden/refusals.json @@ -44,6 +44,21 @@ }, "status": 401 }, + "empty-subject": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, "expired": { "body": { "code": "invalid-token", @@ -157,7 +172,7 @@ "headers": { "cache-control": "no-store", "content-type": "application/problem+json", - "retry-after": "present" + "retry-after": "60" }, "status": 429 }, diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index c723922ab6..f84f3e7718 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -61,7 +61,16 @@ pub(crate) async fn verifier( } registry_platform_config::JwksSource::Static { document_ref } => { let bytes = crate::runtime::resolve_secret(runtime, document_ref)?; - let keys = registry_platform_oidc::parse_static_jwks(&bytes).map_err(|_| refuse())?; + let keys = + registry_platform_oidc::parse_static_jwks(&bytes).map_err(|error| match error { + OidcError::StaticKeySet(refused) => RenderProblem::new( + ProblemKind::RuntimeInvalid, + format!( + "authentication.oidc.jwksSource.documentRef was refused: {refused}" + ), + ), + _ => refuse(), + })?; JwksFetcher::new_static(keys, JwksFetcherConfig::defaults()) } }; @@ -90,6 +99,7 @@ pub(crate) enum AuthenticationError { impl AuthenticationError { /// The check that refused the caller. A key source that cannot answer is /// the verifier's own outage. + #[deny(clippy::wildcard_enum_match_arm)] pub(crate) fn failed_check(&self) -> FailedCheck { match self { Self::Refused(check) | Self::Forbidden { check, .. } => *check, @@ -99,21 +109,10 @@ impl AuthenticationError { } fn verifier_failure(error: OidcError) -> AuthenticationError { - let check = error.failed_check(); - match error { - OidcError::Transport(_) - | OidcError::BoundedRead(_) - | OidcError::FetchUrl(_) - | OidcError::HttpStatus(_) - | OidcError::InvalidUrl - | OidcError::Parse - | OidcError::InvalidJwk - | OidcError::EmptyKeySet - | OidcError::MissingIssuer - | OidcError::ConflictingEndpointConfiguration - | OidcError::InsecureHttpRequiresOptIn - | OidcError::EndpointRefused { .. } => AuthenticationError::Unavailable, - _ => AuthenticationError::Refused(check), + if error.is_key_source_unavailable() { + AuthenticationError::Unavailable + } else { + AuthenticationError::Refused(error.failed_check()) } } @@ -336,4 +335,76 @@ pub(crate) mod tests { assert_eq!(verified.client_id.as_deref(), client); } } + + /// Builds the verifier from a runtime file whose static key set is `keys`. + async fn verifier_over_static_keys( + keys: &Value, + ) -> Result, RenderProblem> { + use std::os::unix::fs::PermissionsExt; + let scratch = tempfile::tempdir().expect("home directory"); + let home = scratch + .path() + .canonicalize() + .expect("physical home directory"); + std::fs::create_dir(home.join("bundle")).expect("package directory"); + std::fs::create_dir(home.join("audit")).expect("audit directory"); + let key_file = home.join("jwks.json"); + std::fs::write(&key_file, keys.to_string()).expect("write the key set"); + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + let runtime = format!( + "apiVersion: {}\nkind: {}\nlistener:\n bind: 127.0.0.1:18080\npackage:\n root: {}\nsecretProviders:\n file:\n root: {}\nauthentication:\n oidc:\n issuer: https://issuer.example.test\n audience: urn:render:test\n allowedClients: [portal]\n jwksSource:\n type: static\n documentRef: secret:file/jwks.json\naudit:\n path: {}\n", + crate::runtime::RUNTIME_API_VERSION, + crate::runtime::RUNTIME_KIND, + home.join("bundle").display(), + home.display(), + home.join("audit").join("render.jsonl").display(), + ); + let path = home.join("runtime.yaml"); + std::fs::write(&path, runtime).expect("write the runtime file"); + let (runtime, _) = crate::runtime::load(&path).expect("the runtime file loads"); + verifier(&runtime).await + } + + fn ec_public_key() -> Value { + let set = registry_platform_testing::TokenSigner::new().public_key_set(); + set["keys"] + .as_array() + .expect("a key set lists keys") + .iter() + .find(|key| key["kty"] == "EC") + .expect("the corpus holds an EC key") + .clone() + } + + #[tokio::test] + async fn a_static_key_set_with_unknown_public_members_loads() { + let mut key = ec_public_key(); + key["ext"] = json!(true); + let verifier = verifier_over_static_keys(&json!({ "keys": [key] })) + .await + .expect("a public member the verifier does not read is ignored"); + assert!(verifier.is_some()); + } + + #[tokio::test] + async fn a_static_key_set_with_a_private_member_is_refused_with_the_reason() { + let mut key = ec_public_key(); + key["d"] = json!("private"); + let problem = match verifier_over_static_keys(&json!({ "keys": [key] })).await { + Err(problem) => problem, + Ok(_) => panic!("a key set holding a private member must be refused"), + }; + assert_eq!(problem.kind, ProblemKind::RuntimeInvalid); + assert!( + problem.detail.contains("private-key member \"d\""), + "the detail names the refused member: {}", + problem.detail + ); + assert!( + problem.detail.contains("authentication.oidc.jwksSource"), + "the detail names the setting: {}", + problem.detail + ); + } } diff --git a/crates/registry-render/src/metrics.rs b/crates/registry-render/src/metrics.rs index 2415356a63..ff67b247ec 100644 --- a/crates/registry-render/src/metrics.rs +++ b/crates/registry-render/src/metrics.rs @@ -5,8 +5,9 @@ //! reaching the series requires reaching a different, private address. //! //! Every label is closed by construction. `operation` is `render` or `seal`, -//! `result` is a coarse status class, and `seal` is a seal id the operator -//! wrote in the runtime file, so the set is bounded by that file. Document +//! `result` is a coarse status class, `check` is one of the shared refusal +//! checks, and `seal` is a seal id the operator wrote in the runtime file, so +//! the set is bounded by that file. Document //! data, caller identities, request paths and problem details never become //! labels. //! diff --git a/crates/registry-render/src/server.rs b/crates/registry-render/src/server.rs index 6357245be4..510062c135 100644 --- a/crates/registry-render/src/server.rs +++ b/crates/registry-render/src/server.rs @@ -1207,23 +1207,45 @@ struct SealCall { } impl SealCall { - /// Refuse the call before any render starts: one response entry naming - /// the seal when it is known, accepted before responding. + /// Refuse the call before any render starts for a reason that is not a + /// caller refusal: one response entry naming the seal when it is known, + /// accepted before responding. A 401 or 403 goes through `refuse_checked`, + /// so every refused caller carries the check that refused it. async fn refuse(&self, service: &Service, problem: RenderProblem) -> Response { - self.refuse_checked(service, problem, None).await + debug_assert!( + !matches!(problem.kind.http_status(), 401 | 403), + "a refused caller is answered by refuse_checked" + ); + match self.audit_refusal(service, &problem).await { + Ok(()) => problem_response(&problem, self.trace.as_deref()), + Err(answer) => answer, + } } /// Refuse the call as `refuse` does, and record the check that refused - /// the caller when there is one. + /// the caller. async fn refuse_checked( &self, service: &Service, problem: RenderProblem, - check: Option, + check: FailedCheck, ) -> Response { + match self.audit_refusal(service, &problem).await { + Ok(()) => refusal_response(&problem, self.trace.as_deref(), check), + Err(answer) => answer, + } + } + + /// Write the refusal's response entry. When the audit write fails the + /// answer is the audit failure. + async fn audit_refusal( + &self, + service: &Service, + problem: &RenderProblem, + ) -> Result<(), Response> { let mut event = RenderAuditEvent::refused( &self.document_type, - &problem, + problem, &self.caller, self.correlation.as_deref(), self.trace.as_deref(), @@ -1231,13 +1253,11 @@ impl SealCall { if let Some(seal_id) = &self.seal_id { event = event.for_seal(seal_id, self.test_only); } - if let Err(audit_problem) = service.audit.response(&self.envelope, event).await { - return problem_response(&audit_problem, self.trace.as_deref()); - } - match check { - Some(check) => refusal_response(&problem, self.trace.as_deref(), check), - None => problem_response(&problem, self.trace.as_deref()), - } + service + .audit + .response(&self.envelope, event) + .await + .map_err(|audit_problem| problem_response(&audit_problem, self.trace.as_deref())) } } @@ -1314,7 +1334,7 @@ async fn seal_route( format!("the verified client is not in signing.seals.{seal_id}.allowedClients"), ); return call - .refuse_checked(&service, problem, Some(FailedCheck::RequesterClient)) + .refuse_checked(&service, problem, FailedCheck::RequesterClient) .await; } seal.recover_signer().await; @@ -2702,11 +2722,20 @@ mod tests { "cache-control", "retry-after", ] { - if let Some(value) = response.headers().get(name) { - headers.insert( - name.to_owned(), - value.to_str().expect("ASCII header").into(), - ); + let values: Vec = response + .headers() + .get_all(name) + .iter() + .map(|value| value.to_str().expect("ASCII header").into()) + .collect(); + match values.len() { + 0 => {} + 1 => { + headers.insert(name.to_owned(), values[0].clone()); + } + _ => { + headers.insert(name.to_owned(), values.into()); + } } } let bytes = axum::body::to_bytes(response.into_body(), 16384) @@ -2721,11 +2750,14 @@ mod tests { fn bearer_request( method: Method, uri: &str, - credential: Option, + authorization: &[Vec], ) -> axum::extract::Request { let mut request = axum::http::Request::builder().method(method).uri(uri); - if let Some(credential) = credential { - request = request.header(header::AUTHORIZATION, credential); + for value in authorization { + request = request.header( + header::AUTHORIZATION, + header::HeaderValue::from_bytes(value).expect("header value"), + ); } request .header(header::CONTENT_TYPE, "application/json") @@ -2810,7 +2842,8 @@ mod tests { mode: Mode, method: Method, uri: &'static str, - credential: Option, + /// The `Authorization` header values, in order. + authorization: Vec>, check: &'static str, } @@ -2828,12 +2861,22 @@ mod tests { mode, method, uri, - credential, + authorization: credential.into_iter().map(String::into_bytes).collect(), check, } } + + /// A case that sends the given `Authorization` header values as they + /// are, repeated or not ASCII included. + fn raw(mut self, authorization: Vec>) -> Self { + self.authorization = authorization; + self + } } + /// A client id no refusal answer or log line may repeat. + const CANARY_CLIENT: &str = "canary-client-0123456789"; + /// Every refusal the access layers and the seal handler make, with the /// check each one must record. fn refusal_cases() -> Vec { @@ -2863,6 +2906,32 @@ mod tests { Some("Bearer ".to_owned()), "credential-malformed", ), + RefusalCase::new( + "value-shorter-than-the-scheme", + Mode::Legacy, + Method::GET, + "/v1/documents", + Some("Basic".to_owned()), + "credential-malformed", + ), + RefusalCase::new( + "repeated-authorization-header", + Mode::Legacy, + Method::GET, + "/v1/documents", + None, + "credential-malformed", + ) + .raw(vec![b"Bearer first".to_vec(), b"Bearer second".to_vec()]), + RefusalCase::new( + "non-ascii-authorization-header", + Mode::Legacy, + Method::GET, + "/v1/documents", + None, + "credential-malformed", + ) + .raw(vec![b"Bearer caf\xe9".to_vec()]), RefusalCase::new( "legacy-key-mismatch", Mode::Legacy, @@ -2903,6 +2972,14 @@ mod tests { token_header(serde_json::json!({"client_id":"other"})), "token-client", ), + RefusalCase::new( + "token-client-canary", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"client_id":CANARY_CLIENT})), + "token-client", + ), RefusalCase::new( "scope-on-render-route", Mode::Oidc, @@ -2957,13 +3034,13 @@ mod tests { mode, method, uri, - credential, + authorization, .. } in refusal_cases() { let service = refusal_service(mode).await; let response = refusal_stack(service, &Arc::new(Metrics::default())) - .oneshot(bearer_request(method, uri, credential)) + .oneshot(bearer_request(method, uri, &authorization)) .await .expect("router"); answers.insert(name.to_owned(), frozen_answer(response).await); @@ -3022,13 +3099,14 @@ mod tests { "canary-wrong-key-0123456789abcdef0123456789", "canary-invalid-token", "canary-principal", + CANARY_CLIENT, ]; for RefusalCase { name, mode, method, uri, - credential, + authorization, check, } in refusal_cases() { @@ -3042,7 +3120,7 @@ mod tests { let service = refusal_service(mode).await; let metrics = Arc::new(Metrics::default()); let response = refusal_stack(Arc::clone(&service), &metrics) - .oneshot(bearer_request(method, uri, credential)) + .oneshot(bearer_request(method, uri, &authorization)) .await .expect("router"); let trace = registry_platform_httpsec::response_trace_id(response.headers()) @@ -3062,6 +3140,16 @@ mod tests { "{name}" ); let written = String::from_utf8(logs.0.lock().expect("log").clone()).expect("UTF-8"); + // The whole bearer value of a signed token never reaches a log line. + for value in &authorization { + if let Some(token) = value + .strip_prefix(b"Bearer ") + .filter(|token| token.len() > 40) + { + let token = String::from_utf8_lossy(token); + assert!(!written.contains(token.as_ref()), "{name}: {written}"); + } + } let lines: Vec = written .lines() .map(|line| serde_json::from_str::(line).expect("JSON log line")) diff --git a/crates/registry-render/tests/golden/authentication_refusals.json b/crates/registry-render/tests/golden/authentication_refusals.json index 8dfc7162c8..b33ac551e1 100644 --- a/crates/registry-render/tests/golden/authentication_refusals.json +++ b/crates/registry-render/tests/golden/authentication_refusals.json @@ -87,6 +87,21 @@ }, "status": 401 }, + "non-ascii-authorization-header": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, "render-scope-on-seal-route": { "body": { "code": "render.forbidden", @@ -101,6 +116,21 @@ }, "status": 403 }, + "repeated-authorization-header": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, "scheme-not-bearer": { "body": { "code": "render.unauthorized", @@ -174,6 +204,21 @@ }, "status": 401 }, + "token-client-canary": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, "token-expired": { "body": { "code": "render.unauthorized", @@ -188,5 +233,20 @@ "www-authenticate": "Bearer" }, "status": 401 + }, + "value-shorter-than-the-scheme": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 } } diff --git a/crates/registry-render/tests/serve.rs b/crates/registry-render/tests/serve.rs index 4525a5adbd..be455ae0a2 100644 --- a/crates/registry-render/tests/serve.rs +++ b/crates/registry-render/tests/serve.rs @@ -405,6 +405,10 @@ fn the_metrics_listener_serves_the_series_and_the_api_listener_does_not() { body.contains("render_documents_total{operation=\"render\",result=\"refused\"} 1"), "{body}" ); + assert!( + body.contains("render_request_refusals_total{check=\"credential-missing\"} 1"), + "{body}" + ); assert!( body.contains("\nrender_audit_write_failures_total 0\n"), "{body}" diff --git a/docs/site/src/content/docs/configure/breg-mcp.mdx b/docs/site/src/content/docs/configure/breg-mcp.mdx index 071fcee6ab..3200843698 100644 --- a/docs/site/src/content/docs/configure/breg-mcp.mdx +++ b/docs/site/src/content/docs/configure/breg-mcp.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-10-17" +last_reviewed: "2026-11-27" doc_type: reference locale: en standards_referenced: [] @@ -517,7 +517,9 @@ standard error from `breg-review`, so collect both. | Service | Level | Message | |---|---|---| | `breg-mcp` | info | `tool call`, with `request_id`, `tool`, and `outcome` | -| `breg-mcp` | warn | `the access-token key set is unavailable` | +| `breg-mcp` | info | `request refused`, with `failed_check` (the check that refused the request) and `suppressed`. At most five lines per check per minute | +| `breg-mcp` | error | `the gateway could not admit a request`, at most once a minute | +| `breg-mcp` | error | `the static key set was refused`, with the reason, at startup | | `breg-mcp` | error | `tool audit request refused` or `tool audit response refused` | | `breg-review` | warn | `a rate limit refused a request` | | `breg-review` | warn | `the registry declined a review request` or `the registry could not answer a review` | @@ -528,7 +530,9 @@ Neither service logs a token, secret, cookie, or field value. {/* Evidence: crates/registry-breg-mcp/src/main.rs, LOG_VARIABLE, main; crates/registry-breg-review/src/main.rs, LOG_VARIABLE; crates/registry-breg-mcp/src/gateway.rs, call; - crates/registry-mcp-edge/src/inbound.rs, authenticate; + crates/registry-mcp-edge/src/inbound.rs, authenticate, refuse; + crates/registry-mcp-edge/src/server.rs, require_resource_host; + crates/registry-breg-mcp/src/runtime.rs, static_key_fetcher; crates/registry-breg-review/src/pages.rs, review, submit; crates/registry-breg-review/src/lib.rs, Problem. */} diff --git a/docs/site/src/content/docs/operate/breg-monitor.mdx b/docs/site/src/content/docs/operate/breg-monitor.mdx index fe3a18029f..4b2b93b930 100644 --- a/docs/site/src/content/docs/operate/breg-monitor.mdx +++ b/docs/site/src/content/docs/operate/breg-monitor.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-10-17" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -161,11 +161,12 @@ curl -s http://127.0.0.1:9464/metrics ``` After one readiness probe and two requests without a token, the scrape held these samples (help -text and histogram lines omitted): +text and histogram lines omitted, and the other 44 `breg_request_refusals_total` checks showing 0): ```text breg_http_requests_total{route="/ready",method="GET",status="success"} 1 breg_http_requests_total{route="/v1/records/facilities",method="GET",status="client-error"} 2 +breg_request_refusals_total{check="credential-missing"} 2 breg_pool_connections{state="maximum-size"} 4 breg_pool_connections{state="size"} 3 breg_pool_connections{state="available"} 3 @@ -340,23 +341,26 @@ with one of the `breg.external-refresh.*` codes in [Troubleshooting](#troublesho ## Watch refused requests -`breg_request_refusals_total{check}` counts every request BReg refused, by the check that refused +`breg_request_refusals_total{check}` counts the requests BReg refused, by the check that refused it, since the process started. Every `check` value is published from the first scrape at zero, so a rate needs no `absent()` guard. A missing or refused credential, a refused token, an unreachable key source and a refused review completion callback all count. So does a request answered `404 resource.not_found` because the caller may not see the target (a missing scope or purpose, a row outside the caller's boundary, a refused task grant, a field beyond the profile), and a write -refused as outside the caller's boundary. +refused as outside the caller's boundary. A batch of Proposal review contexts answers `200`, and +each concealed item counts once under its own check. A generic `412` precondition answer, which also +covers a stale version, and a request for an unknown route are not counted. -Each refusal also writes one `request refused` line with `failed_check` and the request's trace id, -at most five lines per check per minute across the process. The next line for that check carries +Each refusal also writes one `request refused` line at `INFO` level with `failed_check` and the +request's trace id, at most five lines per check per minute across the process. At `BREG_LOG=warn` +no line is written, and the counter still counts. The next line for that check carries `suppressed`, the number of refusals the minute counted but did not log, so alert on the counter, not the log. The counter and the line carry only a fixed check name, never a token, claim, client or subject value. Counting changes nothing the caller receives. A rising `credential-missing` or `credential-malformed` count usually means a caller sends no -token or a broken one. A rising `key-source-unavailable` count means BReg cannot read its signing -keys; check the issuer before the callers. +token or a broken one. A rising `key-source-unavailable` count means BReg cannot read or use the +issuer's keys; check the issuer before the callers. {/* Evidence: crates/registry-breg/src/correlation.rs, finish_response(); crates/registry-breg/src/metrics.rs, @@ -461,7 +465,7 @@ Find the code the command, log, or HTTP problem printed. A `*` stands for any pa | `apply.successor.roles-differ` | The file names other roles than the active activation. | Apply the active package under the new roles, then the successor. | | `startup.audit.refused` | The audit destination or hash key was refused. | Secret files are regular, owned by the running user, mode `0400` or `0600`, with one link. The audit directory and its files are owned by the running user, the directory `0700`. | | `startup.cursor.refused` | The cursor secret was refused. | As above. | -| `startup.oidc.refused` | The issuer's key set could not be loaded. | Check that this host reaches and trusts the issuer. | +| `startup.oidc.refused` | The issuer's key set could not be loaded, or a pinned static key set was refused. | Check that this host reaches and trusts the issuer. For a pinned key set, the message names the rule and the key's position: correct that key. | | `authentication.refused` | A token was refused. | Check [what a token must carry](../breg/#what-a-token-must-carry); `aud` may be a list of up to 16 that includes the audience. | | `breg.runtime.invalid-metrics-listener` | `metricsListener.bind` is invalid. | See [Scrape metrics](#scrape-metrics). | | `postgres.connections.pool-over-half` | One pool may take over half the connections. | Lower the pool or raise `max_connections`. | diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index 3cdce92c39..94c45e54cd 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-09-28" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -80,59 +80,6 @@ root read-only, and give the audit directory durable writable storage. {/* Evidence: crates/registry-casework/install.sh; release/docker/Dockerfile.casework, ENTRYPOINT and CMD. */} -## Provision PostgreSQL - -Use a new database. Your runtime file names the roles, their passwords, and the database: they are -the URLs in `database.migrationUrlRef` and `database.runtimeUrlRef`, which -[the next section](#write-the-runtime-file) writes. Put both URLs in their secret files, then run -`caseworkctl provision` once as a PostgreSQL role that can create roles and databases: - -```sh -caseworkctl provision --runtime-config runtime.yaml --admin-url-file admin-url -``` - -The `admin-url` file holds one PostgreSQL URL for that administrator, for example -`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and -`CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, -use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set -`database.caBundleRef` in the runtime file to trust a private CA. The command never prints the -administrator URL or a password. - -The command: - -- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. -- Creates the database and closes it to `PUBLIC`. -- Grants both roles `CONNECT` on the database. -- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it - from `PUBLIC`. - -Run it again at any time. It creates only what is missing and refuses a role that exists with -different attributes. When both URLs name one role, it creates that one role and the deployment -records single-role mode. - -If a database administrator must run the SQL, add `--print-sql` and leave out the administrator -flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a -`\password` line that prompts for the password in `psql`, so the script holds no password. - -{/* Evidence: crates/registry-caseworkctl/src/provision.rs; crates/registry-platform-provision/src/plan.rs, - SchemaLayout::PublicForMigration; crates/registry-caseworkctl/tests/provision.rs. */} - -Each runtime holds up to 32 connections and waits up to 5 seconds for one; neither is configurable, -so allow 32 connections per replica. - -{/* Evidence: crates/registry-casework/src/store.rs, max_size(32) and wait_timeout. */} - -Only `caseworkctl apply` uses the migration credential, so keep it off the serving host. Apply -grants the runtime role what it serves with and keeps the activation ledger read-only to it. - -If apply reports `casework.activation.role-mode-weakened`, make the ownership, privilege, or -trigger correction it names, then plan again; never give the runtime role ledger writes to get past -it. When both credentials name one role, the deployment records single-role mode, and `status` -says the runtime credential can activate packages. - -{/* Evidence: crates/registry-casework/src/activation.rs, grant_runtime_role(), observe_role(), and stray_authority(); - crates/registry-casework/src/store.rs, tcp_user_timeout. */} - ## Write the runtime file The runtime file is yours, kept apart from the authored policy. This one uses mounted secrets and @@ -240,6 +187,61 @@ Keep earlier package directories for recovery, and plan every activation, rollba {/* Evidence: crates/registry-casework/src/config.rs, verify_casework_package() and expected_digest; crates/registry-casework/src/config.rs, RuntimePackageConfig. */} +## Provision PostgreSQL + +Use a new database. Your runtime file names the roles, their passwords, and the database: they are +the URLs in `database.migrationUrlRef` and `database.runtimeUrlRef`, which +[the runtime file](#write-the-runtime-file) names. `caseworkctl provision` loads that file and +verifies the package it points at, so write the runtime file and verify the package first. Put both +URLs in their secret files, then run `caseworkctl provision` once as a PostgreSQL role that can +create roles and databases: + +```sh +caseworkctl provision --runtime-config runtime.yaml --admin-url-file admin-url +``` + +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and +`CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, +use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set +`database.caBundleRef` in the runtime file to trust a private CA. The command never prints the +administrator URL or a password. + +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema and the runtime role `USAGE` + on it, and takes `CREATE` on it from `PUBLIC`. + +Run it again at any time. It creates only what is missing and refuses a role that exists with +different attributes. When both URLs name one role, it creates that one role and the deployment +records single-role mode. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a +`\password` line that prompts for the password in `psql`, so the script holds no password. + +{/* Evidence: crates/registry-caseworkctl/src/provision.rs; crates/registry-platform-provision/src/plan.rs, + SchemaLayout::PublicForMigration; crates/registry-caseworkctl/tests/provision.rs. */} + +Each runtime holds up to 32 connections and waits up to 5 seconds for one; neither is configurable, +so allow 32 connections per replica. + +{/* Evidence: crates/registry-casework/src/store.rs, max_size(32) and wait_timeout. */} + +Only `caseworkctl apply` uses the migration credential, so keep it off the serving host. Apply +grants the runtime role what it serves with and keeps the activation ledger read-only to it. + +If apply reports `casework.activation.role-mode-weakened`, make the ownership, privilege, or +trigger correction it names, then plan again; never give the runtime role ledger writes to get past +it. When both credentials name one role, the deployment records single-role mode, and `status` +says the runtime credential can activate packages. + +{/* Evidence: crates/registry-casework/src/activation.rs, grant_runtime_role(), observe_role(), and stray_authority(); + crates/registry-casework/src/store.rs, tcp_user_timeout. */} + ## Refuse a package that strands pinned work An accepted review keeps the policy closure it was admitted under. A candidate that removes a @@ -270,7 +272,8 @@ Applying the package that is already active is refused with If apply returns `casework.activation.applied-unaudited`, the activation committed but its audit entry did not: restore audit, read `status`, and record the recovery. A runtime role that cannot -read the ledger gets `casework.activation.ledger-unreadable`; apply restores its grants. Exit codes +read the ledger gets `casework.activation.ledger-unreadable`; apply restores its grants. `USAGE` on +`public` comes from `provision`, so run `provision` again if the runtime role lost it. Exit codes are `0` for success, `1` for a refusal, `2` for usage, and `3` for an operational failure. Then serve as the runtime user: diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index 13f7a2b48c..0793be305a 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -260,7 +260,7 @@ Secret values never appear in a diagnostic or a log. Use PostgreSQL 17 or newer; `apply` and startup refuse an older server. `provision` creates what the two database URLs in your runtime file name: the migration role, the runtime role, and the database, and it lets only those two roles connect. -It takes the role names, the database name, and the passwords from `database.migrationUrlRef` and `database.runtimeUrlRef`, so you write each of them once. +It takes the role names, the database name, and the passwords from `database.migrationUrlRef` and `database.runtimeUrlRef`, so you write each of them once, except that when the runtime file has a `deployment` block, the user of the runtime URL must be `deployment.runtimeRole`: `provision` refuses a different user before it connects, with `coordinator.runtime-config.runtime-role-mismatch`. Run it as a PostgreSQL administrator that can create roles and databases (`CREATEROLE` and `CREATEDB`). It needs no superuser. @@ -646,8 +646,8 @@ curl -fsS http://127.0.0.1:8108/ready coordinatorctl doctor --url https://coordinator.example.org --token-file /run/operator-token ``` -`/health` answers `{"live":true}` while the process answers. -`/ready` answers `{"ready":true}`, or HTTP 503 with `{"ready":false}` while the service cannot accept work. +`/health` answers `{"live":true,"status":"ok"}` while the process answers. +`/ready` answers `{"ready":true,"status":"ready"}`, or HTTP 503 with `{"ready":false}` while the service cannot accept work. Every `/ready` probe checks mutable schema, activation, role, state-key custody, audit, and recovery holds; a held run does not make the service unready. The retained live-binding scan is coalesced and cached for 30 seconds, including failures. A cache miss still waits for that scan, so the cache bounds frequency rather than latency. @@ -767,7 +767,10 @@ They expose every label value from the first scrape. - An authentication refusal is a bearer credential refused before a caller is resolved. `refused` is a missing, malformed, or unverified token, or a completion event without a configured completion token and recipient binding. `policy` is a verified token no caller policy admits, and `unavailable` means the token verifier cannot answer. - A resolved caller refused an action is not counted here. + A resolved caller refused an action is not counted here, but `coordinator_request_refusals_total` counts it. +- `coordinator_request_refusals_total` counts every refused request under the check that refused it, and no label carries caller text. + It covers a refused credential, a policy denial after authentication, a refused signed event delivery or completion callback, a key source the service cannot reach or use (the token verifier's keys or the signed-event key), and a run the caller cannot see. + Each refusal also writes one `request refused` log line with `failed_check`, at most five per check per minute. `coordinator_dispatch_jobs` is read from the database on each scrape. `pending` steps wait for their next attempt, `leased` steps are being attempted, and `unknown` steps wait for an operator to settle an uncertain effect. @@ -799,7 +802,8 @@ Bind the metrics listener where only your monitoring can reach it: the counts de {/* Evidence: crates/registry-coordinator/src/metrics.rs coordinator_runs_admitted_total, coordinator_runs_finished_total, coordinator_step_attempts_total, - coordinator_authentication_refusals_total, coordinator_metrics_sample_failures_total, + coordinator_authentication_refusals_total, coordinator_request_refusals_total, + coordinator_metrics_sample_failures_total, coordinator_dispatch_jobs, coordinator_runs_attention, coordinator_runs_restore_review_required, coordinator_hold_active, coordinator_oldest_due_age_seconds; diff --git a/docs/site/src/content/docs/operate/documents.mdx b/docs/site/src/content/docs/operate/documents.mdx index 23d221a11f..9ffc312ca7 100644 --- a/docs/site/src/content/docs/operate/documents.mdx +++ b/docs/site/src/content/docs/operate/documents.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -54,8 +54,10 @@ The `admin-url` file holds one PostgreSQL URL for that administrator, for exampl `postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and `CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set -`database.caBundleRef` in the runtime file to trust a private CA. The command never prints the -administrator URL or a password. +`database.caBundleRef` in the runtime file to trust a private CA. The administrator URL must name the +same host and port as the two product URLs, and a database other than the product database, such +as `postgres`. The command refuses it otherwise. It never prints the administrator URL or a +password. The command: @@ -94,11 +96,13 @@ backup space above the database size. {/* Evidence: crates/registry-documents/migrations/0100_documents.sql, content bytea. */} -`provision` grants the runtime role nothing beyond `CONNECT`. `apply` grants it what serving needs, -and `serve` refuses a runtime role that holds authority over the schema. If the runtime role later loses `USAGE` on the -schema or read access to the activation ledger, `serve` refuses to start and the operator commands -answer `documentsctl.activation.ledger-unreadable` at `database.runtimeUrlRef`. Run `apply` again -with the migration credential to restore its grants. +`provision` grants the runtime role `CONNECT` on the database and `USAGE` on the `public` schema. +`apply` grants it the rest of what serving needs, and `serve` refuses a runtime role that holds +authority over the schema. If the runtime role later loses `USAGE` on the schema, run `provision` +again: it restores that grant, and `apply` does not. If the runtime role loses read access to the +activation ledger, `serve` refuses to start and the operator commands answer +`documentsctl.activation.ledger-unreadable` at `database.runtimeUrlRef`. Run `apply` again with the +migration credential to restore those grants. {/* Evidence: crates/registry-documents/src/activation.rs, apply (grant_runtime_role and stray_authority) and check_runtime; @@ -118,7 +122,7 @@ matter most: | `identity.databaseId` | A name for the one database this deployment owns. The service refuses a database recorded for another. | | `package.root` and `package.expectedDigest` | The package directory, and the digest `documentsctl package` printed. | | `database.caBundleRef` | The PEM bundle of the CA that signs the database certificate, when a private CA does. It replaces the system roots. | -| `authentication.oidc` | The `issuer`, the `audience` your tokens carry, every client in `allowedClients`, and `jwksSource` when the runtime should not fetch the issuer's keys itself. See [Access tokens](#access-tokens). | +| `authentication.oidc` | The `issuer`, the `audience` your tokens carry, `allowedClients` (a list that covers every client an access profile names, or `from-package`), and `jwksSource` when the runtime should not fetch the issuer's keys itself. See [Access tokens](#access-tokens). | | `storage.type` | `database` or `s3`. The first upload pins the choice: a later start under another backend or bucket is refused. | | `storage.maximumDocumentBytes` | The largest version the deployment takes: 16 MiB by default on both backends. On `s3` you may raise it up to 64 MiB. | | `contentVerification` | `type: http` with the verifier's `url`, `authorizationRef`, and `policyId`. `type: disabled` approves everything and is accepted only on a development loopback listener. | @@ -182,7 +186,8 @@ authentication: The secret holds a JSON Web Key Set of RSA or EC public keys, and every key needs its own non-empty `kid`: startup refuses a key without one, a repeated `kid`, and a symmetric key. It also refuses a key that carries a private member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth` or `k`) or a repeated -member name, and the startup error names the rule and the key's position, never a key value. Members +member name. The startup error names the rule it broke, and the key's position for a rule about one key, +never a key value. Members the runtime does not know, such as `x5c`, `x5t` or `ext`, are ignored. The set is read once at startup and never rotates, so to change keys, replace the secret and restart `serve`. @@ -286,10 +291,14 @@ documents --runtime-config /etc/registry-documents/runtime.yaml serve It logs JSON lines on standard error, starting with `the Document Store is serving` and the address. `DOCUMENTS_LOG` sets the level to `error`, `warn`, or `info`, the default; any other value -stops `documents serve` with exit status 2. The log has no line per request: a request is logged only when -something fails behind it, such as the database or the token verifier, or when its token lacks a -scope its profile requires. A refused request is explained by its problem response, and every -audited operation, such as an upload, a download, or a grant, is in the audit journal. +stops `documents serve` with exit status 2. A request that succeeds writes no log line. A refused request writes one +`request refused` line that names `failed_check`, at most five per check per minute, with `suppressed` +counting the rest, and `documents_request_refusals_total` counts every one (see +[Metrics](#watch-the-metrics)). A token verifier that cannot reach its key source answers 503 and is logged +the same way, as `request refused` with `failed_check` `key-source-unavailable`, not as a warning, so +`DOCUMENTS_LOG=warn` shows no line for it and the counter is the signal to alert on. A failure behind +a request, such as the database, is logged where it happens. Every audited operation, such as an +upload, a download, or a grant, is in the audit journal. `serve` never applies the schema. Before it connects to the database, it refuses a runtime file that `documentsctl check --project` refuses against the package's project, such as a hook diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 67f66a6117..879725f16a 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -160,12 +160,14 @@ A request batch audits both items as not available, and the metric still counts declared_existence_disclosure_mode_governs_the_public_collapse, a_declared_unresolved_problem_logs_a_cause_only_when_a_404_does_not_match_it. */} -BReg counts every refused request by the check that refused it, in `breg_request_refusals_total{check}` on the private metrics listener. +BReg counts each request it refuses by the check that refused it, in `breg_request_refusals_total{check}` on the private metrics listener. The `check` label is a closed set of 45 names, every one published at zero, and no caller value becomes a label. Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. A request that BReg answers `404 resource.not_found` because the caller may not see the target reads the same to the caller whatever the reason. The operator can tell the reasons apart: the counter holds the request under the rule that refused it, for example `scope`, `purpose`, `requester-client`, `row-boundary`, `task-grant-binding`, `disclosure` or `visibility`. A refused write the engine answers with `write.outside-boundary` counts under `row-boundary`, and a Proposal outside the caller's scope counts under `ownership`. +A batch of Proposal review contexts answers `200`, and each concealed item counts once under its own check. +A generic `412` precondition answer, which also covers a stale version, and a request for an unknown route are not counted. Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and recording a refusal changes nothing the caller receives. A `visibility` count is a record that is absent or outside the boundary, and BReg does not say which, so it also counts a caller probing for identifiers. The audit journal's `refusalReason` stays the three values it lists below. @@ -173,6 +175,8 @@ The audit journal's `refusalReason` stays the three values it lists below. {/* Evidence: crates/registry-breg/tests/concealment_refusals.rs, every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wire; crates/registry-breg/src/api/mod.rs, concealed(), refusal_check_tests; + crates/registry-breg/tests/postgres_proposal.rs, + review_context_projects_an_omitted_optional_input_as_null; crates/registry-breg/src/mutation.rs, MutationError::failed_check. */} ### Public check export @@ -508,13 +512,17 @@ The residuals refer to these obligations by number. Loopback HTTP is accepted for an issuer; anything else needs `authentication.oidc.allowInsecureHttp: true`, which is logged at startup and reported by `bregctl doctor` (`BREG-RES-17`). - Loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name `localhost` in any letter case, which BReg connects to only through the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. + For an issuer and for `listener.publicOrigin`, loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name `localhost` in any letter case, which BReg connects to only through the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. A pinned key set (`authentication.oidc.jwksSource.type: static`) holds public keys only. BReg refuses a key that carries a private or symmetric member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth`, `k`), a repeated member name, a missing or repeated `kid`, or a key that does not match `allowedAlgorithm`. - It ignores members it does not name, such as `x5c` or `ext`. - A refusal names the rule and the key's position, never a value. + It also requires `use` to be `sig` and `key_ops` to be `["verify"]` when a key carries either, + and refuses a denied `kid`, a `kid` over the bound and more than 128 keys. + It ignores other members it does not name, such as `x5c` or `ext`. + When the shared public-key rule refuses a key, the startup log and `bregctl doctor` name the rule + and, for a rule about one key, the key's position, never a value. + The algorithm, `use`, `key_ops`, `kid` and key-count rules name no position. {/* Evidence: crates/registry-breg/src/runtime_config.rs, PlaintextDatabase, validate_static_jwks, PublicOrigin::parse; crates/registry-breg/tests/runtime_config.rs, diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index 6cf76aa755..4694e1fc94 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -169,16 +169,22 @@ grants in [Registry Casework task grants](../../reference/casework-task-grants/) becomes a label. Refusals the caller cannot tell apart are told apart there. A review or administration request refused for its role, its profile's stage eligibility, an - earlier decision by the same person (separation of duties), a task the caller does not hold, a - task grant that is expired, invalidated or bound to another client, or a source that declines to - disclose, counts once under its own check. + earlier decision by the same person (separation of duties), moving or reading a task the caller + does not hold, a task grant that is expired, invalidated or bound to another client, or a source + that says the subject is not reviewable, counts once under its own check. + A source that declines to disclose a subject counts under `visibility`. + Deciding, drafting or releasing a task the caller does not hold answers 409 + `review.task-not-held` and is not counted. A target concealed as not found counts under `visibility`, or under the check that hid it. + An absence that conceals nothing, such as the task grant key set route when task grants are not + configured, an unknown holiday revision, or an unknown absence id, is not counted. Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and recording a refusal changes nothing the caller receives: the answer is the same - `operation.not-authorized` or `request.not-found` body as before. + `operation.not-authorized`, `request.not-found`, `review.distinct-approver-required` or + `review.initiator-excluded` body as before. {/* Evidence: crates/registry-casework/src/http.rs, impl From for HttpError; crates/registry-casework/src/review.rs, a_reviewer_who_already_acted_is_refused_for_separation_of_duties, diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index c691fa564b..1cabc6388c 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -43,8 +43,8 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ The `check` label is a closed set of 45 names, every one published at zero, and no caller value becomes a label. The counter covers a refused credential, a policy denial after authentication, a refused signed - event delivery or completion callback, an unreachable key source, and a run the caller cannot - see. + event delivery or completion callback, a key source the receiver cannot reach or use (the + access-token verifier's keys or the signed-event key), and a run the caller cannot see. Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. @@ -55,6 +55,10 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ machine. - PostgreSQL holds run, wait and job state. Coordinator does not defend against a database superuser. + Plaintext PostgreSQL is admitted only to a Unix socket, a loopback address literal or the name + `localhost`, in any letter case. + Coordinator matches `localhost` by spelling and does not pin its resolution, so a host that maps + that name elsewhere redirects the connection. {/* Evidence: crates/registry-coordinator/tests/external_command_project.rs the_workflow_cannot_name_a_destination_path_or_credential; @@ -68,7 +72,9 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ a_policy_denial_after_authentication_is_counted, the_authorization_header_names_a_missing_or_a_malformed_credential; crates/registry-coordinator/src/event_trigger_tests.rs - a_refused_delivery_names_the_check_that_failed; + a_refused_delivery_names_the_check_that_failed, + an_event_key_outage_answers_503_and_counts_as_a_key_source_outage, + a_verification_key_the_receiver_cannot_use_is_its_own_key_fault; crates/registry-coordinator/src/completion.rs a_refused_sender_names_the_check_that_failed. */} diff --git a/docs/site/src/content/docs/security/documents.mdx b/docs/site/src/content/docs/security/documents.mdx index 8082ca99d6..a60537dceb 100644 --- a/docs/site/src/content/docs/security/documents.mdx +++ b/docs/site/src/content/docs/security/documents.mdx @@ -39,7 +39,7 @@ and the restore drill is in A static key set (`jwksSource: static`) holds public keys only. The runtime refuses to start on a set that carries a private member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth` or `k`), a symmetric key, a repeated member name, or a key without a unique `kid`. - The startup error names the rule and the key's position, never a key value. + The startup error names the rule it broke, and the key's position for a rule about one key, never a key value. Members it does not know, such as `x5c` or `ext`, are ignored. - The operator's view of a refusal: the answer to the caller names a problem code and no cause, so an operator tells the causes apart from the private metrics listener and the log. diff --git a/docs/site/src/content/docs/security/render.mdx b/docs/site/src/content/docs/security/render.mdx index 4f015c1bbc..748af3d1e1 100644 --- a/docs/site/src/content/docs/security/render.mdx +++ b/docs/site/src/content/docs/security/render.mdx @@ -214,17 +214,19 @@ rules only. ## How refusals are recorded Render counts every refused request by the check that refused it, in -`render_request_refusals_total{check}` on the private metrics listener. +`render_request_refusals_total{check}`. The series is served on the private metrics listener when +`metricsListener` is set. Without it the counter still counts and the log line is the only signal. The `check` label is a closed set of 45 names, every one published at zero, and no caller value becomes a label. The counter covers a missing or malformed credential, a legacy API key mismatch, a token the -verifier refuses, an unreachable key source, a missing scope, the legacy key presented to the seal +verifier refuses, a key source Render cannot reach or use, a missing scope, the legacy key presented to the seal route, and a client that the seal's `allowedClients` does not list. Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and recording a refusal changes nothing the caller receives. +A refusal whose audit entry cannot be written is answered as an audit failure and is not counted. {/* Evidence: crates/registry-render/src/server.rs each_refusal_is_counted_and_logged_under_its_check, diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index bf8b1e882e..e455067d5b 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,20 +2,26 @@ ## Unreleased -- BReg counts every refused request by the check that refused it, in +- BReg counts the requests it refuses by the check that refused it, in `breg_request_refusals_total{check}`, published at zero for every check from - the first scrape. Each refusal writes one `request refused` line with - `failed_check` and the request's trace id, at most five lines per check per - minute. That line replaces the authentication refusal line that carried a - `stage` field. A request answered `404 resource.not_found` because the caller - may not see the target counts under the rule that hid it, and so does a write - refused as outside the caller's boundary. Refusal statuses, headers and bodies - are unchanged. + the first scrape. Each refusal writes one `request refused` line at `INFO` + level with `failed_check` and the request's trace id, at most five lines per + check per minute. That line replaces the authentication refusal line that + carried a `stage` field. A request answered `404 resource.not_found` because + the caller may not see the target counts under the rule that hid it, and so + does a write refused as outside the caller's boundary. A batch of Proposal + review contexts answers `200` and counts each concealed item once. An expired + task grant counts under `task-grant-expired`, a grant bound to another client + or resource under `task-grant-binding`, and a grant token with no `iat`, an + `iat` ahead of the clock or an `exp` not after `iat` under + `task-grant-claims`. A generic `412` precondition answer and an unknown route + are not counted. Refusal statuses, headers and bodies are unchanged. - The BReg MCP gateway and the review page read loopback the way every - other service does. Under `development-loopback`, plain HTTP to - `127.0.0.2`, `[::1]` or `[::ffff:127.0.0.1]` is accepted as well as - `127.0.0.1` and `localhost`. `localhost.` and `*.localhost` stay refused. A + other service does. Under `development-loopback`, plain HTTP to the + IPv4-mapped form of a loopback address, for example `[::ffff:127.0.0.1]`, is + now accepted. The rest of `127.0.0.0/8`, `[::1]` and `localhost` were already + accepted. `localhost.` and `*.localhost` stay refused. A static key set the BReg MCP gateway refuses is logged with the reason, and its startup code is unchanged. @@ -35,9 +41,13 @@ - A pinned static key set (`authentication.oidc.jwksSource.type: static`) follows the shared public-key rule every product uses. Members BReg does not name, such as `x5c` or `ext`, and members beside `keys` no longer refuse the - document. A private or symmetric key member, a repeated member name, and a - missing or repeated `kid` are still refused, and the startup refusal names - the rule and the key's position. A listener origin treats an IPv4-mapped + document. BReg still reads `use` and `key_ops`, and refuses a `use` other + than `sig` and a `key_ops` other than `["verify"]`. A private or symmetric + key member, a repeated member name, and a missing or repeated `kid` are still + refused. When the shared rule refuses a key set, the startup log and + `bregctl doctor` name the rule and, for a rule about one key, the key's + position, and the refusal keeps the `startup.oidc.refused` code. A listener + origin treats an IPv4-mapped loopback literal, such as `[::ffff:127.0.0.1]`, as loopback. - Refused Record file downloads use the same attachment audit operation as diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index a353b475d6..54c613a1fa 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -8,15 +8,27 @@ `failed_check` and the request's trace id, at most five lines per check per minute. That line replaces the authentication refusal line that carried a `stage` field. The count covers review, directory, clock and task-grant - refusals, each under the check its producer names. Refusal statuses, headers - and bodies are unchanged. -- A static key set with a private key member or a repeated member name is - refused at startup under `casework.runtime.unreadable-jwks-secret`, with the - rule it broke and the key's position, in place of - `casework.runtime-dependency.unavailable`. + refusals, each under the check its producer names. An absence that conceals + nothing, such as the task grant key set route when task grants are not + configured, is not counted. Refusal statuses, headers and bodies are + unchanged. +- A static key set with a private key member is refused at startup under + `casework.runtime.unreadable-jwks-secret`, with the rule it broke and the + key's position. Earlier releases loaded such a set, so remove private + members from the key set before upgrading. +- A static key set with a repeated member name is refused at startup under + `casework.runtime.unreadable-jwks-secret`, without a key position, in place + of `casework.runtime-dependency.unavailable`. - A review completion destination may use any loopback literal in plain `http`: `127.0.0.0/8`, `::1`, or an IPv4-mapped form of `127.0.0.0/8`. The name `localhost` stays refused. +- `caseworkctl provision` creates the migration role, the runtime role and the + database from the two URLs in the runtime file, so each credential is + written once. It connects with an administrator URL from + `--admin-url-file` or `--admin-url-env` over verified TLS, or prints the SQL + with `--print-sql` and connects to nothing. Run it again at any time: it + creates only what is missing and refuses a role that exists with different + attributes. It loads the whole runtime file and verifies the package first. - `GET /health` answers `{"status":"ok"}` and `GET /ready` answers `{"status":"ready"}` as `application/json`, in place of an empty 200. Both diff --git a/products/casework/contracts/security-invariant-matrix.yaml b/products/casework/contracts/security-invariant-matrix.yaml index f5f7f1f72f..9821f35193 100644 --- a/products/casework/contracts/security-invariant-matrix.yaml +++ b/products/casework/contracts/security-invariant-matrix.yaml @@ -37,7 +37,7 @@ invariants: - {id: CASEWORK-SEC-31, invariants: [9, 17], state: enforced, targetWave: beta, threat: "A reviewer's private reason or an advisory finding reaches the producer or audit journal, or a decision uses an outcome outside its stage or one another approver in its stage did not choose.", enforcementPoint: "The frozen policy catalogue, current stage's outcome subset, per-outcome publicReason rule and stage outcome agreement are checked in the decision transaction; result built only from the settling decision; audit allow-list carries publicReasonGiven.", refusal: "Refuse undeclared or unavailable outcomes, an approval naming another outcome than its stage already chose, and missing, undeclared or oversized public reasons; never copy a private reason or advisory payload into the producer result or audit.", negativeId: CASEWORK-NEG-31, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: advisory_rejection_advances_to_final_approval_without_releasing_its_reason}} - {id: CASEWORK-SEC-32, invariants: [5, 9, 17], state: enforced, targetWave: beta, threat: "A retained terminal Casework read leaks source context after the source conceals it, or loses the Casework-owned decision with that context; or, once the source stops calling the subject reviewable, it releases still-disclosed context to anyone other than the author of that task's decision on a request that has left review.", enforcementPoint: "Separate live source context disclosure from retained terminal task and history authorization. For a still-disclosed but non-reviewable subject, release context only once the request has left review, only to the recorded author of that task's decision, with authorship and current Casework membership, profile and retention checked before the provider read and re-checked after it; the source decides disclosure for the caller's own token and source profile in that read.", refusal: "Release only Casework-owned retained records under current Casework authority; keep concealed source context not found; keep non-reviewable context not found for other reviewers, for the authors of other tasks and for any author while the request is still reviewing; refuse expired or erased results as expired.", negativeId: CASEWORK-NEG-32, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: decided_current_source_context_is_retained_only_for_its_author}} - {id: CASEWORK-SEC-33, invariants: [4, 5, 9, 17], state: enforced, targetWave: beta, threat: "Task-grant evaluation borrows another source profile or accepts substituted request identity or unrequested source fields.", enforcementPoint: "Separately selected BReg task-context service profile, exact request echo and policy/subject/context binding, field-limited schema and current source disclosure.", refusal: "Refuse missing task profile, status or human-context fallback, malformed requests, mismatched responses and unrequested fields before deriving task authority; RoutingContext remains unsupported.", negativeId: CASEWORK-NEG-33, negativeTest: {path: crates/registry-casework-breg/tests/context_provider.rs, name: task_context_uses_only_its_distinct_profile_and_echoes_the_exact_request}} - - {id: CASEWORK-SEC-34, invariants: [1, 3, 5, 9, 14, 17, 18], state: enforced, targetWave: beta, threat: "A gateway delegation impersonates a human, reads another person's assignment, reuses a cursor across reader policies, reaches a Casework mutation, promises current-source work without an exchange, leaks internal policy machinery, or leaks downstream failure values.", enforcementPoint: "Named delegated reader policy with exact client, actor subject, assertion issuer, audience, human assertion, required scope subset and lifetime; optional actor issuer must match the verified token issuer and nested actors are refused; delegated cursors are partitioned by reader policy; startup cross-check of policy-reachable current-source providers; dedicated read-only routes; one configured downstream request; one bulk post-source list recheck and before/after context holder and revision checks; model-visible context omits the internal policy closure while retaining the policy binding and review context; distinct OAuth clients separate unattended status authority from subject delegation; static gateway failure classes with a validated trace identifier; terminal minimized audit.", refusal: "Keep ordinary human authentication closed to delegated-reader act or scope, require source profiles and exchange only for policy-reachable current-source work, expose only assigned due list and assigned context without internal routing, clock or retention policy, expire cursors crossing reader policies, refuse changed holder/revision without probing or retrying, and withhold results until person plus gateway/client audit is accepted.", negativeId: CASEWORK-NEG-34, negativeTest: {path: crates/registry-casework/src/auth.rs, name: delegated_staff_read_negative_cases_have_value_free_stage_diagnostics}} + - {id: CASEWORK-SEC-34, invariants: [1, 3, 5, 9, 14, 17, 18], state: enforced, targetWave: beta, threat: "A gateway delegation impersonates a human, reads another person's assignment, reuses a cursor across reader policies, reaches a Casework mutation, promises current-source work without an exchange, leaks internal policy machinery, or leaks downstream failure values.", enforcementPoint: "Named delegated reader policy with exact client, actor subject, assertion issuer, audience, human assertion, required scope subset and lifetime; optional actor issuer must match the verified token issuer and nested actors are refused; delegated cursors are partitioned by reader policy; startup cross-check of policy-reachable current-source providers; dedicated read-only routes; one configured downstream request; one bulk post-source list recheck and before/after context holder and revision checks; model-visible context omits the internal policy closure while retaining the policy binding and review context; distinct OAuth clients separate unattended status authority from subject delegation; static gateway failure classes with a validated trace identifier; terminal minimized audit.", refusal: "Keep ordinary human authentication closed to delegated-reader act or scope, require source profiles and exchange only for policy-reachable current-source work, expose only assigned due list and assigned context without internal routing, clock or retention policy, expire cursors crossing reader policies, refuse changed holder/revision without probing or retrying, and withhold results until person plus gateway/client audit is accepted.", negativeId: CASEWORK-NEG-34, negativeTest: {path: crates/registry-casework/src/auth.rs, name: delegated_staff_read_negative_cases_name_their_check_and_write_no_log_line}} - {id: CASEWORK-SEC-35, invariants: [3, 9, 17], state: enforced, targetWave: beta, threat: "An applicant progress read exposes an internal stage or accepts progress for another request, subject, policy or submission.", enforcementPoint: "Explicit producer query, bounded policy-authored code from the accepted digest-pinned closure, reviewing-only projection and exact accepted tuple verification in the shared client.", refusal: "Omit progress on plain, unmapped and terminal reads; refuse malformed codes and every substituted accepted binding member.", negativeId: CASEWORK-NEG-35, negativeTest: {path: crates/registry-review-client/tests/http_boundary.rs, name: request_progress_rejects_each_substituted_binding_member}} - {id: CASEWORK-SEC-36, invariants: [3], state: enforced, targetWave: beta, threat: "Synthetic run preparation silently changes producer identity or broadens initiator trust.", enforcementPoint: "The development runner's run issuer binding (bind_casework_run_issuer and checked_casework_run_issuer in crates/registry-rstack-dev/src/products.rs): exact producer issuer, profile, subject and grant-scope comparison, an existing initiator pin, a closed initiator trust member, and a change limited to the producer issuer members of a private project copy before the public caseworkctl check and package.", refusal: "Refuse mismatched producer pins, an absent initiator pin and an initiator trust other than run-test-people, each at its dev.yaml pointer.", negativeId: CASEWORK-NEG-36, negativeTest: {path: crates/registry-rstack/tests/dev_run.rs, name: casework_run_issuer_mismatch_names_the_dev_yaml_pointer}} - {id: CASEWORK-SEC-37, invariants: [1, 3, 9, 14], state: enforced, targetWave: beta, threat: "A separate source bearer substitutes another human or leaks through inbox filtering or retained recovery.", enforcementPoint: "Independent provider-bound cryptographic same-human authentication before output, explicit source profile and invocation-local source credential.", refusal: "Refuse invalid or ambiguous pairs before source I/O; BReg still owns source client/profile admission.", negativeId: CASEWORK-NEG-37, negativeTest: {path: crates/registry-casework/tests/review_http.rs, name: separate_human_source_credentials_bind_before_empty_inbox_and_guard_mutations}} diff --git a/products/casework/contracts/security-test-traceability.yaml b/products/casework/contracts/security-test-traceability.yaml index 5c531fca79..ca11fcc158 100644 --- a/products/casework/contracts/security-test-traceability.yaml +++ b/products/casework/contracts/security-test-traceability.yaml @@ -35,7 +35,7 @@ entries: - {id: CASEWORK-SEC-31, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: advisory_rejection_advances_to_final_approval_without_releasing_its_reason}, {file: crates/registry-casework/tests/review_postgres.rs, name: rejected_cancelled_and_superseded_results_commit_atomically}, {file: crates/registry-casework/tests/review_postgres.rs, name: review_decisions_are_audited_after_the_decision_commits}, {file: crates/registry-casework/tests/review_acceptance_postgres.rs, name: approvals_in_one_stage_must_agree_on_the_outcome_they_release}, {file: crates/registry-casework/tests/review_http.rs, name: stage_outcomes_allow_local_changes_request_but_refuse_it_at_final_over_http}]} - {id: CASEWORK-SEC-32, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: decided_review_state_stays_readable_after_the_source_conceals_context}, {file: crates/registry-casework/tests/review_postgres.rs, name: decided_current_source_context_is_retained_only_for_its_author}, {file: crates/registry-casework/tests/review_postgres.rs, name: earlier_stage_author_gets_no_context_while_the_request_is_still_reviewing}, {file: crates/registry-casework/tests/review_postgres.rs, name: retained_context_authorship_is_scoped_to_the_decided_task_and_issuer}, {file: crates/registry-casework/tests/breg_review_journey.rs, name: native_proposal_requires_pinned_casework_approval_before_breg_apply}]} - {id: CASEWORK-SEC-33, tests: [{file: crates/registry-casework-breg/tests/context_provider.rs, name: task_context_uses_only_its_distinct_profile_and_echoes_the_exact_request}, {file: crates/registry-casework-breg/tests/context_provider.rs, name: task_context_has_no_status_profile_fallback}, {file: crates/registry-casework-breg/tests/context_provider.rs, name: task_context_refuses_invalid_and_unknown_fields_before_credentials_or_io}, {file: crates/registry-casework-breg/src/lib.rs, name: task_projection_keeps_only_definitions_reachable_from_selected_properties}]} - - {id: CASEWORK-SEC-34, tests: [{file: crates/registry-casework/src/auth.rs, name: delegated_staff_read_is_separate_from_human_authentication}, {file: crates/registry-casework/src/auth.rs, name: delegated_staff_read_refuses_changed_actor_scope_lifetime_and_source_profile}, {file: crates/registry-casework/src/auth.rs, name: delegated_staff_reader_accepts_rfc_actor_and_rejects_actor_substitution}, {file: crates/registry-casework/src/auth.rs, name: delegated_staff_read_negative_cases_have_value_free_stage_diagnostics}, {file: crates/registry-casework/src/auth/delegated.rs, name: delegated_caller_refusals_are_not_audited_as_runtime_failures}, {file: crates/registry-casework/src/auth/delegated.rs, name: delegated_recheck_conceals_authority_changes_but_preserves_store_failures}, {file: crates/registry-casework/src/config.rs, name: delegated_staff_reader_allows_client_rotation_for_one_staff_profile}, {file: crates/registry-casework/src/config.rs, name: delegated_reader_source_profiles_require_exchange_on_reachable_configured_provider}, {file: crates/registry-casework/src/config.rs, name: submitted_only_delegated_reader_may_omit_source_profiles}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_reader_credential_cannot_enter_producer_create_or_cancel_routes}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_review_task_list_withholds_results_when_audit_begin_or_terminal_fails}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_review_task_context_withholds_results_when_audit_begin_or_terminal_fails}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_submitted_context_ignores_admitted_source_profile_and_audits_one_success}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_cursor_is_partitioned_by_reader_policy_during_client_rotation}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_reads_withhold_rows_and_context_when_assignment_changes_during_source_io}, {file: crates/registry-casework-client/tests/staffing_boundary.rs, name: delegated_staff_read_uses_only_its_dedicated_route_and_policy_header}, {file: crates/registry-casework-breg/src/lib.rs, name: delegated_exchange_uses_exact_source_authority}, {file: crates/registry-mcp/src/casework.rs, name: context_uses_the_configured_source_profile_in_one_request}, {file: crates/registry-mcp/src/casework.rs, name: model_visible_context_omits_internal_policy_closure}, {file: crates/registry-mcp/src/casework.rs, name: casework_failure_log_keeps_only_static_class_status_and_safe_trace}, {file: crates/registry-mcp/tests/provider_contract.rs, name: casework_failures_have_static_actionable_classes_and_preserve_safe_trace}, {file: crates/registry-mcp/tests/native_casework.rs, name: native_staff_gateway_preserves_delegated_read_authority}]} + - {id: CASEWORK-SEC-34, tests: [{file: crates/registry-casework/src/auth.rs, name: delegated_staff_read_is_separate_from_human_authentication}, {file: crates/registry-casework/src/auth.rs, name: delegated_staff_read_refuses_changed_actor_scope_lifetime_and_source_profile}, {file: crates/registry-casework/src/auth.rs, name: delegated_staff_reader_accepts_rfc_actor_and_rejects_actor_substitution}, {file: crates/registry-casework/src/auth.rs, name: delegated_staff_read_negative_cases_name_their_check_and_write_no_log_line}, {file: crates/registry-casework/src/auth/delegated.rs, name: delegated_caller_refusals_are_not_audited_as_runtime_failures}, {file: crates/registry-casework/src/auth/delegated.rs, name: delegated_recheck_conceals_authority_changes_but_preserves_store_failures}, {file: crates/registry-casework/src/config.rs, name: delegated_staff_reader_allows_client_rotation_for_one_staff_profile}, {file: crates/registry-casework/src/config.rs, name: delegated_reader_source_profiles_require_exchange_on_reachable_configured_provider}, {file: crates/registry-casework/src/config.rs, name: submitted_only_delegated_reader_may_omit_source_profiles}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_reader_credential_cannot_enter_producer_create_or_cancel_routes}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_review_task_list_withholds_results_when_audit_begin_or_terminal_fails}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_review_task_context_withholds_results_when_audit_begin_or_terminal_fails}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_submitted_context_ignores_admitted_source_profile_and_audits_one_success}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_cursor_is_partitioned_by_reader_policy_during_client_rotation}, {file: crates/registry-casework/tests/review_http.rs, name: delegated_reads_withhold_rows_and_context_when_assignment_changes_during_source_io}, {file: crates/registry-casework-client/tests/staffing_boundary.rs, name: delegated_staff_read_uses_only_its_dedicated_route_and_policy_header}, {file: crates/registry-casework-breg/src/lib.rs, name: delegated_exchange_uses_exact_source_authority}, {file: crates/registry-mcp/src/casework.rs, name: context_uses_the_configured_source_profile_in_one_request}, {file: crates/registry-mcp/src/casework.rs, name: model_visible_context_omits_internal_policy_closure}, {file: crates/registry-mcp/src/casework.rs, name: casework_failure_log_keeps_only_static_class_status_and_safe_trace}, {file: crates/registry-mcp/tests/provider_contract.rs, name: casework_failures_have_static_actionable_classes_and_preserve_safe_trace}, {file: crates/registry-mcp/tests/native_casework.rs, name: native_staff_gateway_preserves_delegated_read_authority}]} - {id: CASEWORK-SEC-35, tests: [{file: crates/registry-review-protocol/src/lib.rs, name: progress_codes_follow_the_shared_local_identifier_grammar}, {file: crates/registry-review-client/tests/http_boundary.rs, name: request_progress_gets_once_with_the_explicit_option_and_exact_binding}, {file: crates/registry-review-client/tests/http_boundary.rs, name: plain_request_refuses_an_unsolicited_progress_projection}, {file: crates/registry-review-client/tests/http_boundary.rs, name: request_progress_rejects_each_substituted_binding_member}, {file: crates/registry-review-client/tests/http_boundary.rs, name: request_progress_rejects_terminal_or_invalid_codes}, {file: crates/registry-casework-core/src/review.rs, name: policy_closure_digest_pins_every_stage_rule}, {file: crates/registry-casework/tests/review_http.rs, name: producer_http_create_recover_conflict_and_pending_result_are_closed}, {file: crates/registry-casework/tests/review_http.rs, name: producer_progress_omits_an_unmapped_active_stage}]} - {id: CASEWORK-SEC-36, tests: [{file: crates/registry-rstack/tests/dev_run.rs, name: casework_run_issuer_mismatch_names_the_dev_yaml_pointer}, {file: crates/registry-rstack/tests/dev_run.rs, name: normal_check_uses_owning_casework_tool_for_exact_run_producer_chain}, {file: crates/registry-rstack/tests/dev_run.rs, name: casework_run_issuer_binding_needs_no_run_source_command}, {file: crates/registry-rstack-dev/src/bindings.rs, name: run_source_opt_in_is_closed}, {file: crates/registry-rstack-dev/src/products.rs, name: the_run_issuer_is_bound_only_when_it_is_a_loopback_url}, {file: crates/registry-rstack-dev/src/products.rs, name: casework_run_issuer_binding_refuses_each_mismatch_at_its_pointer}, {file: crates/registry-rstack-dev/src/products.rs, name: binding_the_run_issuer_changes_only_the_producer_issuer_members}]} - {id: CASEWORK-SEC-37, tests: [{file: crates/registry-casework/src/auth.rs, name: separate_human_source_pair_uses_raw_subject_and_independent_source_client}, {file: crates/registry-casework/tests/review_http.rs, name: separate_human_source_credentials_bind_before_empty_inbox_and_guard_mutations}, {file: crates/registry-casework/src/http/source_credentials.rs, name: verified_provider_handles_do_not_forward_casework_or_mix_invocations}, {file: crates/registry-casework-client/tests/http_boundary.rs, name: separate_human_source_credential_is_explicit_per_call_and_never_retained}]} diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index 51ab2353de..254dd74175 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -13,6 +13,19 @@ host, an IPv4-mapped loopback literal such as `[::ffff:127.0.0.1]` counts as loopback, the same as `127.0.0.1`. A database host of `localhost` is matched in any letter case. Host names other than `localhost` stay refused. +- A signed event delivery that Coordinator cannot verify because its own + signing key is unreadable, missing or too short counts under + `key-source-unavailable` in `coordinator_request_refusals_total`. The 401 and + 503 answers are unchanged. +- A static key set that startup refuses now names the key position and member + in the `access.configuration` message instead of pointing at the issuer and + policy configuration. +- `coordinatorctl provision` creates the database, the migration and runtime + roles and the grants `apply` expects, from the two database URLs in the + runtime file, as a PostgreSQL administrator. `--print-sql` prints the plan + and connects to nothing. When the runtime file has a `deployment` block, a + runtime URL whose user is not `deployment.runtimeRole` is refused before any + connection with `coordinator.runtime-config.runtime-role-mismatch`. - `GET /health` and `GET /ready` carry the `status` member the other services answer: `{"live":true,"status":"ok"}` and diff --git a/products/documents/CHANGELOG.md b/products/documents/CHANGELOG.md index baf1869a9f..0524cee508 100644 --- a/products/documents/CHANGELOG.md +++ b/products/documents/CHANGELOG.md @@ -21,8 +21,26 @@ `authentication.oidc.scopeClaim`. Refusal statuses, headers and bodies are unchanged. - A static key set with a private key member or a repeated member name is - refused at startup, and the error names the rule it broke and the key's - position, never a key value. + refused at startup, and the error names the rule it broke, and the key's + position for a rule about one key, never a key value. +- A token verifier that cannot reach its key source still answers 503, and the + operator's record of it is the `request refused` line with `failed_check` + `key-source-unavailable` and the counter, not a warning per request, so + `DOCUMENTS_LOG=warn` writes no line for it. +- A caller that sees a document and does not hold custody of it is counted + under `ownership` when it lists or issues grants, as it is when it downloads + or requests erasure. A custodian without grant authority is counted under + `operation`. The answer is unchanged. +- `documentsctl provision` creates the migration and runtime login roles and + the database that the runtime file's two database URLs name, grants both roles + `CONNECT`, gives the migration role `USAGE` and `CREATE` on the `public` + schema and the runtime role `USAGE` on it, from a PostgreSQL administrator + URL. Running it again restores the runtime role's `USAGE`. It creates only + what is missing, + refuses a role whose password differs from its URL, refuses an administrator + URL that names another host or port than the product URLs, and with + `--print-sql` prints the script without connecting or printing a password. + `documentsctl apply` still grants the runtime role what serving needs. - The Rust Documents client accepts a `/health` answer with an empty body or a JSON object body of at most 4096 bytes, and ignores the object's members. A diff --git a/products/documents/contracts/recorded-decisions.yaml b/products/documents/contracts/recorded-decisions.yaml index 2c197a261a..3740c6f602 100644 --- a/products/documents/contracts/recorded-decisions.yaml +++ b/products/documents/contracts/recorded-decisions.yaml @@ -490,3 +490,28 @@ decisions: - {path: crates/registry-documents/tests/postgres_documents.rs, name: grant_authority_and_unknown_ids_answer_without_disclosing_a_document} - {path: crates/registry-documents-core/src/access.rs, name: the_reserving_system_sees_a_delivered_document_but_may_neither_grant_nor_read_it} - {path: crates/registry-documents/tests/postgres_journey.rs, name: a_rendered_document_reaches_a_named_recipient_and_outlives_its_share} + - id: DOCUMENTS-DEC-36 + subject: An explicit allowedClients list must cover every package client, and from-package admits exactly them + decision: >- + authentication.oidc.allowedClients: from-package admits the requester + clients of the package's access profiles and no others. An explicit list + that omits a client a profile names is refused at startup with + documents.runtime.profile-client-not-allowed, so a missing client + never fails at run time. A client named under assertionIssuers that is + not admitted is refused with + documents.runtime.assertion-issuer-client-not-allowed. + evidence: + - {path: crates/registry-documents/src/config.rs, name: explicit_list_missing_a_package_client_is_refused} + - {path: crates/registry-documents/src/config.rs, name: from_package_admits_exactly_the_package_clients} + - id: DOCUMENTS-DEC-37 + subject: A path id that is not an id, and a grant naming another version, answer as a concealed document + decision: >- + A document or grant id in a path that is not a UUID answers 404 + resource.not-found, and so does a grant request whose versionId is not + the document's current version. Both are validation of a name that + points at nothing the caller may see, answered like an absent document, + and the operator's counter records them under the visibility check. + evidence: + - {path: crates/registry-documents/src/http.rs, name: a_path_id_that_is_not_an_id_names_nothing} + - {path: crates/registry-documents/tests/refusal_golden.rs, name: every_refusal_answers_the_bytes_the_golden_file_holds} + - {path: crates/registry-documents/tests/refusal_golden.rs, name: every_refusal_is_counted_and_logged_under_the_check_it_failed} diff --git a/products/documents/contracts/security-invariant-matrix.yaml b/products/documents/contracts/security-invariant-matrix.yaml index ebd5ec9acc..a997b81903 100644 --- a/products/documents/contracts/security-invariant-matrix.yaml +++ b/products/documents/contracts/security-invariant-matrix.yaml @@ -85,7 +85,12 @@ invariants: admits exactly those clients. The unrestricted form is refused. refusal: >- Refuse with documents.runtime.allowed-clients-required at - /authentication/oidc/allowedClients. + /authentication/oidc/allowedClients. An explicit list that omits a + requester client a package profile names is refused with + documents.runtime.profile-client-not-allowed, held by + explicit_list_missing_a_package_client_is_refused and + from_package_admits_exactly_the_package_clients in + crates/registry-documents/src/config.rs (DOCUMENTS-DEC-36). negativeTest: path: crates/registry-documents/src/config.rs name: unrestricted_clients_are_refused diff --git a/products/documents/scripts/check_database_test_isolation.py b/products/documents/scripts/check_database_test_isolation.py index 677d2e21db..5e3a9fc9cf 100755 --- a/products/documents/scripts/check_database_test_isolation.py +++ b/products/documents/scripts/check_database_test_isolation.py @@ -19,6 +19,8 @@ "postgres_operator", "postgres_s3", "postgres_startup", + "refusal_golden", + "refusal_key_source", }, "registry-documentsctl": {"postgres_cli"}, } diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 0874bfbdb9..14a92791bb 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -136,11 +136,16 @@ - The MCP edge counts every refusal by the check that refused it and writes one `request refused` line with `failed_check`, at most five lines per check per minute. The edge has no metrics listener, so the line is the operator's - signal there. Refusal statuses, headers and bodies are unchanged. Gateways + signal there. An unreachable key set is that line with + `failed_check` `key-source-unavailable`, in place of the earlier unbounded + warning, and a request the gateway cannot admit because of its own fault + writes at most one error line a minute. Refusal statuses, headers and bodies + are unchanged. Gateways built on the edge (`registry-mcp`, `registry-breg-mcp`) and the BReg review - page accept the loopback spellings of the shared definition under - `development-loopback` (for example `127.0.0.2` and `[::ffff:127.0.0.1]`), - and still refuse `localhost.` and `*.localhost`. A refused static key set + page now also accept the IPv4-mapped loopback form, for example + `[::ffff:127.0.0.1]`, under `development-loopback`. The rest of + `127.0.0.0/8`, `[::1]` and `localhost` were already accepted, and + `localhost.` and `*.localhost` stay refused. A refused static key set now says why: `registry-mcp` names the refusal in its startup message, and `registry-breg-mcp` logs it, with its startup code unchanged. diff --git a/products/render/CHANGELOG.md b/products/render/CHANGELOG.md index 993402d465..3d28f73d83 100644 --- a/products/render/CHANGELOG.md +++ b/products/render/CHANGELOG.md @@ -3,9 +3,13 @@ ## Unreleased - Render counts every refusal of a caller in `render_request_refusals_total{check}` - on the metrics listener and writes one `request refused` log line with + (served when `metricsListener` is set) and writes one `request refused` log line with `failed_check` and the trace id, at most five per check per minute. The counter and the line carry a fixed check name only. Responses are unchanged. + A refusal whose audit entry cannot be written is answered as an audit + failure and is not counted. +- A static key set that Render refuses at startup now names the reason in the + `render.runtime-invalid` detail, such as a private key member or an OKP key. - A test timestamp authority may use an IPv4-mapped loopback literal in plain `http`, such as `http://[::ffff:127.0.0.1]/tsr`, the same as `127.0.0.1`. An IPv4-mapped address off the host, such as `[::ffff:10.0.0.5]`, stays From 98a2f3fdf9732a1df87d2bd31adf0b4c07dbb7cb Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:43:32 +0100 Subject: [PATCH 040/136] fix(platform): read loopback in identity and authoring tooling with the shared rule Development identity files, task connections and evidencectl suggest now decide what is local with registry-platform-loopback, as the runtimes do. - registry-thunderid-tooling accepts any 127.0.0.0/8 address, [::1], the IPv4-mapped form and localhost for a development issuer, an exchange issuer or a local app origin. The identity facts issuer and the local app origin accepted only 127.0.0.1 before. - evidencectl suggest accepts an IPv4-mapped IPv6 loopback literal for a plain-HTTP base URL or OpenAPI URL. The name localhost is still refused there. Signed-off-by: Jeremi Joslin --- Cargo.lock | 2 + crates/registry-evidencectl/Cargo.toml | 1 + .../registry-evidencectl/src/suggest/fetch.rs | 33 ++++++++++- .../registry-evidencectl/src/suggest/mod.rs | 22 ++++++- crates/registry-thunderid-tooling/Cargo.toml | 1 + .../src/description.rs | 58 +++++++++++++++++-- .../registry-thunderid-tooling/src/grant.rs | 26 ++++++++- .../src/identity_facts.rs | 6 +- .../src/identity_facts_tests.rs | 19 ++++++ .../src/task_connection.rs | 23 +++++++- products/evidence/CHANGELOG.md | 3 + products/platform/CHANGELOG.md | 6 ++ 12 files changed, 188 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d560df0364..c87f419721 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7390,6 +7390,7 @@ dependencies = [ "registry-platform-config", "registry-platform-crypto", "registry-platform-httpsec", + "registry-platform-loopback", "registry-platform-yaml", "registry-rstack-dev", "registry-thunderid-tooling", @@ -8590,6 +8591,7 @@ dependencies = [ "registry-platform-config", "registry-platform-crypto", "registry-platform-httputil", + "registry-platform-loopback", "registry-platform-oidc", "registry-platform-yaml", "reqwest 0.12.28", diff --git a/crates/registry-evidencectl/Cargo.toml b/crates/registry-evidencectl/Cargo.toml index ffd6ce7d80..b4691acb4c 100644 --- a/crates/registry-evidencectl/Cargo.toml +++ b/crates/registry-evidencectl/Cargo.toml @@ -41,6 +41,7 @@ registry-cli-api.workspace = true registry-cli-reference.workspace = true registry-platform-crypto.workspace = true registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-loopback.workspace = true registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-thunderid-tooling.workspace = true diff --git a/crates/registry-evidencectl/src/suggest/fetch.rs b/crates/registry-evidencectl/src/suggest/fetch.rs index ba4eff9cde..04d68eea4e 100644 --- a/crates/registry-evidencectl/src/suggest/fetch.rs +++ b/crates/registry-evidencectl/src/suggest/fetch.rs @@ -114,8 +114,10 @@ pub fn check_url(value: &str) -> Result { match url.scheme() { "https" => {} "http" => match url.host() { - Some(Host::Ipv4(address)) if address.is_loopback() => {} - Some(Host::Ipv6(address)) if address.is_loopback() => {} + Some(Host::Ipv4(address)) + if registry_platform_loopback::loopback_address(address.into()) => {} + Some(Host::Ipv6(address)) + if registry_platform_loopback::loopback_address(address.into()) => {} _ => { return Err(safe_url_refusal( "evidence.openapi.url-insecure", @@ -211,3 +213,30 @@ pub fn get(url: &Url, max_bytes: u64) -> Result { String::from_utf8(body).with_context(|| format!("decoding the document at {url} as UTF-8")) } + +#[cfg(test)] +mod tests { + use super::check_url; + + #[test] + fn plain_http_follows_the_shared_loopback_rule_for_numeric_hosts() { + for (host, accepted) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", false), + ("LOCALHOST", false), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!( + check_url(&format!("http://{host}:4010/openapi.json")).is_ok(), + accepted, + "{host}" + ); + } + } +} diff --git a/crates/registry-evidencectl/src/suggest/mod.rs b/crates/registry-evidencectl/src/suggest/mod.rs index e2f3259d91..7ec71886f3 100644 --- a/crates/registry-evidencectl/src/suggest/mod.rs +++ b/crates/registry-evidencectl/src/suggest/mod.rs @@ -404,7 +404,9 @@ fn validate_base_url(raw: &str) -> Result { bail!("an HTTP --base-url must use a numeric loopback address") } }; - if !ip.is_loopback() || parsed.port().is_none_or(|port| port == 0) { + if !registry_platform_loopback::loopback_address(ip) + || parsed.port().is_none_or(|port| port == 0) + { bail!("an HTTP --base-url must use a numeric loopback address and non-zero port"); } } @@ -1695,6 +1697,24 @@ fn missing_flags_message(args: &SuggestArgs) -> String { mod tests { use super::validate_base_url; + #[test] + fn http_source_origins_follow_the_shared_loopback_rule_for_numeric_hosts() { + for (origin, accepted) in [ + ("http://127.0.0.1:4010", true), + ("http://127.0.0.2:4010", true), + ("http://[::1]:4010", true), + ("http://[::ffff:7f00:1]:4010", true), + ("http://localhost:4010", false), + ("http://LOCALHOST:4010", false), + ("http://a.localhost:4010", false), + ("http://localhost.:4010", false), + ("http://10.0.0.1:4010", false), + ("http://example.com:4010", false), + ] { + assert_eq!(validate_base_url(origin).is_ok(), accepted, "{origin}"); + } + } + #[test] fn json_runs_never_prompt() { assert!(!super::prompts_allowed(crate::OutputFormat::Json)); diff --git a/crates/registry-thunderid-tooling/Cargo.toml b/crates/registry-thunderid-tooling/Cargo.toml index 8951f1afdb..074165ce02 100644 --- a/crates/registry-thunderid-tooling/Cargo.toml +++ b/crates/registry-thunderid-tooling/Cargo.toml @@ -20,6 +20,7 @@ workspace = true base64.workspace = true getrandom.workspace = true registry-platform-config.workspace = true +registry-platform-loopback.workspace = true registry-platform-crypto = { workspace = true, optional = true } registry-platform-httputil = { workspace = true, optional = true } registry-platform-oidc = { workspace = true, optional = true } diff --git a/crates/registry-thunderid-tooling/src/description.rs b/crates/registry-thunderid-tooling/src/description.rs index 718bb284b5..ae36e69fde 100644 --- a/crates/registry-thunderid-tooling/src/description.rs +++ b/crates/registry-thunderid-tooling/src/description.rs @@ -324,10 +324,18 @@ fn private_file_name(path: &std::path::Path) -> bool { .all(|part| matches!(part, std::path::Component::Normal(_))) } +/// A host a development profile may reach over plain HTTP: loopback, or the +/// name Docker gives the host machine. +fn development_host(host: &str) -> bool { + registry_platform_loopback::loopback_host(host).is_some() || host == "host.docker.internal" +} + fn local_url(value: &str) -> bool { url::Url::parse(value).is_ok_and(|url| { url.scheme() == "http" - && url.host_str() == Some("127.0.0.1") + && url + .host_str() + .is_some_and(|host| registry_platform_loopback::loopback_host(host).is_some()) && url.port().is_some_and(|port| port != 0) && url.username().is_empty() && url.password().is_none() @@ -619,10 +627,7 @@ impl IssuerDescription { && (url.scheme() == "https" || (development && url.scheme() == "http" - && matches!( - url.host_str(), - Some("127.0.0.1" | "localhost" | "host.docker.internal") - ))) + && url.host_str().is_some_and(development_host))) }); if !valid { return refuse("exchange issuer and JWKS URLs require HTTPS or an explicit development host"); @@ -965,6 +970,49 @@ pub(crate) fn all_distinct(ids: impl IntoIterator) -> bool { mod tests { use super::*; + #[test] + fn local_urls_follow_the_shared_loopback_rule() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", true), + ("LOCALHOST", true), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!( + local_url(&format!("http://{host}:3000")), + loopback, + "{host}" + ); + } + assert!(!local_url("http://127.0.0.1"), "a port is required"); + } + + #[test] + fn development_hosts_are_loopback_or_the_docker_host_name() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", true), + ("LOCALHOST", true), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!(development_host(host), loopback, "{host}"); + } + assert!(development_host("host.docker.internal")); + assert!(!development_host("host.docker.internal.")); + } + pub(super) fn exchange_description() -> IssuerDescription { let mut description = crate::testing::synthetic_description(); description.exchange_issuers.push(ExchangeIssuer { diff --git a/crates/registry-thunderid-tooling/src/grant.rs b/crates/registry-thunderid-tooling/src/grant.rs index 3baddfc13c..47282e13be 100644 --- a/crates/registry-thunderid-tooling/src/grant.rs +++ b/crates/registry-thunderid-tooling/src/grant.rs @@ -41,7 +41,9 @@ fn endpoint(address: &str) -> Result { || url.fragment().is_some() || !(url.scheme() == "https" || (url.scheme() == "http" - && matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]")))) + && url + .host_str() + .is_some_and(|host| registry_platform_loopback::loopback_host(host).is_some()))) || url.host_str().is_none() { return Err(refused( @@ -216,6 +218,28 @@ mod tests { scopes: vec!["records:get".into()], } } + #[test] + fn plain_http_endpoints_follow_the_shared_loopback_rule() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", true), + ("LOCALHOST", true), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!( + endpoint(&format!("http://{host}:8100")).is_ok(), + loopback, + "{host}" + ); + } + } + #[test] fn connection_refuses_ambiguous_or_unprotected_endpoints_and_scopes() { assert!(connection().validate().is_ok()); diff --git a/crates/registry-thunderid-tooling/src/identity_facts.rs b/crates/registry-thunderid-tooling/src/identity_facts.rs index 152b5ae716..63006bda42 100644 --- a/crates/registry-thunderid-tooling/src/identity_facts.rs +++ b/crates/registry-thunderid-tooling/src/identity_facts.rs @@ -486,7 +486,9 @@ fn issuer_url(value: &str) -> bool { || (Url::new(value).is_ok() && url::Url::parse(value).is_ok_and(|url| { url.scheme() == "http" - && url.host_str() == Some("127.0.0.1") + && url.host_str().is_some_and(|host| { + registry_platform_loopback::loopback_host(host).is_some() + }) && url.username().is_empty() && url.password().is_none() && url.query().is_none() @@ -570,7 +572,7 @@ fn check(document: &Document, facts: &IdentityFacts) -> Vec { error( "/issuer", "identity.facts.invalid-issuer", - "the issuer is neither https nor http to 127.0.0.1, or carries user information, a query or a fragment", + "the issuer is neither https nor http to a loopback host, or carries user information, a query or a fragment", "Write the issuer URL the product trusts.", ); } diff --git a/crates/registry-thunderid-tooling/src/identity_facts_tests.rs b/crates/registry-thunderid-tooling/src/identity_facts_tests.rs index a41d110a78..564d4a56a2 100644 --- a/crates/registry-thunderid-tooling/src/identity_facts_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_facts_tests.rs @@ -528,3 +528,22 @@ fn every_set_list_refuses_a_repeat_at_the_repeat() { ); } } + +#[test] +fn an_http_issuer_follows_the_shared_loopback_rule() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", true), + ("LOCALHOST", true), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!(issuer_url(&format!("http://{host}:8091")), loopback, "{host}"); + } + assert!(issuer_url("https://id.registry.example")); +} diff --git a/crates/registry-thunderid-tooling/src/task_connection.rs b/crates/registry-thunderid-tooling/src/task_connection.rs index 3f5d7219d5..800e808cf8 100644 --- a/crates/registry-thunderid-tooling/src/task_connection.rs +++ b/crates/registry-thunderid-tooling/src/task_connection.rs @@ -122,7 +122,9 @@ fn valid_endpoint(url: &Url) -> bool { parsed.query().is_none() && parsed.fragment().is_none() && (url.is_https() - || matches!(parsed.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"))) + || parsed + .host_str() + .is_some_and(|host| registry_platform_loopback::loopback_host(host).is_some())) } fn valid_scope(scope: &str) -> bool { @@ -309,6 +311,25 @@ clients: - records:get "; + #[test] + fn plain_http_endpoints_follow_the_shared_loopback_rule() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", true), + ("LOCALHOST", true), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + let url = Url::new(format!("http://{host}:8090")).expect("a URL"); + assert_eq!(valid_endpoint(&url), loopback, "{host}"); + } + } + fn read(text: &str) -> Result, Report> { super::read("task-connection.yaml", text.as_bytes()).map(|_| Vec::new()) } diff --git a/products/evidence/CHANGELOG.md b/products/evidence/CHANGELOG.md index c5ed84e516..4fcd87ee1c 100644 --- a/products/evidence/CHANGELOG.md +++ b/products/evidence/CHANGELOG.md @@ -26,6 +26,9 @@ startup message, still under `evidence.oid4vp.issuer-unavailable`. A request whose `Authorization` header is present but unreadable as text counts under `credential-malformed`. The answer is unchanged. +- `evidencectl suggest` accepts an IPv4-mapped IPv6 loopback address, for + example `[::ffff:127.0.0.1]`, for a plain-HTTP base URL or OpenAPI URL, as + the shared loopback rule does. The name `localhost` is still refused there. - BREAKING (experimental surface): `evidencectl check` and `evidencectl package` refuse a `publicCheck` definition whose Source facts schema states more than diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 14a92791bb..ad9ed8a22f 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -89,6 +89,12 @@ `[127.0.0.1]` are never loopback. Sites that use it accept more literal spellings than before, for example `127.0.0.2` and `[::ffff:127.0.0.1]`. +- `registry-thunderid-tooling` reads development identity files and task + connections with the same loopback rule. A development issuer, exchange + issuer or local app origin may be any `127.0.0.0/8` address, `[::1]`, the + IPv4-mapped form or `localhost`. The identity facts issuer and the local app + origin accepted only `127.0.0.1` before. + - Every client built by `OutboundClientBuilder` resolves the name `localhost` to `127.0.0.1` and `::1` itself, so no resolver is asked for it. A host whose resolver or hosts file maps `localhost` elsewhere is no From 1c83016f588a96a5f155635adbb3bef8a63acf7a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:49:10 +0100 Subject: [PATCH 041/136] fix(breg): refuse a non-bool freshness flag in the Python hook verifier - verify_hook_delivery in the Python binding takes caller_enforced_freshness as a bool only. Any other value raises the binding's invalid-request error instead of a TypeError, and the message names the rule. - The Python type stubs list stale-delivery among the hook verification codes, as the Node declarations do. - The Rust Within freshness option documents that it applies the skew as given, while the bindings accept 1 to 3600 seconds. - The Node and Python edge tests round the delivery time to the nearest second. Signed-off-by: Jeremi Joslin --- .../__test__/webhook-verification.test.js | 5 ++++- .../python/registry_breg_client/__init__.pyi | 1 + crates/registry-breg-client-py/src/lib.rs | 16 ++++++++++++---- .../tests/python/test_webhook_verification.py | 6 +++++- crates/registry-breg-client/src/hook.rs | 5 +++++ 5 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/registry-breg-client-node/__test__/webhook-verification.test.js b/crates/registry-breg-client-node/__test__/webhook-verification.test.js index b3f93ed84d..9b398a193c 100644 --- a/crates/registry-breg-client-node/__test__/webhook-verification.test.js +++ b/crates/registry-breg-client-node/__test__/webhook-verification.test.js @@ -48,7 +48,10 @@ function input(overrides = {}) { function signedHeaders(deliveryTime) { const values = { ...headers(), - 'x-registry-delivery-time': deliveryTime.toISOString().replace(/\.\d{3}Z$/, 'Z'), + // Rounded to the nearest second so a one-second window is not crossed by the fraction. + 'x-registry-delivery-time': new Date(Math.round(deliveryTime.getTime() / 1000) * 1000) + .toISOString() + .replace(/\.\d{3}Z$/, 'Z'), }; const parts = [ values['Ce-Specversion'], values['CE-ID'], values['ce-source'], values['ce-type'], diff --git a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi index 2602c96592..bb7db6f3a9 100644 --- a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi +++ b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi @@ -209,6 +209,7 @@ def encode_ingestion_chunk( HookVerificationRefusalCode = Literal[ "missing-header", "invalid-delivery-time", + "stale-delivery", "duplicate-header", "body-too-large", "invalid-key", diff --git a/crates/registry-breg-client-py/src/lib.rs b/crates/registry-breg-client-py/src/lib.rs index bc39955ad3..3214f6f2df 100644 --- a/crates/registry-breg-client-py/src/lib.rs +++ b/crates/registry-breg-client-py/src/lib.rs @@ -1052,17 +1052,25 @@ const HOOK_MAXIMUM_SKEW_SECONDS: u32 = 3600; fn hook_freshness( py: Python<'_>, max_skew_seconds: Option<&Bound<'_, PyAny>>, - caller_enforced_freshness: bool, + caller_enforced_freshness: Option<&Bound<'_, PyAny>>, ) -> PyResult { let invalid = || { to_py_err( py, MappedError::binding( "invalid-request", - "hook freshness options are invalid: max_skew_seconds is a whole number from 1 to 3600 and cannot be combined with caller_enforced_freshness", + "hook freshness options are invalid: max_skew_seconds is a whole number from 1 to 3600, caller_enforced_freshness is a bool, and the two cannot be combined", ), ) }; + let caller_enforced_freshness = match caller_enforced_freshness { + None => false, + Some(value) if value.is_none() => false, + Some(value) => match value.cast::() { + Ok(flag) => flag.is_true(), + Err(_) => return Err(invalid()), + }, + }; let Some(value) = max_skew_seconds.filter(|value| !value.is_none()) else { return Ok(if caller_enforced_freshness { BRegHookFreshness::CallerEnforced @@ -1097,7 +1105,7 @@ fn hook_freshness( /// `BaseRegistryClientError` with kind `hook-verification` and a value-free /// `code`; input of the wrong shape raises kind `invalid-request`. #[pyfunction] -#[pyo3(signature = (*, method, path, headers, body, key, max_skew_seconds=None, caller_enforced_freshness=false))] +#[pyo3(signature = (*, method, path, headers, body, key, max_skew_seconds=None, caller_enforced_freshness=None))] #[allow(clippy::too_many_arguments)] fn verify_hook_delivery<'py>( py: Python<'py>, @@ -1107,7 +1115,7 @@ fn verify_hook_delivery<'py>( body: &Bound<'py, PyAny>, key: &Bound<'py, PyAny>, max_skew_seconds: Option<&Bound<'py, PyAny>>, - caller_enforced_freshness: bool, + caller_enforced_freshness: Option<&Bound<'py, PyAny>>, ) -> PyResult> { let freshness = hook_freshness(py, max_skew_seconds, caller_enforced_freshness)?; let method = hook_text(py, method, "method")?; diff --git a/crates/registry-breg-client-py/tests/python/test_webhook_verification.py b/crates/registry-breg-client-py/tests/python/test_webhook_verification.py index 3c542c7afa..bf4d9a5362 100644 --- a/crates/registry-breg-client-py/tests/python/test_webhook_verification.py +++ b/crates/registry-breg-client-py/tests/python/test_webhook_verification.py @@ -70,7 +70,9 @@ def verify(**overrides): def signed_headers(delivery_time: datetime) -> list[tuple[str, str]]: """The fixed headers re-signed for `delivery_time` with the vector's key.""" - stamp = delivery_time.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + # Rounded to the nearest second so a one-second window is not crossed by the fraction. + rounded = datetime.fromtimestamp(round(delivery_time.timestamp()), tz=timezone.utc) + stamp = rounded.strftime("%Y-%m-%dT%H:%M:%SZ") values = replace_header(headers(), "x-registry-delivery-time", stamp) by_name = {name.lower(): value for name, value in values} signed = bytearray(b"breg-webhook-signature-v1") @@ -190,6 +192,8 @@ def test_refuses_a_freshness_option_out_of_range_or_combined(self) -> None: {"max_skew_seconds": True}, {"max_skew_seconds": "10"}, {"max_skew_seconds": 10, "caller_enforced_freshness": True}, + {"caller_enforced_freshness": "yes"}, + {"caller_enforced_freshness": 1}, ): with self.subTest(overrides=overrides): with self.assertRaises(BaseRegistryClientError) as raised: diff --git a/crates/registry-breg-client/src/hook.rs b/crates/registry-breg-client/src/hook.rs index 244f435f81..c6fd1cc2b9 100644 --- a/crates/registry-breg-client/src/hook.rs +++ b/crates/registry-breg-client/src/hook.rs @@ -11,6 +11,11 @@ pub enum BRegHookFreshness { #[default] DefaultWindow, /// Refuse a delivery time further than `skew` from the receiver clock. + /// + /// The Rust verifier applies `skew` as given. A zero `skew` refuses every + /// delivery and a very large one disables the window. The Node and Python + /// bindings accept 1 to 3600 seconds only. A receiver that wants no window + /// of its own uses [`Self::CallerEnforced`], which says so explicitly. Within { skew: Duration }, /// Check only that the delivery time is well formed. The caller enforces /// its own window. From 7f54b98511a61b7df94b926cf7ce345cd69bca5a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:49:42 +0100 Subject: [PATCH 042/136] fix(adapter): refuse a binding on a reserved facade path when authoring - BREAKING: adapterctl check refuses a binding whose concrete path is /health, /ready or the effective-contract path, with adapter.project.reserved-facade-path, and adapterctl compile refuses it with adapterctl.compile.reserved-path. The facade already left such a binding unserved. To migrate, rename the record type or change the operation path. - A static key set the facade refuses at startup states the rule it broke. - The configuration page says operation calls are authenticated and names the two probes that answer without a token. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-core/src/checks.rs | 88 ++++++++++++++++++- .../registry-adapter-core/src/diagnostics.rs | 4 + crates/registry-adapter/src/serve.rs | 78 +++++++++++++++- .../src/compile/document.rs | 61 ++++++++++++- .../src/content/docs/configure/adapter.mdx | 5 +- products/adapter/CHANGELOG.md | 8 +- products/adapter/fixtures/corpus/README.md | 1 + .../pack.yaml | 46 ++++++++++ .../profile.yaml | 37 ++++++++ .../project.yaml | 43 +++++++++ 10 files changed, 363 insertions(+), 8 deletions(-) create mode 100644 products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/pack.yaml create mode 100644 products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/profile.yaml create mode 100644 products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/project.yaml diff --git a/crates/registry-adapter-core/src/checks.rs b/crates/registry-adapter-core/src/checks.rs index 4d27c302b4..5403e0b942 100644 --- a/crates/registry-adapter-core/src/checks.rs +++ b/crates/registry-adapter-core/src/checks.rs @@ -4747,6 +4747,29 @@ pub fn check_project(workspace: &Workspace<'_>) -> Vec { "Name a record type the project declares.", )); } + // The listener answers the effective-contract, health and ready routes + // itself, so a binding whose concrete path is one of them would be + // advertised and never served. + if let Some(operation) = operation { + let concrete = operation.path.replace( + &format!("{{{}}}", operation.record_type_parameter.as_str()), + binding.record_type.as_str(), + ); + if [ + WELL_KNOWN_PATH, + registry_platform_httputil::probe::HEALTH_PATH, + registry_platform_httputil::probe::READY_PATH, + ] + .contains(&concrete.as_str()) + { + findings.push(finding( + CheckCode::ProjectReservedFacadePath, + &format!("{prefix}/recordType"), + "the binding's concrete facade path is reserved for the effective-contract, health or ready route", + "Rename the record type, or change the operation path, so the concrete path is not the effective-contract, health or ready path.", + )); + } + } // A search binding filters on declared fields of its bound record // type: the facade // offers exactly the declared list as typed equality query @@ -5869,8 +5892,10 @@ fn direct_route_closure<'a>( (closure, unresolved) } +/// The effective-contract route the Adapter serves on the facade listener. +const WELL_KNOWN_PATH: &str = "/.well-known/registry-adapter/effective-contract"; + fn async_status_path_collision_checks(workspace: &Workspace<'_>) -> Vec { - const WELL_KNOWN_PATH: &str = "/.well-known/registry-adapter/effective-contract"; let mut findings = Vec::new(); let statuses: Vec<(usize, &str, String)> = workspace .profile @@ -9247,6 +9272,67 @@ mod tests { ); } + /// A binding whose concrete path is the effective-contract, health or + /// ready route is refused, because the listener answers those routes + /// itself and never serves the binding. + #[test] + fn a_binding_on_a_reserved_facade_path_is_refused() { + for (path, record_type, reserved) in [ + ("/{type}", "health", true), + ("/{type}", "ready", true), + ( + "/.well-known/registry-adapter/{type}", + "effective-contract", + true, + ), + ("/{type}", "cases", false), + ("/health/{type}", "health", false), + ] { + let (mut profile, mut pack, mut project) = async_workspace_parts(); + let mut read = operation("cases-find", HttpMethod::Get); + read.path = path.to_string(); + read.path_parameters = UniqueList::new(vec![local("type")]).expect("parameters"); + read.record_type_parameter = local("type"); + read.record_id_parameter = None; + profile.operations = + UniqueIdList::new(vec![profile.operations[0].clone(), read]).expect("operations"); + let mut routes = pack.routes.into_vec(); + routes.push(RouteDefinition { + id: local("find-case"), + from: RouteFrom { + uri: direct("find-case"), + }, + steps: vec![to_get("case-api")], + }); + pack.routes = UniqueIdList::new(routes).expect("routes"); + let mut record_types = project.record_types.into_vec(); + record_types.push(RecordType { + name: local(record_type), + fields: record_types[0].fields.clone(), + }); + project.record_types = UniqueIdList::new(record_types).expect("record types"); + let mut bindings = project.bindings.into_vec(); + bindings.push(Binding { + async_completion: None, + id: local("find-case"), + operation: id("cases-find"), + record_type: local(record_type), + route: id("find-case"), + filters: UniqueList::new(Vec::new()).expect("empty"), + maximum_upstream_calls: BoundedU64::new(1).expect("budget"), + }); + project.bindings = UniqueIdList::new(bindings).expect("bindings"); + let findings = check_project(&workspace(&profile, &pack, &project)); + let reported = findings + .iter() + .any(|finding| finding.code == CheckCode::ProjectReservedFacadePath.code()); + assert_eq!( + reported, reserved, + "{path} with {record_type}: {findings:?}" + ); + } + } + /// A write operation needs a request envelope naming the record slot; /// a read operation needs none. #[test] diff --git a/crates/registry-adapter-core/src/diagnostics.rs b/crates/registry-adapter-core/src/diagnostics.rs index 242c714a2f..2e138c8a67 100644 --- a/crates/registry-adapter-core/src/diagnostics.rs +++ b/crates/registry-adapter-core/src/diagnostics.rs @@ -103,6 +103,7 @@ pub enum CheckCode { ProjectPinDigestMismatch, ProjectPinVersionMismatch, ProjectRequiredParameterUnbound, + ProjectReservedFacadePath, ProjectTemplateNotInstantiated, ProjectTransformBindingUnknown, ProjectTransformEntrypoint, @@ -257,6 +258,7 @@ impl CheckCode { Self::ProjectPinDigestMismatch, Self::ProjectPinVersionMismatch, Self::ProjectRequiredParameterUnbound, + Self::ProjectReservedFacadePath, Self::ProjectTemplateNotInstantiated, Self::ProjectTransformBindingUnknown, Self::ProjectTransformEntrypoint, @@ -437,6 +439,7 @@ impl CheckCode { Self::ProjectPinDigestMismatch => "adapter.project.pin-digest-mismatch", Self::ProjectPinVersionMismatch => "adapter.project.pin-version-mismatch", Self::ProjectRequiredParameterUnbound => "adapter.project.required-parameter-unbound", + Self::ProjectReservedFacadePath => "adapter.project.reserved-facade-path", Self::ProjectTemplateNotInstantiated => "adapter.project.template-not-instantiated", Self::ProjectTransformBindingUnknown => "adapter.project.transform-binding-unknown", Self::ProjectTransformEntrypoint => "adapter.project.transform-entrypoint", @@ -653,6 +656,7 @@ impl CheckCode { | Self::ProjectPinDigestMismatch | Self::ProjectPinVersionMismatch | Self::ProjectRequiredParameterUnbound + | Self::ProjectReservedFacadePath | Self::ProjectTemplateNotInstantiated | Self::ProjectTransformBindingUnknown | Self::ProjectTransformEntrypoint diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 32d9d54b47..91c4f829b2 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -209,8 +209,16 @@ pub(crate) async fn authenticator( let document = resolver .resolve(document_ref) .map_err(|_| invalid("the static key document could not be resolved"))?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| invalid("the static key document was refused"))?; + let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { + match error { + // The document is the operator's own file, so its text names the + // rule it breaks and never a key value. + OidcError::StaticKeySet(refused) => invalid(&format!( + "the static key document is not a usable key set: {refused}" + )), + _ => invalid("the static key document was refused"), + } + })?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -1336,6 +1344,72 @@ mod token_characterisation; mod tests { use super::*; + fn static_key_runtime() -> AdapterRuntimeConfig { + serde_json::from_value(serde_json::json!({ + "id": "static-key-set", + "endpoints": [{"endpoint": "tracker", "baseUrl": "https://tracker.example.invalid"}], + "listener": {"bind": "127.0.0.1:8080"}, + "database": { + "runtimeUrlRef": "secret:file/database-runtime", + "migrationUrlRef": "secret:file/database-migration" + }, + "oidc": { + "issuer": "https://issuer.example.test", + "audience": "registry-adapter-test", + "jwksSource": {"type": "static", "documentRef": "secret:file/issuer-keys.json"} + }, + "allowedClients": ["coordinator"], + "allowedPrivateCidrs": ["10.0.0.0/8"], + "audit": {"retentionDays": 90} + })) + .expect("the runtime configuration parses") + } + + async fn authenticator_over(keys: &serde_json::Value) -> Result { + use std::os::unix::fs::PermissionsExt; + let directory = tempfile::tempdir().expect("a scratch directory"); + let root = directory.path().canonicalize().expect("physical directory"); + let file = root.join("issuer-keys.json"); + std::fs::write(&file, keys.to_string()).expect("write the key set"); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + let resolver = SecretResolver::new([registry_platform_config::SecretProvider::File], root) + .expect("resolver"); + authenticator(&static_key_runtime(), &resolver).await + } + + #[tokio::test] + async fn a_static_key_set_with_a_private_member_is_refused_with_the_rule_text() { + let private = + registry_platform_testing::access_token_test_key(jsonwebtoken::Algorithm::ES256); + let mut keys = registry_platform_testing::jwks_from_private_jwk(&private); + keys["keys"][0]["d"] = serde_json::json!("AQAB"); + let Err(ServeError::Configuration(text)) = authenticator_over(&keys).await else { + panic!("a key set holding a private member is refused"); + }; + assert!( + text.contains("not a usable key set"), + "the refusal names the key set: {text}" + ); + assert!( + text.len() > "oidc: the static key document is not a usable key set: ".len(), + "the rule text follows: {text}" + ); + assert!(!text.contains("AQAB"), "no key value in the text: {text}"); + } + + #[tokio::test] + async fn a_static_key_set_with_a_public_ext_member_loads() { + let private = + registry_platform_testing::access_token_test_key(jsonwebtoken::Algorithm::ES256); + let mut keys = registry_platform_testing::jwks_from_private_jwk(&private); + keys["keys"][0]["ext"] = serde_json::json!(true); + authenticator_over(&keys) + .await + .map(|_| ()) + .expect("a public key set with ext loads"); + } + #[test] fn runtime_requirements_follow_the_deployment_feature_set() { const JOURNAL: (&str, &[&str]) = diff --git a/crates/registry-adapterctl/src/compile/document.rs b/crates/registry-adapterctl/src/compile/document.rs index 63e4bcd382..9684f0ef1b 100644 --- a/crates/registry-adapterctl/src/compile/document.rs +++ b/crates/registry-adapterctl/src/compile/document.rs @@ -254,6 +254,17 @@ pub(crate) fn assemble( } })); } + for (reserved, route) in [ + (registry_platform_httputil::probe::HEALTH_PATH, "health"), + (registry_platform_httputil::probe::READY_PATH, "ready"), + ] { + if paths.contains_key(reserved) { + findings.push(assembly_refusal( + "adapterctl.compile.reserved-path", + &format!("an authored operation collides with the Adapter {route} route"), + )); + } + } if paths.contains_key(well_known_path) { findings.push(assembly_refusal( "adapterctl.compile.reserved-path", @@ -768,13 +779,18 @@ mod tests { /// One project over that profile, with the given bindings. fn project(bindings: Value) -> AdapterProject { + project_of_record_type("case", bindings) + } + + /// [`project`] with its one record type named `record_type`. + fn project_of_record_type(record_type: &str, bindings: Value) -> AdapterProject { serde_json::from_value(json!({ "project": {"id": "case-deployment", "version": "1"}, "profile": {"id": "case-api", "version": "1", "digest": PINNED_DIGEST}, "pack": {"id": "case-api-pack", "version": "1", "digest": PINNED_DIGEST}, "recordTypes": [ { - "name": "case", + "name": record_type, "fields": [ {"name": "case_type", "type": "string", "required": true}, {"name": "severity", "type": "integer"}, @@ -1333,6 +1349,49 @@ mod tests { assert_eq!(findings[0].code, "adapterctl.compile.path-collision"); } + /// A binding whose concrete path is the health or ready route refuses the + /// assembly, because the listener answers those routes itself. + #[test] + fn a_concrete_path_equal_to_the_health_or_ready_route_refuses() { + let mut declared = profile_value(); + declared["operations"][1]["path"] = json!("/{type}"); + let profile: AdapterProfile = + serde_json::from_value(declared).expect("the profile decodes"); + for (record_type, route) in [("health", "health"), ("ready", "ready")] { + let findings = assemble( + &profile, + &project_of_record_type( + record_type, + json!([{ + "id": "case-find", + "operation": "cases-find", + "recordType": record_type, + "route": "case-find", + "maximumUpstreamCalls": 11, + }]), + ), + ) + .expect_err("the reserved path refuses"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert_eq!(findings[0].code, "adapterctl.compile.reserved-path"); + assert!(findings[0].message.contains(route), "{findings:?}"); + } + assemble( + &profile, + &project_of_record_type( + "cases", + json!([{ + "id": "case-find", + "operation": "cases-find", + "recordType": "cases", + "route": "case-find", + "maximumUpstreamCalls": 11, + }]), + ), + ) + .expect("an ordinary record type compiles"); + } + /// The same authored bytes compile to the same rendered bytes. #[test] fn the_document_is_deterministic() { diff --git a/docs/site/src/content/docs/configure/adapter.mdx b/docs/site/src/content/docs/configure/adapter.mdx index f217225070..20bab82d87 100644 --- a/docs/site/src/content/docs/configure/adapter.mdx +++ b/docs/site/src/content/docs/configure/adapter.mdx @@ -671,9 +671,10 @@ Response custody and terminal audit remain one PostgreSQL transaction. {/* Evidence: crates/registry-adapter/tests/oauth_served_route.rs */} {/* TODO[evidence]: allowedClients admission and the required non-empty list have no test located by symbol in the files searched */} -Every facade call is authenticated with an OIDC bearer token through the platform block, as in every Registry Stack product. +Every facade operation call is authenticated with an OIDC bearer token through the platform block, as in every Registry Stack product. It is authorised by the Adapter's own access profiles: named bindings of scopes to concrete facade operations and record types, declared in the project. -The facade accepts no API keys, no Basic authentication and no anonymous calls. +The facade accepts no API keys, no Basic authentication and no anonymous operation calls. +The one exception is the two listener probes, `GET /health` and `GET /ready`, which answer anyone with a fixed body and read nothing the caller names. [Probe health and readiness](../../operate/adapter/#probe-health-and-readiness) describes them. The Adapter inherits no authorisation from any product and grants none to any source. The caller's token is never forwarded upstream. diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index 835074ae82..14bfb9eb4b 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -31,13 +31,17 @@ loopback addresses, and `a.localhost` and `localhost.` stay named hosts. A plain `http://` origin named by host name now fails the runtime check with `adapter.runtime.insecure-origin` when `allowedPrivateCidrs` is empty. -- The facade listener answers `GET /health` and `GET /ready` without +- BREAKING: the facade listener answers `GET /health` and `GET /ready` without authentication. `/health` answers `{"status":"ok"}`. `/ready` answers `{"status":"ready"}` when the journal migrations match the binary and the runtime role holds its journal privileges, and a constant 503 `{"status":"not-ready"}` otherwise. The bodies never vary with the project. A project operation whose facade path is `/health` or `/ready` is - unserved under `adapter.operation.reserved-facade-path`. + unserved under `adapter.operation.reserved-facade-path`. To migrate, rename + the record type or change the operation path so no binding's concrete path + is `/health`, `/ready` or the effective-contract path. `adapterctl check` + refuses such a binding with `adapter.project.reserved-facade-path` and + `adapterctl compile` refuses it with `adapterctl.compile.reserved-path`. - `adapter serve` grants the runtime database role the table privileges its deployment needs, after it migrates and before it listens, when the runtime and migration sessions run as different roles. The grantee is the role the diff --git a/products/adapter/fixtures/corpus/README.md b/products/adapter/fixtures/corpus/README.md index 8760f79a63..4f445c73b5 100644 --- a/products/adapter/fixtures/corpus/README.md +++ b/products/adapter/fixtures/corpus/README.md @@ -138,6 +138,7 @@ and deployment custody aligned. Each refuses with its directory's exact code. | `adapter.pack.async-status-route-unsafe` | The status closure contains an idempotent custody processor | checks | | `adapter.profile.async-status-path-collision` | An ordinary concrete GET path collides with the host status path | checks | | `adapter.project.async-declaration-mismatch` | The binding omits completion while profile and source declare it | checks | +| `adapter.project.reserved-facade-path` | A binding's concrete path is `/health`, which the listener answers itself | checks | | `adapter.route.resume-invalid` | A safe single-send route carries a resume binding outside an admitted linear write plan | checks | | `adapter.runtime.async-idempotency-required` | The runtime omits exact-response custody for an asynchronous binding | checks with runtime | | `adapter.runtime.async-wait-exceeds-retention` | The bounded wait equals, rather than stays below, custody retention | checks with runtime | diff --git a/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/pack.yaml b/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/pack.yaml new file mode 100644 index 0000000000..c76a4d89b7 --- /dev/null +++ b/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/pack.yaml @@ -0,0 +1,46 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/adapter/pack/pack.v1alpha1.schema.json +# +# Bad-corpus member adapter.project.reserved-facade-path: this artifact set must be refused with +# exactly adapter.project.reserved-facade-path. Clean baseline pack; another artifact carries the defect. +# +# Refuse with: +# target/debug/adapterctl check products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/project.yaml +apiVersion: id.registrystack.org/formats/adapter/pack/v1alpha1 +kind: AdapterPack +id: case-api-pack +version: "1" +testedVersions: + - "1.0" +endpoints: + - id: cases + component: http + authentication: + type: basic + attemptTimeoutMilliseconds: 10000 + maximumResponseBytes: 1048576 +routeTemplates: + - id: find-cases + parameters: + - name: type + type: string + required: false + - name: case_id + type: string + required: false + steps: + - to: + uri: http:cases + parameters: + httpMethod: GET + path: /v2/cases/{{type}}/{{case_id}} + pathParameters: + type: + constant: welfare + case_id: + header: recordId + query: + _format: + constant: json + filter[region]: + constant: west +capabilities: {} diff --git a/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/profile.yaml b/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/profile.yaml new file mode 100644 index 0000000000..6020016097 --- /dev/null +++ b/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/profile.yaml @@ -0,0 +1,37 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/adapter/profile/profile.v1alpha1.schema.json +# +# Bad-corpus member adapter.project.reserved-facade-path: this artifact set must be refused with +# exactly adapter.project.reserved-facade-path. Clean baseline profile; the project binds record type `health` to this operation, whose concrete path is then `/health`. +# +# Refuse with: +# target/debug/adapterctl check products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/project.yaml +apiVersion: id.registrystack.org/formats/adapter/profile/v1alpha1 +kind: AdapterProfile +id: case-api +version: "1" +operations: + - id: cases-get + method: GET + path: /{type} + pathParameters: + - type + recordTypeParameter: type + responseEnvelope: '{"case": {{record}}, "fetchedAt": "{{requestId}}"}' +problems: + - code: cases.upstream + status: 502 + title: the source could not be reached + classes: [upstream, breaker.open, throttle.rejected, loop.maximum-iterations-reached] + - code: cases.mapping + status: 422 + title: the request or its mapping was refused + classes: [validation, conversion.unmapped, aggregation.duplicate] + - code: cases.exhausted + status: 502 + title: the run exhausted a budget + classes: [script, budget.exhausted] + - code: cases.boundary + status: 500 + title: the facade refused the call + classes: [disclosure.violation, egress.refused, credential.rejected, outcome, facade] +problemEnvelope: '{"family": "{{problemCode}}"}' diff --git a/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/project.yaml b/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/project.yaml new file mode 100644 index 0000000000..e642ed7999 --- /dev/null +++ b/products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/project.yaml @@ -0,0 +1,43 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/adapter/project/project.v1alpha1.schema.json +# +# Bad-corpus member adapter.project.reserved-facade-path: this artifact set must be refused with +# exactly adapter.project.reserved-facade-path. The binding's concrete path is `/health`, which the listener answers itself, so the binding would be advertised and never served. +# +# Refuse with: +# target/debug/adapterctl check products/adapter/fixtures/corpus/bad/adapter.project.reserved-facade-path/project.yaml +apiVersion: id.registrystack.org/formats/adapter/project/v1alpha1 +kind: AdapterProject +project: + id: case-api-example + version: "1" +profile: + id: case-api + version: "1" + digest: sha256:61b726c7e21aa6d434f91bbbdbdb2ea5aa2a8c880506e82abc3e87b8b7fad14e +pack: + id: case-api-pack + version: "1" + digest: sha256:a83e595f8183464fa6c459e8bd1fab44123bcb92a619feb8b0a84ca4753517b6 +recordTypes: + - name: health + fields: + - name: case_type + type: string + required: true +templatedRoutes: + - routeTemplate: find-cases + routeId: case-find +bindings: + - id: case-get + operation: cases-get + recordType: health + route: case-find + maximumUpstreamCalls: 4 +accessProfiles: + - id: case-reader + scopes: + - cases.read + operations: + - cases-get + recordTypes: + - health From 4e27b2d68aa09f4ba5e63ee60d166115a268f680 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:50:03 +0100 Subject: [PATCH 043/136] docs(messaging): record the provision verb and test its refusals - The changelog records messagingctl provision: the roles and database from the runtime file's two URLs over verified TLS, the runtime role's USAGE on public restored by running it again, and --print-sql. - messagingctl dev, not rstack dev, writes allowedClients: from-package, and the configuration reference describes from-package. - provision tests cover the loader refusals with no password in either stream, assert that a second run creates nothing, check the stderr of the two-administrator refusal, and match the quoted CREATE DATABASE. Signed-off-by: Jeremi Joslin --- .../tests/provision_cli.rs | 97 +++++++++++++++++-- .../tests/provision_postgres.rs | 3 + .../reference/messaging-configuration.mdx | 4 +- products/messaging/CHANGELOG.md | 8 +- 4 files changed, 103 insertions(+), 9 deletions(-) diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs index cacbe39cce..acc1e64853 100644 --- a/crates/registry-messagingctl/tests/provision_cli.rs +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -117,9 +117,10 @@ fn print_sql_writes_the_script_and_no_password() { let stderr = String::from_utf8(output.stderr).unwrap(); assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); assert!(stderr.is_empty(), "{stderr}"); - for name in ["messaging_migration", "messaging_runtime", "messaging"] { + for name in ["messaging_migration", "messaging_runtime"] { assert!(stdout.contains(name), "the script names {name}: {stdout}"); } + assert!(stdout.contains("CREATE DATABASE \"messaging\""), "{stdout}"); assert!(stdout.contains("CREATE ROLE"), "{stdout}"); assert!(stdout.contains("\\password"), "{stdout}"); for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { @@ -192,11 +193,95 @@ fn both_administrator_flags_are_refused() { vec!["provision", "--runtime-config", &runtime], ] { let output = ctl(&arguments); - assert_eq!( - output.status.code(), - Some(2), - "{arguments:?}: {}", - String::from_utf8_lossy(&output.stderr) + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{arguments:?}: {stderr}"); + // clap also answers 2 for an unknown verb, so the text names the flags. + assert!( + stderr.contains("--admin-url") || stderr.contains("--print-sql"), + "{arguments:?}: {stderr}" ); } } + +/// The refusal `provision --print-sql --format json` reports, with the exit +/// code. The reports carry no password, so neither does their text. +fn refusal(runtime: &str) -> (Option, serde_json::Value) { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!( + !stdout.contains(secret), + "stdout holds no password: {stdout}" + ); + assert!( + !stderr.contains(secret), + "stderr holds no password: {stderr}" + ); + } + let report = serde_json::from_str(&stdout) + .unwrap_or_else(|error| panic!("a JSON report: {error}: {stdout}{stderr}")); + (output.status.code(), report) +} + +fn first_diagnostic(report: &serde_json::Value) -> &serde_json::Value { + &report["diagnostics"][0] +} + +#[test] +fn a_missing_runtime_url_secret_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + let (code, report) = refusal(&runtime); + assert_eq!(code, Some(1), "{report:#}"); + let diagnostic = first_diagnostic(&report); + assert_eq!(diagnostic["code"], "config.refused", "{report:#}"); + assert_eq!(diagnostic["path"], "/database/runtimeUrlRef", "{report:#}"); +} + +#[test] +fn a_migration_url_secret_that_is_not_text_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let secret = directory.path().join("secrets/migration-database-url"); + std::fs::write(&secret, [0xff, 0xfe, 0xfd]).unwrap(); + let (code, report) = refusal(&runtime); + assert_eq!(code, Some(1), "{report:#}"); + let diagnostic = first_diagnostic(&report); + assert_eq!(diagnostic["code"], "config.refused", "{report:#}"); + assert_eq!( + diagnostic["path"], "/database/migrationUrlRef", + "{report:#}" + ); + assert!( + diagnostic["message"] + .as_str() + .unwrap() + .contains("not UTF-8"), + "{report:#}" + ); +} + +#[test] +fn a_runtime_file_that_does_not_load_is_refused_before_any_database_work() { + let directory = scratch(); + let missing = directory.path().join("no-such-runtime.yaml"); + let (code, report) = refusal(missing.to_str().unwrap()); + assert_eq!(code, Some(1), "{report:#}"); + assert_eq!(report["executed"], false, "{report:#}"); + assert!( + !first_diagnostic(&report)["code"] + .as_str() + .unwrap() + .is_empty(), + "{report:#}" + ); +} diff --git a/crates/registry-messagingctl/tests/provision_postgres.rs b/crates/registry-messagingctl/tests/provision_postgres.rs index 59d48bf16c..611f04e31e 100644 --- a/crates/registry-messagingctl/tests/provision_postgres.rs +++ b/crates/registry-messagingctl/tests/provision_postgres.rs @@ -231,6 +231,9 @@ async fn provision_then_apply_then_serve_with_split_roles() { admin_file.to_str().unwrap(), ]); assert_eq!(code, 0, "a second run converges: {again:#}"); + for statement in again["statements"].as_array().unwrap() { + assert_ne!(statement["outcome"], "created", "{statement}"); + } let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); assert_eq!(code, 0, "{applied:#}"); diff --git a/docs/site/src/content/docs/reference/messaging-configuration.mdx b/docs/site/src/content/docs/reference/messaging-configuration.mdx index 23366516ce..da004fa74e 100644 --- a/docs/site/src/content/docs/reference/messaging-configuration.mdx +++ b/docs/site/src/content/docs/reference/messaging-configuration.mdx @@ -157,8 +157,8 @@ The runtime requires TLS on both. `database.testOnlyPlaintext: true` is accepted only by a build that carries the `postgres-test` feature. `authentication.oidc` requires `issuer`, `audience`, and `allowedClients`. -`allowedClients` lists at least one distinct client, and every requester client that an access profile names must be listed; a profile that no admitted client could reach is refused at load. -An omitted member, an empty list, and a repeated client are refused when the file is read, and so is the `unrestricted` keyword that the sibling runtimes accept on development loopback. +`allowedClients` is required. Write `from-package` to admit exactly the requester clients of the package's access profiles, so the clients are written once, in the package. A list is also accepted. It lists at least one distinct client and must include every requester client that an access profile names, or the runtime refuses to start with `messaging.runtime.profile-client-not-allowed`. A profile that no admitted client could reach is refused at load. +An omitted member, an empty list, and a repeated client are refused when the file is read, and so is the `unrestricted` keyword that the sibling runtimes accept on development loopback, with `messaging.runtime.allowed-clients-required`. `scopeClaim` defaults to `scope`. `jwksSource` defaults to issuer discovery and can instead select `{type: static, documentRef: secret:...}` or `{type: uri, uri: HTTPS_URL}`. The former `jwksUri` member is refused. diff --git a/products/messaging/CHANGELOG.md b/products/messaging/CHANGELOG.md index ddf897035e..a351fc1fb3 100644 --- a/products/messaging/CHANGELOG.md +++ b/products/messaging/CHANGELOG.md @@ -16,6 +16,12 @@ refused at startup under `messaging.runtime.unreadable-jwks-secret`, with the rule it broke, and `messagingctl` names the rule when it refuses a borrowed owner's key set. A public member the service does not know loads. +- `messagingctl provision --runtime-config FILE` creates the migration and + runtime roles and the database from the runtime file's two database URLs, as + a non-superuser administrator over verified TLS, or prints the script with + `--print-sql`. It also grants the runtime role USAGE on the `public` schema, + and running it again restores that grant. The operate page no longer gives + hand SQL. - A plain `http` provider base URL and an SMTP relay in development use the same loopback rule: `127.0.0.0/8`, `::1`, or an IPv4-mapped form of `127.0.0.0/8`. The name `localhost` is accepted for a provider base URL as @@ -25,7 +31,7 @@ which admits the requester clients of the package's access profiles, so the clients are written once, in the package. The member stays required, and an omitted member, an empty list and `unrestricted` are still refused. A list - must still include every client a profile names. `rstack dev` writes + must still include every client a profile names. `messagingctl dev` writes `from-package`. - `registry-messaging-client` accepts an empty body or a JSON object of at From 069cf8500b25d717eb403bbdac1a6a16021b615e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:50:19 +0100 Subject: [PATCH 044/136] fix(platform): read the failed check in the acceptance journeys The own-provider and promote journeys read failed_check from a refusal line and map it onto their stage words, so they keep working now that every runtime names the failed check. The journeys README says which member they read. Signed-off-by: Jeremi Joslin --- products/platform/journeys/README.md | 6 ++- products/platform/journeys/own-provider.sh | 29 +++++++++++-- products/platform/journeys/promote.sh | 29 +++++++++++-- .../platform/journeys/test_journey_tables.py | 43 +++++++++++++++++++ 4 files changed, 100 insertions(+), 7 deletions(-) diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index 074577dcf9..7c56084f3d 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -49,7 +49,11 @@ forms. step named in the form found nothing to work with, lost the written record or refused the reader's own setup. - `http..`: a refused call. The stage is one of the - authentication stages the shared OIDC crate reports. + authentication stages the shared OIDC crate reports. The journeys read it + from the product's `stage` log field or from the `failed_check` label of its + refusal line, mapped onto the stage words (for example `token-key` is `key` + and `credential-malformed` is `header`). A label with no stage word leaves the + stage empty, and the cell records the problem code instead. - `product.`: the diagnostic code a product prints. Each row has a `basis`. A `predicted` row was inferred from reading the code. A diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index c6b10e5ca8..8b7655fef6 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -961,18 +961,41 @@ missing_claims() { journey_harness_failure "cannot read the claims of the token of $CELL" } -# logged_stage FILE...: the last authentication stage the product logged. +# logged_stage FILE...: the last authentication stage the product logged, +# from its `stage` field or the `failed_check` label of its refusal line. logged_stage() { perl -e ' my $stage = ""; + my %check_stage = ( + "credential-malformed" => "header", + "token-algorithm" => "algorithm", + "token-type" => "token-type", + "token-key" => "key", + "token-signature" => "signature", + "token-issuer" => "issuer", + "token-audience" => "audience", + "token-time" => "time", + "token-client" => "client", + "token-assertion-issuer" => "client", + "scope" => "scope", + "key-source-unavailable" => "unavailable", + ); local $/; for my $path (@ARGV) { open my $fh, "<", $path or next; my $text = <$fh>; next unless defined $text; $text =~ s/\e\[[0-9;]*m//g; - while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2/g) { - $stage = defined $1 ? $1 : $3; + # A product logs `stage`, or the refusal recorder `failed_check` + # label, which the map turns into the stage word the table lists. + # A label with no stage word is skipped, so the problem code names + # the refusal instead. + while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2|\bfailed_check"?[:=]\s*"([a-z]+(?:-[a-z]+)*)"/g) { + if (defined $4) { + $stage = $check_stage{$4} if exists $check_stage{$4}; + } else { + $stage = defined $1 ? $1 : $3; + } } } print $stage;' "$@" diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 139d0e32a8..91b2ef82dd 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -378,18 +378,41 @@ claim_names() { journey_harness_failure "cannot read the claims of the token of $CELL" } -# logged_stage FILE...: the last authentication stage the product logged. +# logged_stage FILE...: the last authentication stage the product logged, +# from its `stage` field or the `failed_check` label of its refusal line. logged_stage() { perl -e ' my $stage = ""; + my %check_stage = ( + "credential-malformed" => "header", + "token-algorithm" => "algorithm", + "token-type" => "token-type", + "token-key" => "key", + "token-signature" => "signature", + "token-issuer" => "issuer", + "token-audience" => "audience", + "token-time" => "time", + "token-client" => "client", + "token-assertion-issuer" => "client", + "scope" => "scope", + "key-source-unavailable" => "unavailable", + ); local $/; for my $path (@ARGV) { open my $fh, "<", $path or next; my $text = <$fh>; next unless defined $text; $text =~ s/\e\[[0-9;]*m//g; - while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2/g) { - $stage = defined $1 ? $1 : $3; + # A product logs `stage`, or the refusal recorder `failed_check` + # label, which the map turns into the stage word the table lists. + # A label with no stage word is skipped, so the problem code names + # the refusal instead. + while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2|\bfailed_check"?[:=]\s*"([a-z]+(?:-[a-z]+)*)"/g) { + if (defined $4) { + $stage = $check_stage{$4} if exists $check_stage{$4}; + } else { + $stage = defined $1 ? $1 : $3; + } } } print $stage;' "$@" diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index ff3b1557ce..6491fd6e41 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -13,6 +13,8 @@ import os import re +import subprocess +import tempfile import unittest from pathlib import Path @@ -276,5 +278,46 @@ def test_realm_import_has_no_protocol_mappers(self): self.assertNotIn("protocolMappers", realm.read_text(encoding="utf-8")) +class LoggedStage(unittest.TestCase): + """`logged_stage` reads a refused call's stage from `stage` or from `failed_check`.""" + + CASES = ( + ('{"stage":"token-type","msg":"refused"}', "token-type"), + ("WARN refused stage=audience", "audience"), + ('INFO request refused decision="refused" failed_check="token-type" suppressed=0', "token-type"), + ('{"fields":{"decision":"refused","failed_check":"credential-malformed"}}', "header"), + ('failed_check="token-client"', "client"), + ('failed_check="token-assertion-issuer"', "client"), + ('failed_check="key-source-unavailable"', "unavailable"), + ('failed_check="token-key"\nfailed_check="token-time"', "time"), + ('failed_check="credential-missing"', ""), + ('failed_check="token-time"\nfailed_check="operation"', "time"), + ("no refusal here", ""), + ) + + @staticmethod + def function(script: str) -> str: + text = (TABLES / script).read_text(encoding="utf-8") + match = re.search(r"^logged_stage\(\) \{\n.*?^\}\n", text, re.S | re.M) + assert match, f"{script} has no logged_stage" + return match.group(0) + + def test_the_stage_reads_both_log_fields(self): + for script in ("own-provider.sh", "promote.sh"): + function = self.function(script) + for log, expected in self.CASES: + with self.subTest(script=script, log=log): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "server.log" + path.write_text(log + "\n", encoding="utf-8") + result = subprocess.run( + ["bash", "-c", function + '\nlogged_stage "$1"', "bash", str(path)], + capture_output=True, + text=True, + check=True, + ) + self.assertEqual(result.stdout, expected) + + if __name__ == "__main__": unittest.main() From dd5ba24a067b37a52101a9af70ee3bbe11b88989 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 07:54:28 +0100 Subject: [PATCH 045/136] docs: record the provision verb in Scheduling and BReg and test its refusals docs(scheduling): record the provision verb and test its refusals - The changelog records schedulingctl provision: the administrator URL on the same host and port, the two login roles, the database closed to PUBLIC, each role's grants, what a second run does, --print-sql and --format json. - The operate page says the administrator URL must name the product URLs' host and port, lists the runtime role's USAGE on public, and shows the script the built tool prints. - provision tests cover the loader refusals with no password in either stream, assert that a second run creates nothing, check the stderr of the two-administrator refusal, and match the quoted CREATE DATABASE. - The database isolation check lists provision_postgres among the suites that stay opt-in. docs(breg): record the provision verb and test its refusals - The changelog records bregctl provision: the two login roles and the database closed to PUBLIC, btree_gist and the five managed schemas owned by the migration role, the PostGIS schema and bounding-box role with a spatial package, --print-sql, and what a second run does. - The help text and the operate page give the runtime role's grants as provision makes them: CONNECT on the database, and USAGE on the PostGIS schema with a spatial package. The page says what to do when the PostGIS extension is present but incomplete, and shows the script the built tool prints. - provision tests cover the loader refusals and a URL user that differs from database.roles, with no password in either stream, and the PostgreSQL test removes its roles and database even when an assertion fails. Signed-off-by: Jeremi Joslin --- crates/registry-bregctl/src/lib.rs | 5 +- .../registry-bregctl/tests/provision_cli.rs | 88 +++++++++++ .../tests/provision_postgres.rs | 36 ++++- .../tests/provision_cli.rs | 138 ++++++++++++++---- .../tests/provision_postgres.rs | 6 + docs/site/src/content/docs/operate/breg.mdx | 27 +++- .../src/content/docs/operate/scheduling.mdx | 16 +- products/breg/CHANGELOG.md | 16 ++ products/scheduling/CHANGELOG.md | 11 ++ .../scripts/check_database_test_isolation.py | 1 + 10 files changed, 300 insertions(+), 44 deletions(-) diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index d4f359fdb7..52315a9ea4 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -257,9 +257,10 @@ enum Command { /// /// The runtime file's two database URLs name both roles, the database and both passwords. /// The administrator URL comes from a file or an environment variable, never from the command - /// line. The command grants the runtime role CONNECT and nothing else: apply grants the rest. + /// line. The command grants the runtime role CONNECT on the database: apply grants the rest. /// With --package, a package that needs PostGIS also gets its schema, extension and - /// bounding-box role, which CREATE EXTENSION postgis needs a superuser for. + /// bounding-box role, which CREATE EXTENSION postgis needs a superuser for, and both roles + /// get USAGE on the PostGIS schema. Provision(ProvisionCommand), /// Inspect and operate native Record timers through bounded audited commands. Timer(timer_operator_lifecycle::TimerArgs), diff --git a/crates/registry-bregctl/tests/provision_cli.rs b/crates/registry-bregctl/tests/provision_cli.rs index c2d26130e3..1ae1a291a6 100644 --- a/crates/registry-bregctl/tests/provision_cli.rs +++ b/crates/registry-bregctl/tests/provision_cli.rs @@ -228,3 +228,91 @@ fn a_package_that_is_not_a_package_is_refused_before_any_connection() { assert_eq!(report["ok"], false, "{stdout}"); assert_eq!(report["executed"], false, "{stdout}"); } + +/// Runs `provision --print-sql --format json`, asserts the runtime file was +/// refused with exit 1 and no password anywhere in the output, and returns the +/// first diagnostic's code and path. The loader makes the checks `apply` +/// makes before it resolves the URLs itself, so these are the runtime file's +/// own codes. +fn loader_refusal(runtime: &str) -> (String, String) { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + runtime, + "--print-sql", + ]); + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert_eq!(output.status.code(), Some(1), "{stdout}{stderr}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!( + !stdout.contains(secret) && !stderr.contains(secret), + "a refusal prints no password" + ); + } + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["ok"], false, "{stdout}"); + assert_eq!(report["executed"], false, "{stdout}"); + let diagnostic = &report["diagnostics"][0]; + ( + diagnostic["code"].as_str().unwrap().to_owned(), + diagnostic["path"].as_str().unwrap().to_owned(), + ) +} + +#[test] +fn a_missing_runtime_url_secret_is_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + assert_eq!( + loader_refusal(&runtime), + ("breg.runtime.secret".to_owned(), String::new()) + ); +} + +#[test] +fn a_runtime_url_that_is_not_utf8_is_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let secret = directory.path().join("secrets/runtime-database-url"); + std::fs::write(&secret, [0xff, 0xfe, 0xfd]).unwrap(); + assert_eq!( + loader_refusal(&runtime), + ("breg.runtime.secret".to_owned(), String::new()) + ); +} + +#[test] +fn a_url_user_that_differs_from_the_runtime_role_is_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let secret = directory.path().join("secrets/runtime-database-url"); + std::fs::write( + &secret, + format!("postgresql://someone_else:{RUNTIME_PASSWORD}@db.invalid:5432/registry"), + ) + .unwrap(); + let (code, path) = loader_refusal(&runtime); + assert_eq!(code, "breg.runtime.invalid-database"); + assert_eq!(path, "/database"); +} + +#[test] +fn a_missing_ca_bundle_is_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let text = std::fs::read_to_string(&runtime).unwrap(); + let with_ca = text.replace( + " pool:\n", + " caBundleRef: secret:file/no-such-ca.pem\n pool:\n", + ); + assert_ne!(text, with_ca, "the runtime file gains the CA reference"); + std::fs::write(&runtime, with_ca).unwrap(); + assert_eq!( + loader_refusal(&runtime), + ("breg.runtime.secret".to_owned(), String::new()) + ); +} diff --git a/crates/registry-bregctl/tests/provision_postgres.rs b/crates/registry-bregctl/tests/provision_postgres.rs index bd94d943cd..8290300cd5 100644 --- a/crates/registry-bregctl/tests/provision_postgres.rs +++ b/crates/registry-bregctl/tests/provision_postgres.rs @@ -371,8 +371,14 @@ impl Deployment { ]); build.join("package") } +} - async fn finish(self) { +/// Removes the databases and roles the suite created, whether the test passed +/// or an assertion failed. The statements run on a thread of their own with a +/// fresh session, so they do not depend on the test's runtime, which may be +/// unwinding. +impl Drop for Deployment { + fn drop(&mut self) { // Dropping a database waits for its sessions to end, which the // administrator session's statement timeout would cut short. let mut statements: Vec = vec!["SET statement_timeout = 0".to_owned()]; @@ -388,8 +394,30 @@ impl Deployment { for role in [&self.runtime_role, &self.migration, &self.owner] { statements.push(format!("DROP ROLE IF EXISTS {role}")); } - for statement in statements { - self.admin.batch_execute(&statement).await.unwrap(); + let (base_url, ca) = (self.base_url.clone(), self.ca.clone()); + let cleanup = std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime for the cleanup") + .block_on(async { + let admin = connect_verified(&base_url, &ca, None).await; + for statement in statements { + admin + .batch_execute(&statement) + .await + .unwrap_or_else(|error| { + panic!("cleanup statement `{statement}` failed: {error}") + }); + } + }); + }); + if let Err(failure) = cleanup.join() { + if std::thread::panicking() { + eprintln!("the suite's databases and roles were not removed: {failure:?}"); + } else { + std::panic::resume_unwind(failure); + } } } } @@ -481,7 +509,6 @@ async fn provision_then_apply_then_serve_with_split_roles() { assert!(ready, "the readiness route answers"); stop.send(()).unwrap(); server.await.unwrap().expect("the server stops cleanly"); - deployment.finish().await; } /// A package with a polygon field needs PostGIS, and `CREATE EXTENSION @@ -518,5 +545,4 @@ async fn spatial_package_as_a_non_superuser_owner_names_the_postgis_statement() "{refused:#}" ); assert_eq!(diagnostic["path"], "extension.postgis", "{refused:#}"); - deployment.finish().await; } diff --git a/crates/registry-schedulingctl/tests/provision_cli.rs b/crates/registry-schedulingctl/tests/provision_cli.rs index 2dd371aa18..b0709fdab4 100644 --- a/crates/registry-schedulingctl/tests/provision_cli.rs +++ b/crates/registry-schedulingctl/tests/provision_cli.rs @@ -126,9 +126,13 @@ fn print_sql_writes_the_script_and_no_password() { let stderr = String::from_utf8(output.stderr).unwrap(); assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); assert!(stderr.is_empty(), "{stderr}"); - for name in ["scheduling_migration", "scheduling_runtime", "scheduling"] { + for name in ["scheduling_migration", "scheduling_runtime"] { assert!(stdout.contains(name), "the script names {name}: {stdout}"); } + assert!( + stdout.contains("CREATE DATABASE \"scheduling\""), + "{stdout}" + ); assert!(stdout.contains("CREATE ROLE"), "{stdout}"); assert!(stdout.contains("\\password"), "{stdout}"); for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { @@ -180,33 +184,115 @@ fn print_sql_as_json_reports_nothing_executed() { fn both_administrator_flags_are_refused() { let directory = scratch(); let runtime = write_runtime(directory.path()); - for arguments in [ - vec![ - "provision", - "--runtime-config", - &runtime, - "--admin-url-file", - "/nonexistent/admin-url", - "--admin-url-env", - "SCHEDULING_ADMIN_URL", - ], - vec![ - "provision", - "--runtime-config", - &runtime, - "--print-sql", - "--admin-url-env", - "SCHEDULING_ADMIN_URL", - ], - vec!["provision", "--runtime-config", &runtime], + for (arguments, message) in [ + ( + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "SCHEDULING_ADMIN_URL", + ], + "conflicting use of --admin-url-file", + ), + ( + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "SCHEDULING_ADMIN_URL", + ], + "conflicting use of --print-sql", + ), + ( + vec!["provision", "--runtime-config", &runtime], + "missing required argument --admin-url-file, --admin-url-env", + ), ] { let output = ctl(&arguments); - assert_eq!( - output.status.code(), - Some(2), - "{arguments:?}: {}", - String::from_utf8_lossy(&output.stderr) - ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{arguments:?}: {stderr}"); assert!(output.stdout.is_empty(), "{arguments:?}"); + assert!(stderr.contains(message), "{arguments:?}: {stderr}"); } } + +/// Runs `provision --print-sql --format json` over the runtime file and +/// returns the exit code, the first diagnostic and the whole output. +fn refusal(runtime: &str) -> (Option, serde_json::Value, String) { + let output = ctl(&[ + "provision", + "--runtime-config", + runtime, + "--print-sql", + "--format", + "json", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + let report: serde_json::Value = + serde_json::from_str(&stdout).unwrap_or_else(|error| panic!("{error}: {stdout}{stderr}")); + let diagnostic = report["diagnostics"][0].clone(); + ( + output.status.code(), + diagnostic, + format!("{stdout}{stderr}"), + ) +} + +fn assert_refused_at( + (code, diagnostic, output): (Option, serde_json::Value, String), + path: &str, +) { + assert_eq!(code, Some(1), "{output}"); + assert_eq!(diagnostic["code"], "config.refused", "{output}"); + assert_eq!(diagnostic["path"], path, "{output}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!output.contains(secret), "the refusal holds no password"); + } +} + +#[test] +fn a_missing_runtime_url_secret_is_refused_without_a_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + assert_refused_at(refusal(&runtime), "/database/runtimeUrlRef"); +} + +#[test] +fn a_missing_migration_url_secret_is_refused_without_a_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/migration-database-url")).unwrap(); + assert_refused_at(refusal(&runtime), "/database/migrationUrlRef"); +} + +#[test] +fn a_runtime_url_secret_that_is_not_text_is_refused_without_a_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let path = directory.path().join("secrets/runtime-database-url"); + let mut bytes = RUNTIME_PASSWORD.as_bytes().to_vec(); + bytes.extend([0xff, 0xfe]); + std::fs::write(&path, bytes).unwrap(); + assert_refused_at(refusal(&runtime), "/database/runtimeUrlRef"); +} + +#[test] +fn a_missing_ca_bundle_secret_is_refused_without_a_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let document = std::fs::read_to_string(&runtime).unwrap(); + let with_ca = document.replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/postgres-ca.pem\n", + ); + assert_ne!(document, with_ca, "the runtime file names the CA bundle"); + std::fs::write(&runtime, with_ca).unwrap(); + assert_refused_at(refusal(&runtime), "/database/caBundleRef"); +} diff --git a/crates/registry-schedulingctl/tests/provision_postgres.rs b/crates/registry-schedulingctl/tests/provision_postgres.rs index 1cc5608403..9fcbd14251 100644 --- a/crates/registry-schedulingctl/tests/provision_postgres.rs +++ b/crates/registry-schedulingctl/tests/provision_postgres.rs @@ -233,6 +233,12 @@ async fn provision_then_apply_then_serve_with_split_roles() { admin_file.to_str().unwrap(), ]); assert_eq!(code, 0, "a second run converges: {again:#}"); + for statement in again["statements"].as_array().unwrap() { + assert_ne!( + statement["outcome"], "created", + "a second run creates nothing: {statement}" + ); + } let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); assert_eq!(code, 0, "{applied:#}"); diff --git a/docs/site/src/content/docs/operate/breg.mdx b/docs/site/src/content/docs/operate/breg.mdx index d0f996de4c..2ce0546077 100644 --- a/docs/site/src/content/docs/operate/breg.mdx +++ b/docs/site/src/content/docs/operate/breg.mdx @@ -306,6 +306,10 @@ flags. The command connects to nothing and prints the script. Each `CREATE ROLE` `\password` line that prompts for the password in `psql`, so the script holds no password: ```sql +-- provision script, product breg. Nothing was run. +-- For a server where these objects do not exist yet. Review, then run with psql as an +-- administrator that has CREATEROLE and CREATEDB. It stops at the first error. +\set ON_ERROR_STOP on SET createrole_self_grant = 'set,inherit'; CREATE ROLE "registry_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \password "registry_migration" @@ -318,7 +322,10 @@ ALTER DATABASE "registry" ALLOW_CONNECTIONS true; \connect "registry" CREATE EXTENSION btree_gist; CREATE SCHEMA "registry_internal" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_internal" FROM PUBLIC; --- the same two statements for registry_data, registry_source, registry_derived, registry_context +CREATE SCHEMA "registry_data" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_data" FROM PUBLIC; +CREATE SCHEMA "registry_source" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_source" FROM PUBLIC; +CREATE SCHEMA "registry_derived" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_derived" FROM PUBLIC; +CREATE SCHEMA "registry_context" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_context" FROM PUBLIC; ``` The names come from your URLs. Add `--format json` for a report of each statement and its outcome. @@ -330,8 +337,9 @@ with `migration role has database-level administrative authority`, which is also role that is a superuser or has `BYPASSRLS`, `CREATEDB`, or `CREATEROLE`. If a managed PostgreSQL service created the database for you, check its owner and its grants first. -`provision` grants the runtime role nothing beyond `CONNECT`. `apply` grants it what serving -needs. The package creates every table, function, and policy inside the five schemas. A missing +`provision` grants the runtime role `CONNECT` on the database, and `USAGE` on the PostGIS schema +when `--package` names a package that needs PostGIS. It grants no `USAGE` on `public`. `apply` +grants the runtime role what serving needs. The package creates every table, function, and policy inside the five schemas. A missing prerequisite surfaces at `test` or `apply`, never at runtime. ### Install PostGIS @@ -368,9 +376,16 @@ GRANT USAGE ON SCHEMA registry_spatial_ext TO registry_migration, registry_runtime, registry_runtime__spatial_bbox; ``` -A package that stores polygons and grants no bbox queries omits the bbox role, its membership, and -its name from the final `GRANT USAGE`. Keep the PostGIS schema, extension, and grants to the -migration and runtime roles. +For a package that stores polygons and grants no bbox queries, the statements above may leave out +the bbox role, its membership, and its name from the final `GRANT USAGE`. `provision --package` +plans the bbox role for every package that needs PostGIS, including that one. The role is unused +there: the runtime checks for it only when the package grants bbox queries. Keep the PostGIS +schema, extension, and grants to the migration and runtime roles. + +If `provision` stops with `platform.provision.extension-incomplete` at `extension.postgis`, PostGIS +exists in the database but outside `registry_spatial_ext`, or the migration role cannot `SET` the +bbox role. As a superuser, drop a PostGIS installed in another schema, run the statements of the +`extension.postgis` step that `--print-sql` prints, then run `provision` again. Size connections, timeouts, and statement statistics once the registry serves; see [Set a PostgreSQL baseline](../breg-monitor/#set-a-postgresql-baseline). diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index 4d7b7411b9..d18b4fa145 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -145,8 +145,10 @@ schedulingctl provision --runtime-config /etc/registry-scheduling/runtime.yaml - The `admin-url` file holds one PostgreSQL URL for that administrator, for example `postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and -`CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, -use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set +`CREATEDB` and does not need to be a superuser. The URL must name the same host and port as the two +product URLs, or `provision` refuses it as `platform.provision.target-mismatch`. To pass the URL in +an environment variable instead, use `--admin-url-env NAME`. The connection requires TLS and +verifies the server certificate. Set `database.caBundleRef` in the runtime file to trust a private CA. The command never prints the administrator URL or a password. @@ -155,8 +157,8 @@ The command: - Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. - Creates the database and closes it to `PUBLIC`. - Grants both roles `CONNECT` on the database. -- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it - from `PUBLIC`. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema, takes `CREATE` on it + from `PUBLIC`, and gives the runtime role `USAGE` on it. Run it again at any time. It creates only what is missing. It refuses a role that exists with a different password than its URL holds, and tells you which role. @@ -166,6 +168,10 @@ flags. The command connects to nothing and prints the script. Each `CREATE ROLE` `\password` line that prompts for the password in `psql`, so the script holds no password: ```sql +-- provision script, product scheduling. Nothing was run. +-- For a server where these objects do not exist yet. Review, then run with psql as an +-- administrator that has CREATEROLE and CREATEDB. It stops at the first error. +\set ON_ERROR_STOP on SET createrole_self_grant = 'set,inherit'; CREATE ROLE "scheduling_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \password "scheduling_migration" @@ -176,7 +182,7 @@ REVOKE ALL ON DATABASE "scheduling" FROM PUBLIC; GRANT CONNECT ON DATABASE "scheduling" TO "scheduling_migration", "scheduling_runtime"; ALTER DATABASE "scheduling" ALLOW_CONNECTIONS true; \connect "scheduling" -REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "scheduling_migration"; +REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "scheduling_migration"; GRANT USAGE ON SCHEMA public TO "scheduling_runtime"; ``` The names come from your URLs. Add `--format json` for a report of each statement and its outcome. diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index e455067d5b..df6533b78f 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +- `bregctl provision` creates the PostgreSQL objects a Registry needs, from the + two database URLs in its runtime file and an administrator URL read from + `--admin-url-file` or `--admin-url-env`. It creates or adopts the migration + and runtime login roles, each with no privilege beyond `LOGIN`, and the + database, closed to `PUBLIC`. Both roles get `CONNECT` on the database. It + installs `btree_gist` and creates the five managed schemas, each owned by + the migration role and closed to `PUBLIC`. The runtime role gets nothing + else, and no `USAGE` on `public`: `apply` grants the rest. With `--package` + and a package that needs PostGIS, it also installs PostGIS in + `registry_spatial_ext` (the step that needs a superuser), creates the + `__spatial_bbox` role, makes the migration role a member of + it, and grants `USAGE` on that schema to the migration, runtime and bbox + roles. `--print-sql` connects to nothing and prints the script, which holds + `\password` prompts and no password. Running the command again creates only + what is missing, and it refuses a role that exists with other attributes. + - BReg counts the requests it refuses by the check that refused it, in `breg_request_refusals_total{check}`, published at zero for every check from the first scrape. Each refusal writes one `request refused` line at `INFO` diff --git a/products/scheduling/CHANGELOG.md b/products/scheduling/CHANGELOG.md index 0a7d6c6bac..539f40568a 100644 --- a/products/scheduling/CHANGELOG.md +++ b/products/scheduling/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +- Add `schedulingctl provision`. From the two database URLs in the runtime file + and an administrator URL (`--admin-url-file` or `--admin-url-env`, a role + with `CREATEROLE` and `CREATEDB` on the same host and port, over verified + TLS), it creates the migration role and the runtime role, each with `LOGIN` + and no other privilege, and the database, closed to `PUBLIC`. Both roles get + `CONNECT` on the database. The migration role gets `USAGE` and `CREATE` on + the `public` schema, `CREATE` on it is taken from `PUBLIC`, and the runtime + role gets `USAGE` on it. Running it again creates only what is missing and + refuses a role that exists with a different password than its URL holds. + `--print-sql` connects to nothing and prints a `psql` script that prompts for + each password. `--format json` reports each statement and its outcome. - Scheduling counts every refused request by the check that refused it, in `scheduling_request_refusals_total{check}` on the metrics listener, published at zero for every check. Each refusal writes one diff --git a/products/scheduling/scripts/check_database_test_isolation.py b/products/scheduling/scripts/check_database_test_isolation.py index b806bf697a..9e3c7be019 100755 --- a/products/scheduling/scripts/check_database_test_isolation.py +++ b/products/scheduling/scripts/check_database_test_isolation.py @@ -15,6 +15,7 @@ "records_apply_postgres", "intents_postgres", "activation_postgres", + "provision_postgres", }, } From c99455c560c406c74d096fef1aad51ffb577f297 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 08:02:52 +0100 Subject: [PATCH 046/136] refactor(platform): remove the stage-labelled authentication log helpers Every runtime logs and counts refusals by failed check, so the second vocabulary in registry-platform-oidc goes: AuthenticationStage, AuthenticationDiagnostics, OidcError::authentication_stage, TokenVerifier::authentication_diagnostic, the log_authentication_refusal! macro and its tracing re-export, and the crate's tracing dependency. The token characterisation tests keep their expected tables. They name a verifier error's result value through one shared function, Outcome::refused_by in registry-platform-testing, in place of a copy per product. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 - .../src/serve/token_characterisation.rs | 8 +- crates/registry-breg/src/fixtures.rs | 2 +- .../src/access/token_characterisation.rs | 9 +- .../tests/token_characterisation.rs | 2 +- .../tests/token_characterisation.rs | 11 +- .../tests/token_characterisation.rs | 7 +- crates/registry-evidencectl/src/authoring.rs | 7 +- .../src/token_characterisation.rs | 12 +- .../tests/token_characterisation.rs | 2 +- crates/registry-platform-oidc/Cargo.toml | 1 - .../registry-platform-oidc/src/diagnostics.rs | 158 ------------------ crates/registry-platform-oidc/src/lib.rs | 24 +-- .../src/token_fixtures.rs | 42 +++++ .../src/auth/token_characterisation.rs | 9 +- .../tests/token_characterisation.rs | 2 +- .../configure/request-an-access-token.mdx | 4 +- products/platform/CHANGELOG.md | 7 + products/platform/journeys/own-provider.sh | 4 +- 19 files changed, 78 insertions(+), 234 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c87f419721..a755f8d6e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8051,7 +8051,6 @@ dependencies = [ "tempfile", "thiserror 2.0.21", "tokio", - "tracing", "uuid", ] diff --git a/crates/registry-adapter/src/serve/token_characterisation.rs b/crates/registry-adapter/src/serve/token_characterisation.rs index 3745536892..9321899e32 100644 --- a/crates/registry-adapter/src/serve/token_characterisation.rs +++ b/crates/registry-adapter/src/serve/token_characterisation.rs @@ -34,12 +34,6 @@ fn client_of(fixture: &TokenFixture) -> Option { literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) } -fn stage_of(error: &OidcError) -> Outcome { - format!("refused/{}", error.authentication_stage().label()) - .parse() - .expect("every authentication stage label is a result value") -} - fn runtime_for(case: &FixtureCase) -> AdapterRuntimeConfig { let client = client_of(&case.fixture).unwrap_or_else(|| PLACEHOLDER_CLIENT.into()); serde_json::from_value(json!({ @@ -74,7 +68,7 @@ async fn observe(authenticator: &Authenticator, token: &str) -> Outcome { error.failed_check(), "the refusal carries the check the verifier named" ); - stage_of(&error) + Outcome::refused_by(&error) } (Err(CallerRefusal::Unauthenticated(_)), Ok(_)) => { "refused/claims".parse().expect("result value") diff --git a/crates/registry-breg/src/fixtures.rs b/crates/registry-breg/src/fixtures.rs index 69227224e2..aeda7a7edf 100644 --- a/crates/registry-breg/src/fixtures.rs +++ b/crates/registry-breg/src/fixtures.rs @@ -6386,7 +6386,7 @@ mod tests { }; #[test] - fn fixture_authentication_diagnostics_distinguish_missing_claim_from_refused_credential() { + fn fixture_refusals_distinguish_missing_claim_from_refused_credential() { assert_eq!( fixture_authentication_error(crate::auth::AuthenticationError::MissingActorKind), FixtureError::AuthenticationActorKindMissing diff --git a/crates/registry-coordinator/src/access/token_characterisation.rs b/crates/registry-coordinator/src/access/token_characterisation.rs index b93c7d5baf..d292ce50c5 100644 --- a/crates/registry-coordinator/src/access/token_characterisation.rs +++ b/crates/registry-coordinator/src/access/token_characterisation.rs @@ -10,7 +10,6 @@ //! verifier for the check that refused a token and compare it with the check //! the refusal carries. use super::*; -use registry_platform_oidc::OidcError; use registry_platform_testing::{ ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, }; @@ -40,12 +39,6 @@ fn first_scope(fixture: &TokenFixture) -> Option { fixture.read_scope("scope") } -fn stage_of(error: &OidcError) -> Outcome { - format!("refused/{}", error.authentication_stage().label()) - .parse() - .expect("every authentication stage label is a result value") -} - async fn authenticator_for(case: &FixtureCase, secrets: &SecretProvidersConfig) -> Authenticator { let scope_claim = match case.configuration { Configuration::Recipe => "scope", @@ -92,7 +85,7 @@ async fn observe(authenticator: &Authenticator, token: &str) -> Outcome { Some(error.failed_check()), "the refusal names the verifier's check" ); - stage_of(&error) + Outcome::refused_by(&error) } (Err(error), Ok(_)) => { let (outcome, checks): (_, &[FailedCheck]) = match error.code.as_str() { diff --git a/crates/registry-documents/tests/token_characterisation.rs b/crates/registry-documents/tests/token_characterisation.rs index e3d49ecdee..baaec3727c 100644 --- a/crates/registry-documents/tests/token_characterisation.rs +++ b/crates/registry-documents/tests/token_characterisation.rs @@ -260,7 +260,7 @@ destinations: Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { let reference = TokenVerifier::new(config.verifier_profile(&admitted), keys); match reference.verify(token).await { - Err(failure) => refusal(failure.authentication_stage().label()), + Err(failure) => Outcome::refused_by(&failure), Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { if verified.scopes.iter().any(|held| held == &scope) { refusal("profile") diff --git a/crates/registry-evidence-oid4vci/tests/token_characterisation.rs b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs index 070161a043..c2fcad6e01 100644 --- a/crates/registry-evidence-oid4vci/tests/token_characterisation.rs +++ b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs @@ -129,13 +129,10 @@ async fn refusal_stage(config: &OfferAuthorizationConfig, case: &FixtureCase) -> Arc::new(JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults())), ); match verifier.verify(case.token.expose()).await { - Err(error) => { - let label = error.authentication_stage().label(); - match format!("refused/{label}").parse::() { - Ok(Outcome::Refused(stage)) => stage, - other => panic!("the verifier stage `{label}` is not a corpus stage: {other:?}"), - } - } + Err(error) => match Outcome::refused_by(&error) { + Outcome::Refused(stage) => stage, + other => panic!("the verifier error {error:?} is not a refusal: {other:?}"), + }, Ok(verified) => { let present: Vec<&str> = verified.scopes.iter().map(String::as_str).collect(); let scope_missing = config diff --git a/crates/registry-evidence/tests/token_characterisation.rs b/crates/registry-evidence/tests/token_characterisation.rs index 818981305c..0b30c348d2 100644 --- a/crates/registry-evidence/tests/token_characterisation.rs +++ b/crates/registry-evidence/tests/token_characterisation.rs @@ -164,10 +164,9 @@ async fn verifier_refusal(config: &OidcAuthenticationConfig, case: &FixtureCase) Arc::new(JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults())), ); let error = verifier.verify(case.token.expose()).await.err()?; - let label = error.authentication_stage().label(); - match format!("refused/{label}").parse::() { - Ok(Outcome::Refused(stage)) => Some(stage), - other => panic!("the verifier stage `{label}` is not a corpus stage: {other:?}"), + match Outcome::refused_by(&error) { + Outcome::Refused(stage) => Some(stage), + other => panic!("the verifier error {error:?} is not a refusal: {other:?}"), } } diff --git a/crates/registry-evidencectl/src/authoring.rs b/crates/registry-evidencectl/src/authoring.rs index c12d206463..e4afc75579 100644 --- a/crates/registry-evidencectl/src/authoring.rs +++ b/crates/registry-evidencectl/src/authoring.rs @@ -2260,7 +2260,10 @@ mod tests { .expect("a reviewed SQLite extract route opens no production channel"); } - fn assert_authentication_diagnostic(bundle: &Value, artifacts: &BTreeMap>) { + fn assert_authentication_mismatch_refused( + bundle: &Value, + artifacts: &BTreeMap>, + ) { let error = validate_source_authentication(bundle, artifacts) .expect_err("a pack and target that name different authentication must be refused"); let diagnostic = error @@ -2291,7 +2294,7 @@ mod tests { ); let artifacts = direct_http_pack(json!({"type": "static-authorization"})); - assert_authentication_diagnostic(&bundle, &artifacts); + assert_authentication_mismatch_refused(&bundle, &artifacts); } #[test] diff --git a/crates/registry-mcp-edge/src/token_characterisation.rs b/crates/registry-mcp-edge/src/token_characterisation.rs index 0d8bbcc327..5512ac82f4 100644 --- a/crates/registry-mcp-edge/src/token_characterisation.rs +++ b/crates/registry-mcp-edge/src/token_characterisation.rs @@ -20,9 +20,7 @@ use axum::{ Router, }; use registry_platform_audit::AuditProfile; -use registry_platform_oidc::{ - parse_static_jwks, JwksFetcher, JwksFetcherConfig, OidcError, TokenVerifier, -}; +use registry_platform_oidc::{parse_static_jwks, JwksFetcher, JwksFetcherConfig, TokenVerifier}; use registry_platform_testing::{ ClaimValue, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, }; @@ -99,12 +97,6 @@ fn fetcher_for(case: &FixtureCase) -> Arc { )) } -fn stage_of(error: &OidcError) -> Outcome { - format!("refused/{}", error.authentication_stage().label()) - .parse() - .expect("every authentication stage label is a result value") -} - async fn observe(case: &FixtureCase) -> Outcome { let options = options_for(case); let hasher = AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![5; 32])) @@ -149,7 +141,7 @@ async fn observe(case: &FixtureCase) -> Outcome { match (response.status(), verdict) { (StatusCode::OK, Ok(_)) => Outcome::Admitted(None), (StatusCode::OK, Err(_)) => panic!("the edge admitted a token its verifier refused"), - (_, Err(error)) => stage_of(&error), + (_, Err(error)) => Outcome::refused_by(&error), (StatusCode::FORBIDDEN, Ok(_)) => "refused/scope".parse().expect("result value"), (StatusCode::UNAUTHORIZED, Ok(_)) => "refused/claims".parse().expect("result value"), (StatusCode::SERVICE_UNAVAILABLE, Ok(_)) => { diff --git a/crates/registry-messaging/tests/token_characterisation.rs b/crates/registry-messaging/tests/token_characterisation.rs index 59b11f0cd7..55d1c23ddc 100644 --- a/crates/registry-messaging/tests/token_characterisation.rs +++ b/crates/registry-messaging/tests/token_characterisation.rs @@ -184,7 +184,7 @@ async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { let reference = TokenVerifier::new(config.verifier_profile(&admitted), keys); match reference.verify(token).await { - Err(failure) => refusal(failure.authentication_stage().label()), + Err(failure) => Outcome::refused_by(&failure), Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { if verified.scopes.iter().any(|held| held == &scope) { refusal("profile") diff --git a/crates/registry-platform-oidc/Cargo.toml b/crates/registry-platform-oidc/Cargo.toml index d5e3dadc83..7502e97725 100644 --- a/crates/registry-platform-oidc/Cargo.toml +++ b/crates/registry-platform-oidc/Cargo.toml @@ -30,7 +30,6 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true tokio.workspace = true -tracing.workspace = true [dev-dependencies] axum.workspace = true diff --git a/crates/registry-platform-oidc/src/diagnostics.rs b/crates/registry-platform-oidc/src/diagnostics.rs index 2ce828f3cb..99089d5851 100644 --- a/crates/registry-platform-oidc/src/diagnostics.rs +++ b/crates/registry-platform-oidc/src/diagnostics.rs @@ -1,82 +1,9 @@ //! Bounded diagnostic categories, independent of credential and configuration values. -use std::sync::{Mutex, PoisonError}; -use std::time::{Duration, Instant}; - use registry_platform_authcommon::FailedCheck; use crate::OidcError; -/// Fixed verification stages suitable for operational logs. -#[derive(Clone, Copy, Debug)] -pub enum AuthenticationStage { - Header, - Algorithm, - TokenType, - Key, - Signature, - Issuer, - Audience, - Time, - Client, - Scope, - Profile, - Unavailable, -} - -impl AuthenticationStage { - pub const fn label(self) -> &'static str { - match self { - Self::Header => "header", - Self::Algorithm => "algorithm", - Self::TokenType => "token-type", - Self::Key => "key", - Self::Signature => "signature", - Self::Issuer => "issuer", - Self::Audience => "audience", - Self::Time => "time", - Self::Client => "client", - Self::Scope => "scope", - Self::Profile => "profile", - Self::Unavailable => "unavailable", - } - } -} - -impl OidcError { - /// Never format the underlying error to diagnose a public authentication failure. - pub fn authentication_stage(&self) -> AuthenticationStage { - match self { - Self::MalformedToken | Self::InvalidToken | Self::SubjectMismatch => { - AuthenticationStage::Header - } - Self::AlgorithmNotAllowed => AuthenticationStage::Algorithm, - Self::TokenTypeNotAllowed => AuthenticationStage::TokenType, - Self::MissingKid | Self::KidTooLong | Self::UnknownKid => AuthenticationStage::Key, - Self::SignatureInvalid => AuthenticationStage::Signature, - Self::IssuerMismatch { .. } => AuthenticationStage::Issuer, - Self::AudienceMismatch => AuthenticationStage::Audience, - Self::TokenExpired | Self::TokenNotYetValid | Self::InvalidTimeClaims => { - AuthenticationStage::Time - } - Self::ClientNotAllowed | Self::AssertionIssuerNotAllowed => AuthenticationStage::Client, - Self::Transport(_) - | Self::BoundedRead(_) - | Self::FetchUrl(_) - | Self::HttpStatus(_) - | Self::InvalidUrl - | Self::Parse - | Self::InvalidJwk - | Self::EmptyKeySet - | Self::StaticKeySet(_) - | Self::MissingIssuer - | Self::ConflictingEndpointConfiguration - | Self::InsecureHttpRequiresOptIn - | Self::EndpointRefused { .. } => AuthenticationStage::Unavailable, - } - } -} - impl OidcError { /// The check a verification failure maps to. Never format the underlying /// error to diagnose a public authentication failure. @@ -117,91 +44,6 @@ impl OidcError { } } -/// Log one value-free refusal at the call site's own tracing target, at most -/// once per stage per minute per verifier. `$message` is a literal naming the -/// product; the optional `remedy` is a fixed operator hint. -#[macro_export] -macro_rules! log_authentication_refusal { - ($verifier:expr, $stage:expr, $message:literal $(, remedy = $remedy:expr)?) => { - if let Some(stage) = $verifier.authentication_diagnostic($stage) { - $crate::__tracing::info!(stage, $(remedy = $remedy,)? $message); - } - }; -} - -/// At most one diagnostic per fixed stage per minute, per verifier. -/// The fixed array cannot grow with attacker-controlled inputs. -#[derive(Debug, Default)] -pub struct AuthenticationDiagnostics { - last: Mutex<[Option; 12]>, -} - -impl AuthenticationDiagnostics { - pub fn admit(&self, stage: AuthenticationStage) -> bool { - self.admit_at(stage, Instant::now()) - } - - fn admit_at(&self, stage: AuthenticationStage, now: Instant) -> bool { - // The guarded state is plain timestamps, so a poisoned lock is safe to reuse. - let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); - let slot = &mut last[stage as usize]; - if slot.is_some_and(|previous| { - now.saturating_duration_since(previous) < Duration::from_secs(60) - }) { - return false; - } - *slot = Some(now); - true - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn malformed_tokens_remain_header_failures() { - assert_eq!( - OidcError::MalformedToken.authentication_stage().label(), - "header" - ); - assert_eq!( - OidcError::InvalidToken.authentication_stage().label(), - "header" - ); - } - - #[test] - fn diagnostics_are_value_free_and_bounded_per_stage() { - let error = OidcError::IssuerMismatch { - expected: "canary-expected-issuer".into(), - actual: "canary-actual-issuer".into(), - }; - let stage = error.authentication_stage(); - assert_eq!(stage.label(), "issuer"); - assert!(!format!("{stage:?}").contains("canary")); - let diagnostics = AuthenticationDiagnostics::default(); - let now = Instant::now(); - assert!(diagnostics.admit_at(stage, now)); - for _ in 0..1000 { - assert!(!diagnostics.admit_at(stage, now)); - } - assert!(diagnostics.admit_at(AuthenticationStage::Audience, now)); - assert!(diagnostics.admit_at(stage, now + Duration::from_secs(60))); - } - - #[test] - fn a_poisoned_lock_keeps_admitting_diagnostics() { - let diagnostics = AuthenticationDiagnostics::default(); - let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _guard = diagnostics.last.lock().unwrap(); - panic!("poison the lock"); - })); - assert!(poisoned.is_err()); - assert!(diagnostics.admit(AuthenticationStage::Header)); - } -} - #[cfg(test)] mod failed_check_tests { use crate::{OidcEndpoint, OidcError, StaticJwksError}; diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index 0c940a3b5b..641c783321 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -9,10 +9,7 @@ mod access_token_algorithm; mod authorization_claims; mod diagnostics; mod static_jwks; -pub use diagnostics::{AuthenticationDiagnostics, AuthenticationStage}; pub use static_jwks::{public_jwks_document, StaticJwksError}; -#[doc(hidden)] -pub use tracing as __tracing; pub mod task_grant; pub use access_token_algorithm::AccessTokenAlgorithm; @@ -1298,7 +1295,6 @@ impl VerifiedToken { #[derive(Debug)] pub struct TokenVerifier { - diagnostics: AuthenticationDiagnostics, config: TokenVerifierConfig, fetcher: Arc, allowed_clients: HashSet, @@ -1322,7 +1318,6 @@ impl TokenVerifier { let allowed_id_typ = normalize_typ_set(&config.allowed_id_typ); let allowed_userinfo_typ = normalize_typ_set(&config.allowed_userinfo_typ); Self { - diagnostics: AuthenticationDiagnostics::default(), config, fetcher, allowed_clients, @@ -1347,12 +1342,6 @@ impl TokenVerifier { self.verify_access_token(token, true).await } - /// One fixed category, at most once per stage per minute. No values from - /// the error, token, claims, or operator configuration are returned. - pub fn authentication_diagnostic(&self, stage: AuthenticationStage) -> Option<&'static str> { - self.diagnostics.admit(stage).then_some(stage.label()) - } - pub async fn verify_related_token(&self, token: &str) -> Result { self.verify_id_token(token).await } @@ -2666,11 +2655,6 @@ mod tests { "{reason}: {error:?}" ); assert!(!error.is_key_source_unavailable(), "{reason}"); - assert_eq!( - error.authentication_stage().label(), - "algorithm", - "{reason}" - ); } let header = json!({"alg": "RS256", "typ": "at+jwt", "kid": KEYCLOAK_SIG_KID}); @@ -3628,7 +3612,7 @@ mod tests { .verify(&missing_iat) .await .expect_err("invalid time bounds are refused"); - assert_eq!(error.authentication_stage().label(), "time"); + assert_eq!(error.failed_check(), FailedCheck::TokenTime); let mut missing_exp_claims = test_claims( Some("https://issuer.example"), @@ -3642,7 +3626,7 @@ mod tests { .verify(&missing_exp) .await .expect_err("invalid time bounds are refused"); - assert_eq!(error.authentication_stage().label(), "time"); + assert_eq!(error.failed_check(), FailedCheck::TokenTime); let mut non_positive_claims = test_claims( Some("https://issuer.example"), @@ -3656,7 +3640,7 @@ mod tests { .verify(&non_positive) .await .expect_err("invalid time bounds are refused"); - assert_eq!(error.authentication_stage().label(), "time"); + assert_eq!(error.failed_check(), FailedCheck::TokenTime); let mut overlong_claims = test_claims( Some("https://issuer.example"), @@ -3670,7 +3654,7 @@ mod tests { .verify(&overlong) .await .expect_err("invalid time bounds are refused"); - assert_eq!(error.authentication_stage().label(), "time"); + assert_eq!(error.failed_check(), FailedCheck::TokenTime); } fn test_claims(issuer: Option<&str>, audience: Option<&str>, subject: Option<&str>) -> Claims { diff --git a/crates/registry-platform-testing/src/token_fixtures.rs b/crates/registry-platform-testing/src/token_fixtures.rs index e1f90c6cb8..6619ecd04d 100644 --- a/crates/registry-platform-testing/src/token_fixtures.rs +++ b/crates/registry-platform-testing/src/token_fixtures.rs @@ -31,6 +31,7 @@ use registry_platform_crypto::{ generate_private_jwk, verify as verify_with_public_jwk, GeneratedKeyAlgorithm, LocalJwkSigner, PrivateJwk, PublicJwk, }; +use registry_platform_oidc::OidcError; use registry_platform_yaml::{EnvelopeRule, Expect, FormatSpec, Reader}; use serde::Deserialize; use serde_json::{json, Map, Value}; @@ -148,6 +149,47 @@ pub enum Outcome { Unknown, } +impl Outcome { + /// The characterisation result value for a verifier error, `refused/`. + /// It names the stage a corpus row records, so the expected table stays + /// comparable across products. Runtimes log and count the same refusal by + /// `FailedCheck`, not by this value. + /// + /// # Panics + /// + /// On an `OidcError` variant added without a stage here. + #[must_use] + pub fn refused_by(error: &OidcError) -> Self { + use OidcError as E; + let stage = match error { + E::MalformedToken | E::InvalidToken | E::SubjectMismatch => Stage::Header, + E::AlgorithmNotAllowed => Stage::Algorithm, + E::TokenTypeNotAllowed => Stage::TokenType, + E::MissingKid | E::KidTooLong | E::UnknownKid => Stage::Key, + E::SignatureInvalid => Stage::Signature, + E::IssuerMismatch { .. } => Stage::Issuer, + E::AudienceMismatch => Stage::Audience, + E::TokenExpired | E::TokenNotYetValid | E::InvalidTimeClaims => Stage::Time, + E::ClientNotAllowed | E::AssertionIssuerNotAllowed => Stage::Client, + E::Transport(_) + | E::BoundedRead(_) + | E::FetchUrl(_) + | E::HttpStatus(_) + | E::InvalidUrl + | E::Parse + | E::InvalidJwk + | E::EmptyKeySet + | E::StaticKeySet(_) + | E::MissingIssuer + | E::ConflictingEndpointConfiguration + | E::InsecureHttpRequiresOptIn + | E::EndpointRefused { .. } => Stage::Unavailable, + other => panic!("no characterisation stage is recorded for {other:?}"), + }; + Self::Refused(stage) + } +} + impl fmt::Display for Outcome { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { diff --git a/crates/registry-render/src/auth/token_characterisation.rs b/crates/registry-render/src/auth/token_characterisation.rs index 2aee222487..39638776c1 100644 --- a/crates/registry-render/src/auth/token_characterisation.rs +++ b/crates/registry-render/src/auth/token_characterisation.rs @@ -8,7 +8,6 @@ //! sits under `auth` so it can also ask the verifier for the check that //! refused a token, which `AuthenticationError` does not carry. use super::*; -use registry_platform_oidc::OidcError; use registry_platform_testing::{ ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, }; @@ -32,12 +31,6 @@ fn client_of(fixture: &TokenFixture) -> Option { literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) } -fn stage_of(error: &OidcError) -> Outcome { - format!("refused/{}", error.authentication_stage().label()) - .parse() - .expect("every authentication stage label is a result value") -} - /// A runtime file for one row. The recipe for a token that names no client /// writes `unrestricted`, as the runtime allows; every other row lists /// the fixture's client, or a placeholder when the token names none. @@ -75,7 +68,7 @@ async fn observe(verifier: &TokenVerifier, token: &str) -> Outcome { error.failed_check(), "the recorded check is the verifier's" ); - stage_of(&error) + Outcome::refused_by(&error) } (Err(AuthenticationError::Forbidden { .. }), Ok(_)) => { "refused/scope".parse().expect("result value") diff --git a/crates/registry-scheduling/tests/token_characterisation.rs b/crates/registry-scheduling/tests/token_characterisation.rs index 9e1818d371..394b3b6d18 100644 --- a/crates/registry-scheduling/tests/token_characterisation.rs +++ b/crates/registry-scheduling/tests/token_characterisation.rs @@ -170,7 +170,7 @@ async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { ), "{error:?} does not carry the verifier check" ); - refusal(failure.authentication_stage().label()) + Outcome::refused_by(&failure) } Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { if verified.scopes.iter().any(|held| held == &scope) { diff --git a/docs/site/src/content/docs/configure/request-an-access-token.mdx b/docs/site/src/content/docs/configure/request-an-access-token.mdx index 92d87c3df6..bd744f578d 100644 --- a/docs/site/src/content/docs/configure/request-an-access-token.mdx +++ b/docs/site/src/content/docs/configure/request-an-access-token.mdx @@ -109,7 +109,7 @@ Existing bounded multi-audience tokens remain accepted where the owning profile A token without the target audience grants no access to that resource. Casework task-client profiles keep their narrower audience rules. -{/* Evidence: crates/registry-platform-oidc/src/diagnostics.rs AuthenticationStage; +{/* Evidence: crates/registry-platform-oidc/src/diagnostics.rs failed_check; crates/registry-messaging/src/auth.rs access_token_profile, AUDIENCE. */} {/* TODO[evidence]: the multi-audience acceptance rule and the Casework task-client audience rule have no single code anchor. */} @@ -196,7 +196,7 @@ These logs contain no credential, claim, issuer, audience, scope, key, or subjec Use the selected configuration and safe local validation to identify the mismatched field, and never add token contents to runtime logs. Local fixture validation names the field or rule and the expected profile category without printing input values. -{/* Evidence: crates/registry-platform-oidc/src/diagnostics.rs AuthenticationStage, AuthenticationDiagnostics; +{/* Evidence: crates/registry-platform-oidc/src/diagnostics.rs failed_check; crates/registry-adapter-core/src/problem.rs AUTHENTICATION_REFUSED_PROBLEM. */} ## Troubleshooting diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index ad9ed8a22f..0952025849 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- BREAKING: `registry-platform-oidc` no longer has the stage-labelled + authentication log helpers: `AuthenticationStage`, + `AuthenticationDiagnostics`, `OidcError::authentication_stage`, + `TokenVerifier::authentication_diagnostic` and the + `log_authentication_refusal!` macro. Every runtime logs and counts + refusals by failed check. Migration: use `OidcError::failed_check`. + - `registry-platform-posture`, a `std`-only crate, holds `Posture`, `PostureSource`, `DeclaredPosture`, `PostureError` and `declared_from`/`declared`, which read the `--posture` flag and the diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 8b7655fef6..9c77207775 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -80,8 +80,8 @@ REALM=registry-journey POSTGRES_IMAGE=postgres:18.7@sha256:2ea8630df176ad090ec92136dee850397c5af8781e4bcf2e4162593691c61bbc PROJECTS_DIR=$JOURNEY_LIB_DIR/projects SECRETS=$JOURNEY_OUT/secrets -# The stages the shared verifier logs (AuthenticationStage in -# registry-platform-oidc), the same list as authenticationStages in the table. +# The stages a token characterisation result value may name (`Stage` in +# registry-platform-testing), the same list as authenticationStages in the table. STAGES=' header algorithm token-type key signature issuer audience time client scope profile unavailable ' # Every product a token reaches. The realm names a caller client for each, so # every one of their client secrets is generated even when fewer are selected. From 6dea940c819d068dc1628614e376193fc8564484 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 08:13:27 +0100 Subject: [PATCH 047/136] docs(platform): show the printed provision scripts and catalog the provision verbs - The Casework, Coordinator, Documents and Messaging operate pages show the --print-sql script each built tool prints, with a \password line after each role. - The CLI command catalog lists the provision verb of bregctl, caseworkctl, coordinatorctl, documentsctl, messagingctl and schedulingctl, and its --runtime-config help reads like every other runtime file option. - The identifier catalog records the current hashes of the shared provision command and the Scheduling problem codes. - The Documents PostgreSQL test builds its database the way provision does, with the runtime role's USAGE on public. - CI runs the provisioning journey for a change to a provision_postgres test, and no longer for a change to the database-free provision_cli tests alone. - The Scheduling problem-code test sits under its own doc comment. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 8 +- .github/scripts/test_ci_changes.py | 23 + crates/registry-cli-docs/catalog.json | 585 ++++++++++++++++++ .../tests/postgres_cli.rs | 26 +- crates/registry-platform-provision/src/cli.rs | 2 +- .../registry-scheduling-core/src/problem.rs | 6 +- .../src/content/docs/operate/casework.mdx | 16 +- .../src/content/docs/operate/coordinator.mdx | 19 +- .../src/content/docs/operate/documents.mdx | 2 +- .../src/content/docs/operate/messaging.mdx | 2 +- .../identifiers/generated/catalog.v1.json | 70 +-- 11 files changed, 696 insertions(+), 63 deletions(-) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 986f63ff62..d69f47fd9e 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -619,7 +619,13 @@ ) PROVISION_JOURNEY_INPUTS = ( *(f"crates/{package}/src/provision.rs" for package in PROVISION_JOURNEY_PACKAGES), - *(f"crates/{package}/tests/provision*.rs" for package in PROVISION_JOURNEY_PACKAGES), + # Each journey's test file. The database-free `provision_cli.rs` stays out. + *( + f"crates/{package}/tests/provision_postgres.rs" + for package in PROVISION_JOURNEY_PACKAGES + if package != "registry-caseworkctl" + ), + "crates/registry-caseworkctl/tests/provision.rs", "crates/registry-casework/migrations/**", "crates/registry-documents/migrations/**", "crates/registry-messaging/migrations/**", diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index d4dcde5527..5e4848741d 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -4480,6 +4480,29 @@ def test_product_provisioning_changes_select_the_tls_postgres_lane(self) -> None PROVISION_POSTGRES_LANE, outputs["breg_contracts_lanes"] ) + def test_database_free_provisioning_tests_do_not_select_the_tls_postgres_lane( + self, + ) -> None: + # `provision_cli.rs` reads no database, so the ordinary package tests + # cover it and the TLS PostgreSQL journey need not run. The Base + # Registry Engine tool is left out: any change to a breg package + # selects the breg contracts for its own reasons. + edgeless = Workspace(without_dependency_edges(self.metadata)) + checked = 0 + for package in PROVISION_JOURNEY_PACKAGES: + path = f"crates/{package}/tests/provision_cli.rs" + if package == "registry-bregctl" or not Path(path).exists(): + continue + checked += 1 + for graph, workspace in (("real", self.workspace), ("edgeless", edgeless)): + for event, outputs in ( + ("pull_request", classify(workspace, (path,), pull_request=True)), + ("merge_group", classify(workspace, (path,))), + ): + with self.subTest(graph=graph, path=path, event=event): + self.assertFalse(outputs["breg_contracts"]) + self.assertGreater(checked, 0) + def test_contracts_journeys_lane_runs_each_product_provisioning_journey( self, ) -> None: diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 993ce463ea..91cc2ab70b 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -5541,6 +5541,111 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "bregctl provision", + "about": "Create the PostgreSQL roles, database and schemas a Registry needs, from its runtime file", + "long_about": "Create the PostgreSQL roles, database and schemas a Registry needs, from its runtime file. The runtime file's two database URLs name both roles, the database and both passwords. The administrator URL comes from a file or an environment variable, never from the command line. The command grants the runtime role CONNECT on the database: apply grants the rest. With --package, a package that needs PostGIS also gets its schema, extension and bounding-box role, which CREATE EXTENSION postgis needs a superuser for, and both roles get USAGE on the PostGIS schema.", + "usage": "bregctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one `apply` reads. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--package ", + "description": "Absolute target package directory; a package that needs PostGIS adds the PostGIS steps. A symbolic link at any component of this path is refused.", + "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 (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "timer", "invocation": "bregctl timer", @@ -10198,6 +10303,102 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "caseworkctl provision", + "about": "Create the migration and runtime roles and the database named by the runtime file", + "long_about": null, + "usage": "caseworkctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one `apply` reads", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human diagnostics and reports, or one typed JSON report", + "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": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "api", "invocation": "caseworkctl api", @@ -12310,6 +12511,102 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "coordinatorctl provision", + "about": "Create the database, the migration and runtime roles, and the grants `apply` expects, as a PostgreSQL administrator", + "long_about": null, + "usage": "coordinatorctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one `apply` reads", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Output format for local reports and authenticated API responses: readable text, or one JSON report", + "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": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "apply", "invocation": "coordinatorctl apply", @@ -13972,6 +14269,102 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "documentsctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", + "long_about": null, + "usage": "documentsctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one `apply` reads", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "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": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "apply", "invocation": "documentsctl apply", @@ -20880,6 +21273,102 @@ ], "subcommands": [] }, + { + "name": "provision", + "invocation": "messagingctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", + "long_about": null, + "usage": "messagingctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one `apply` reads", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "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": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "plan", "invocation": "messagingctl plan", @@ -25815,6 +26304,102 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "schedulingctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", + "long_about": null, + "usage": "schedulingctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one `apply` reads", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "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": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "apply", "invocation": "schedulingctl apply", diff --git a/crates/registry-documentsctl/tests/postgres_cli.rs b/crates/registry-documentsctl/tests/postgres_cli.rs index f50a7829c8..19366a7bd4 100644 --- a/crates/registry-documentsctl/tests/postgres_cli.rs +++ b/crates/registry-documentsctl/tests/postgres_cli.rs @@ -386,11 +386,12 @@ async fn apply_refuses_a_package_that_is_not_the_pinned_one() { } /// A database provisioned as the Document Store operate page provisions -/// one: split migration and runtime login roles, `PUBLIC` stripped of every -/// privilege on the database and on the `public` schema, and the schema -/// handed to the migration role. The runtime role holds only `CONNECT`, so -/// before the first apply it has no usage on any schema and its -/// `current_schema()` is null. Roles are cluster-wide, so each is named +/// one, as `documentsctl provision` leaves it: split migration and runtime +/// login roles, `PUBLIC` stripped of every privilege on the database and of +/// `CREATE` on the `public` schema, the migration role holding `USAGE` and +/// `CREATE` on `public`, and the runtime role holding `CONNECT` on the +/// database and `USAGE` on `public`. Before the first apply the runtime +/// role has no table privilege. Roles are cluster-wide, so each is named /// after the suite's own database, which makes a leftover from a failed run /// attributable, and [`ProvisionedDatabase::drop`] removes them with the /// database. @@ -445,8 +446,9 @@ impl ProvisionedDatabase { .batch_execute(&format!( "REVOKE ALL ON DATABASE {name} FROM PUBLIC; GRANT CONNECT ON DATABASE {name} TO {migration_role}, {runtime_role}; - ALTER SCHEMA public OWNER TO {migration_role}; - REVOKE ALL ON SCHEMA public FROM PUBLIC;" + REVOKE CREATE ON SCHEMA public FROM PUBLIC; + GRANT USAGE, CREATE ON SCHEMA public TO {migration_role}; + GRANT USAGE ON SCHEMA public TO {runtime_role};" )) .await .unwrap(); @@ -506,8 +508,8 @@ fn base_config() -> tokio_postgres::Config { } /// The operate page's journey on a database provisioned as it says: `plan` -/// over the runtime credential, which holds nothing but `CONNECT` before -/// the first apply, reports the initial activation; `apply` over the +/// over the runtime credential, which holds no table privilege before the +/// first apply, reports the initial activation; `apply` over the /// migration credential splits the roles; and `plan` then reports nothing /// to change. #[tokio::test] @@ -566,7 +568,9 @@ async fn plan_reports_the_initial_activation_on_a_database_provisioned_as_the_op // After apply, a runtime role that lost its schema usage resolves no // schema again. That is a misconfiguration, refused by name rather - // than read as a database nobody applied a package to. + // than read as a database nobody applied a package to. `provision` + // leaves `PUBLIC` its default `USAGE` on `public`, so the revoke names + // `PUBLIC` as well, as an operator who hardened the schema would. let (database, connection) = tokio_postgres::connect(&provisioned.admin_url(), tokio_postgres::NoTls) .await @@ -574,7 +578,7 @@ async fn plan_reports_the_initial_activation_on_a_database_provisioned_as_the_op let connection = tokio::spawn(connection); database .batch_execute(&format!( - "REVOKE USAGE ON SCHEMA public FROM {}", + "REVOKE USAGE ON SCHEMA public FROM PUBLIC, {}", provisioned.runtime_role )) .await diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs index f3f441a985..87ac60b5d8 100644 --- a/crates/registry-platform-provision/src/cli.rs +++ b/crates/registry-platform-provision/src/cli.rs @@ -42,7 +42,7 @@ pub enum OutputFormat { /// `--format` flag, passed to [`run_provision`]. #[derive(clap::Args, Debug, Clone)] pub struct ProvisionArgs { - /// The product's runtime file, the one `apply` reads + /// Runtime configuration file, the one `apply` reads #[arg(long, value_name = "FILE")] pub runtime_config: PathBuf, /// File holding the administrator PostgreSQL URL diff --git a/crates/registry-scheduling-core/src/problem.rs b/crates/registry-scheduling-core/src/problem.rs index 112857b9f9..3f8466ff99 100644 --- a/crates/registry-scheduling-core/src/problem.rs +++ b/crates/registry-scheduling-core/src/problem.rs @@ -441,9 +441,6 @@ mod tests { } } - /// The request-edge family is Casework's, pinned one status per code, so - /// the runtime's edge and every client agree on what a rejected request - /// looks like. #[test] fn a_grant_with_too_much_lifetime_left_has_its_own_code_and_keeps_the_status() { let code = ProblemCode::GrantLifetimeTooLong; @@ -457,6 +454,9 @@ mod tests { assert!(code.detail().contains("900 seconds")); } + /// The request-edge family is Casework's, pinned one status per code, so + /// the runtime's edge and every client agree on what a rejected request + /// looks like. #[test] fn the_request_edge_family_pins_casework_s_statuses() { assert_eq!(ProblemCode::RequestInvalid.http_status(), 400); diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index 94c45e54cd..9e1a3fe182 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -221,7 +221,21 @@ records single-role mode. If a database administrator must run the SQL, add `--print-sql` and leave out the administrator flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a -`\password` line that prompts for the password in `psql`, so the script holds no password. +`\password` line that prompts for the password in `psql`, so the script holds no password: + +```sql +SET createrole_self_grant = 'set,inherit'; +CREATE ROLE "casework_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "casework_migration" +CREATE ROLE "casework_runtime" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "casework_runtime" +CREATE DATABASE "casework" WITH ALLOW_CONNECTIONS false; +REVOKE ALL ON DATABASE "casework" FROM PUBLIC; +GRANT CONNECT ON DATABASE "casework" TO "casework_migration", "casework_runtime"; +ALTER DATABASE "casework" ALLOW_CONNECTIONS true; +\connect "casework" +REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "casework_migration"; GRANT USAGE ON SCHEMA public TO "casework_runtime"; +``` {/* Evidence: crates/registry-caseworkctl/src/provision.rs; crates/registry-platform-provision/src/plan.rs, SchemaLayout::PublicForMigration; crates/registry-caseworkctl/tests/provision.rs. */} diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index 0793be305a..f71dfb8825 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -282,15 +282,16 @@ To review the statements first, or to run them yourself with `psql`, add `--prin It connects to nothing and prints a script with a `\password` line after each role instead of a password: ```sql -CREATE ROLE coordinator_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS; -CREATE ROLE coordinator_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS; -CREATE DATABASE coordinator WITH ALLOW_CONNECTIONS false; -REVOKE ALL ON DATABASE coordinator FROM PUBLIC; -GRANT CONNECT ON DATABASE coordinator TO coordinator_migration, coordinator_runtime; -GRANT CREATE ON DATABASE coordinator TO coordinator_migration; -ALTER DATABASE coordinator WITH ALLOW_CONNECTIONS true; +SET createrole_self_grant = 'set,inherit'; +CREATE ROLE "coordinator_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "coordinator_migration" +CREATE ROLE "coordinator_runtime" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "coordinator_runtime" +CREATE DATABASE "coordinator" WITH ALLOW_CONNECTIONS false; +REVOKE ALL ON DATABASE "coordinator" FROM PUBLIC; +GRANT CONNECT ON DATABASE "coordinator" TO "coordinator_migration", "coordinator_runtime"; +GRANT CREATE ON DATABASE "coordinator" TO "coordinator_migration"; +ALTER DATABASE "coordinator" ALLOW_CONNECTIONS true; ``` These are the only grants `provision` makes. diff --git a/docs/site/src/content/docs/operate/documents.mdx b/docs/site/src/content/docs/operate/documents.mdx index 9ffc312ca7..2870b6c454 100644 --- a/docs/site/src/content/docs/operate/documents.mdx +++ b/docs/site/src/content/docs/operate/documents.mdx @@ -85,7 +85,7 @@ REVOKE ALL ON DATABASE "documents" FROM PUBLIC; GRANT CONNECT ON DATABASE "documents" TO "documents_migration", "documents_runtime"; ALTER DATABASE "documents" ALLOW_CONNECTIONS true; \connect "documents" -REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "documents_migration"; +REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "documents_migration"; GRANT USAGE ON SCHEMA public TO "documents_runtime"; ``` The names come from your URLs. Add `--format json` for a report of each statement and its outcome. diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index 88c1de8d21..c45530c3f7 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -272,7 +272,7 @@ REVOKE ALL ON DATABASE "messaging" FROM PUBLIC; GRANT CONNECT ON DATABASE "messaging" TO "messaging_migration", "messaging_runtime"; ALTER DATABASE "messaging" ALLOW_CONNECTIONS true; \connect "messaging" -REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "messaging_migration"; +REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO "messaging_migration"; GRANT USAGE ON SCHEMA public TO "messaging_runtime"; ``` The names come from your URLs. Add `--format json` for a report of each statement and its outcome. diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 25f7cbec8f..6410934589 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -3994,7 +3994,7 @@ "description": "The bearer credential is missing, invalid, or expired. Sign in again.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "authentication.refused", @@ -4013,7 +4013,7 @@ "description": "An active booking already holds this party's duplicate key. Cancel it, or wait until it has passed, before booking again.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "booking.duplicate-active", @@ -4032,7 +4032,7 @@ "description": "The cancellation cutoff for this appointment has passed, so it can no longer be cancelled.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "cancellation.cutoff-passed", @@ -4051,7 +4051,7 @@ "description": "The party or backing supply does not carry every capability this offering requires.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "capability.unmatched", @@ -4070,7 +4070,7 @@ "description": "The supply is fully committed for the requested interval. Choose another time.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "capacity.exhausted", @@ -4089,7 +4089,7 @@ "description": "This cursor has expired. Start again without a cursor and deduplicate entries by id.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "cursor.expired", @@ -4108,7 +4108,7 @@ "description": "The cursor is invalid for this request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "cursor.invalid", @@ -4127,7 +4127,7 @@ "description": "A required eligibility check could not run. Retry; do not treat this as permission.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "eligibility.unavailable", @@ -4146,7 +4146,7 @@ "description": "The task grant has more than 900 seconds left before it expires. Present a task grant that expires within 900 seconds.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "grant.lifetime-too-long", @@ -4165,7 +4165,7 @@ "description": "The hold expired before confirmation. Its capacity is bookable again; start a new request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "hold.expired", @@ -4184,7 +4184,7 @@ "description": "The claim is not an active hold. It may already be confirmed or released.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "hold.released", @@ -4203,7 +4203,7 @@ "description": "A required lifecycle hook could not run, so the request was refused rather than half-applied.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "hook.unavailable", @@ -4222,7 +4222,7 @@ "description": "The requested start is earlier than the lead time allows or further ahead than the horizon allows.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "horizon.outside", @@ -4241,7 +4241,7 @@ "description": "The stored response for this idempotency key has expired. For an appointment command, read the appointment by its external reference or its identifier to learn the original outcome before choosing a new key. A hold cannot be read and expires on its own, so start a new request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "idempotency.expired", @@ -4260,7 +4260,7 @@ "description": "This idempotency key was used for a different request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "idempotency.key-reused", @@ -4279,7 +4279,7 @@ "description": "A closure covers the requested start. Choose a start outside the closure.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "location.closed", @@ -4298,7 +4298,7 @@ "description": "Your current Scheduling authority does not allow this operation.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "operation.not-authorized", @@ -4317,7 +4317,7 @@ "description": "The party is larger than this offering can ever serve, or its size falls outside the published units.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "party.capacity-inadequate", @@ -4336,7 +4336,7 @@ "description": "The policy revision changed before the request committed. Reload the catalogue and try again with the current revision.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "policy.changed", @@ -4355,7 +4355,7 @@ "description": "The appointment changed since you loaded it. Reload and try again.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "precondition.failed", @@ -4374,7 +4374,7 @@ "description": "This mutation requires the revision you loaded, or the duplicate key this offering keys on.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "precondition.required", @@ -4393,7 +4393,7 @@ "description": "The party is missing a prerequisite this offering requires.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "prerequisite.missing", @@ -4412,7 +4412,7 @@ "description": "The selected Scheduling profile does not authorize this request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "profile.not-authorized", @@ -4431,7 +4431,7 @@ "description": "No retained success receipt matches this caller, key, and original request. The original outcome remains unknown; this is not evidence that no effect occurred.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "receipt.unresolved", @@ -4450,7 +4450,7 @@ "description": "The request body exceeds the accepted size.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "request.body-too-large", @@ -4469,7 +4469,7 @@ "description": "The request could not be read as a Scheduling request.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "request.invalid", @@ -4488,7 +4488,7 @@ "description": "The route exists but not for this method.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "request.method-not-allowed", @@ -4507,7 +4507,7 @@ "description": "The requested route does not exist.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "request.not-found", @@ -4526,7 +4526,7 @@ "description": "The request body could not be processed.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "request.unprocessable", @@ -4545,7 +4545,7 @@ "description": "The request body is not JSON.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "request.unsupported-media-type", @@ -4564,7 +4564,7 @@ "description": "Every capable member is unavailable for this interval.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "resource.unavailable", @@ -4583,7 +4583,7 @@ "description": "The observed revision is no longer current.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "revision.mismatch", @@ -4602,7 +4602,7 @@ "description": "No published schedule serves that start. Choose a start on the published grid.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "schedule.unpublished", @@ -4621,7 +4621,7 @@ "description": "Scheduling storage is unavailable. Try again after the service recovers.", "source": { "path": "crates/registry-scheduling-core/src/problem.rs", - "sha256": "02abb82421813ae66712f7330ce783dc654ff2213d5c4f3a0c2341350c677053" + "sha256": "f42aee1f415846f57dabc1c39eb5e004aacdee8c728e39c19be8ce40673d1eed" }, "problem": { "code": "service.unavailable", @@ -6098,7 +6098,7 @@ "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions.", "source": { "path": "crates/registry-platform-provision/src/cli.rs", - "sha256": "097c8da77b747a79f756b5ab511c296a0b1868e1650ebb8826dfb3b981e02164" + "sha256": "bce58d08771dc21d7d4ceeda472f4709105066979298ab3bfd188d484c53c503" }, "artifact": { "path": "crates/registry-platform-provision/schema/provision-report.schema.json", From 8f3565d4b8f34b0e7ef98dda16a92fac9cecc9bb Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 08:44:08 +0100 Subject: [PATCH 048/136] feat(platform): load runtime files under a declared posture The shared runtime loader now takes the deployment's declared posture and gates development-only settings on it. The shared database block gains `database.transport` (`verified-tls`, `loopback-plaintext`, or the development-only `private-network-plaintext`) and the audit block gains `audit.hashKeyCustody`. The generated runtime schemas mark development-only members with `x-registry-development-only`. Runtimes that have not adopted the posture call the `*_without_posture` entry points, which keep their present admission exactly. No runtime reads the new members yet. BREAKING (Rust API): `RuntimeConfigLoader::new` takes a `DeclaredPosture`. Callers that keep the present behaviour call `RuntimeConfigLoader::new_without_posture`. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-core/src/checks.rs | 2 +- .../src/job_sources.rs | 14 +- crates/registry-adapter-engine/src/load.rs | 2 +- crates/registry-adapter/src/payments/http.rs | 4 +- crates/registry-adapterctl/src/check.rs | 2 +- crates/registry-adapterctl/src/payments.rs | 2 +- crates/registry-breg-mcp/src/config.rs | 2 +- crates/registry-breg-review/src/config.rs | 2 +- crates/registry-breg/src/runtime_config.rs | 4 +- crates/registry-casework/src/config.rs | 4 +- .../src/task_grants/http_tests.rs | 1 + .../src/task_grants/lock_order_tests.rs | 1 + .../src/task_grants/native_exchange_tests.rs | 1 + .../tests/breg_review_journey.rs | 1 + .../registry-casework/tests/refusal_golden.rs | 1 + .../tests/review_acceptance_postgres.rs | 1 + .../tests/review_directory_postgres.rs | 1 + crates/registry-casework/tests/review_http.rs | 1 + .../tests/review_migration_postgres.rs | 2 + .../tests/review_payment_fixture_postgres.rs | 1 + .../tests/review_postgres.rs | 1 + .../tests/secret_diagnostics.rs | 1 + crates/registry-cli-docs/catalog.json | 96 ++++ crates/registry-coordinator/src/access.rs | 3 +- crates/registry-coordinator/src/runtime.rs | 2 +- .../tests/cli_authoring.rs | 4 +- .../registry-coordinator/tests/support/mod.rs | 1 + .../registry-discovery/src/runtime_config.rs | 2 +- crates/registry-documents/src/config.rs | 7 +- .../registry-evidence-oid4vci/src/config.rs | 2 +- crates/registry-evidence-oid4vp/src/config.rs | 4 +- crates/registry-evidence/src/config.rs | 4 +- crates/registry-mcp/src/adapter.rs | 2 +- crates/registry-mcp/src/config.rs | 2 +- crates/registry-messaging/src/config.rs | 4 +- .../tests/postgres_migrate.rs | 1 + crates/registry-platform-config/src/blocks.rs | 325 ++++++++++- .../src/blocks_tests.rs | 22 +- crates/registry-platform-config/src/lib.rs | 9 +- crates/registry-platform-config/src/loader.rs | 135 ++++- .../src/loader_tests.rs | 6 +- .../registry-platform-config/src/offline.rs | 32 +- .../registry-platform-config/src/posture.rs | 11 +- .../src/posture_load_tests.rs | 528 ++++++++++++++++++ .../src/posture_tests.rs | 2 +- crates/registry-render/src/runtime.rs | 4 +- crates/registry-scheduling/src/config.rs | 4 +- .../tests/postgres_commitments.rs | 2 + .../schemas/runtime.v1alpha1.schema.json | 34 +- .../mcp-runtime/mcp-runtime.schema.json | 22 + .../review-runtime/review-runtime.schema.json | 22 + .../generated/runtime/runtime.schema.json | 56 +- .../generated/runtime/runtime.schema.json | 56 +- .../generated/runtime/runtime.schema.json | 34 +- .../generated/runtime/runtime.schema.json | 56 +- .../oid4vci-runtime.schema.json | 22 + .../oid4vp-runtime/oid4vp-runtime.schema.json | 36 +- .../identifiers/generated/catalog.v1.json | 28 +- .../generated/runtime/runtime.schema.json | 56 +- products/platform/CHANGELOG.md | 27 + .../mcp-runtime/mcp-runtime.schema.json | 22 + .../runtime-config-blocks.schema.json | 56 +- .../scripts/check-config-conformance.py | 2 +- products/render/schemas/runtime.schema.json | 7 +- .../generated/runtime/runtime.schema.json | 56 +- 65 files changed, 1732 insertions(+), 125 deletions(-) create mode 100644 crates/registry-platform-config/src/posture_load_tests.rs diff --git a/crates/registry-adapter-core/src/checks.rs b/crates/registry-adapter-core/src/checks.rs index 5403e0b942..bb2bd8438d 100644 --- a/crates/registry-adapter-core/src/checks.rs +++ b/crates/registry-adapter-core/src/checks.rs @@ -6922,7 +6922,7 @@ pub fn check_endpoint_bindings( #[must_use] pub fn check_runtime(workspace: &Workspace<'_>, runtime: &AdapterRuntimeConfig) -> Vec { let mut findings = check_endpoint_bindings(workspace, &runtime.endpoint_bindings()); - if let Err(error) = runtime.oidc.check("oidc", true) { + if let Err(error) = runtime.oidc.check_without_posture("oidc", true) { findings.push(finding( CheckCode::RuntimeInvalidOrigin, "/oidc", diff --git a/crates/registry-adapter-engine/src/job_sources.rs b/crates/registry-adapter-engine/src/job_sources.rs index cf94166b65..d4c5f9953e 100644 --- a/crates/registry-adapter-engine/src/job_sources.rs +++ b/crates/registry-adapter-engine/src/job_sources.rs @@ -272,7 +272,7 @@ impl JobRuntimeConfig { // platforms). A path that cannot be canonicalized is left to // the loader's own unreadable refusal. let absolute = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: registry_adapter_core::ADAPTER_JOB_RUNTIME_API_VERSION, kind: registry_adapter_core::ADAPTER_JOB_RUNTIME_KIND, }) @@ -2098,7 +2098,7 @@ endpoints: [] /// The job runtime config reads through the shared loader. #[test] fn the_loader_reads_the_job_runtime_config() { - let loader = registry_platform_config::RuntimeConfigLoader::new( + let loader = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, @@ -2112,7 +2112,7 @@ endpoints: [] /// reader's own code, pointer, and source position. #[test] fn an_undeclared_member_refuses_with_its_pointer_at_every_depth() { - let loader = registry_platform_config::RuntimeConfigLoader::new( + let loader = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, @@ -2147,7 +2147,7 @@ endpoints: [] /// shape. #[test] fn the_job_and_facade_envelopes_refuse_each_other() { - let job = registry_platform_config::RuntimeConfigLoader::new( + let job = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, @@ -2161,7 +2161,7 @@ endpoints: [] .is_err(), "the job loader refuses the facade envelope" ); - let facade = registry_platform_config::RuntimeConfigLoader::new( + let facade = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_RUNTIME_API_VERSION, kind: ADAPTER_RUNTIME_KIND, @@ -2207,7 +2207,7 @@ endpoints: [] /// and how to fix it, not only that the value is invalid. #[test] fn each_hook_ingress_refusal_names_its_rule_and_the_fix() { - let loader = registry_platform_config::RuntimeConfigLoader::new( + let loader = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, @@ -2261,7 +2261,7 @@ endpoints: [] } fn loader() -> registry_platform_config::RuntimeConfigLoader { - registry_platform_config::RuntimeConfigLoader::new( + registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index 29fe064c91..acb31614f2 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -681,7 +681,7 @@ fn load_inner( let absolute = std::fs::canonicalize(runtime_path).map_err(|_| LoadError::Unreadable { path: runtime_path.display().to_string(), })?; - let runtime = RuntimeConfigLoader::new(RuntimeEnvelope { + let runtime = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: ADAPTER_RUNTIME_API_VERSION, kind: ADAPTER_RUNTIME_KIND, }) diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index 88e2baff34..9f9b52cd85 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -110,7 +110,7 @@ pub fn contract(config: &PaymentsConfig) -> serde_json::Value { 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 { + let config = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: API_VERSION, kind: KIND, }) @@ -464,7 +464,7 @@ pub async fn run_only( ) -> Result<(), ServeError> { let absolute = std::fs::canonicalize(runtime_path) .map_err(|_| refused("runtime configuration could not be read"))?; - let runtime = RuntimeConfigLoader::new(RuntimeEnvelope { + let runtime = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: registry_adapter_core::ADAPTER_RUNTIME_API_VERSION, kind: registry_adapter_core::ADAPTER_RUNTIME_KIND, }) diff --git a/crates/registry-adapterctl/src/check.rs b/crates/registry-adapterctl/src/check.rs index 525b06e4d5..73ae644487 100644 --- a/crates/registry-adapterctl/src/check.rs +++ b/crates/registry-adapterctl/src/check.rs @@ -850,7 +850,7 @@ pub(crate) fn read_runtime( path: shown.clone(), source, })?; - let loader = RuntimeConfigLoader::new(RuntimeEnvelope { + let loader = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: ADAPTER_RUNTIME_API_VERSION, kind: ADAPTER_RUNTIME_KIND, }) diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs index f887d2d466..95faf7f666 100644 --- a/crates/registry-adapterctl/src/payments.rs +++ b/crates/registry-adapterctl/src/payments.rs @@ -254,7 +254,7 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { }; } }; - let check = RuntimeConfigLoader::new(RuntimeEnvelope { + let check = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: API_VERSION, kind: KIND, }) diff --git a/crates/registry-breg-mcp/src/config.rs b/crates/registry-breg-mcp/src/config.rs index 70c21287fc..9e01fdbc42 100644 --- a/crates/registry-breg-mcp/src/config.rs +++ b/crates/registry-breg-mcp/src/config.rs @@ -303,7 +303,7 @@ impl RuntimeConfig { /// its retired apiVersion. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(RUNTIME_ENVELOPE) .removed_keys(REMOVED_KEYS) .retired_api_versions(RETIRED_RUNTIME_API_VERSIONS) } diff --git a/crates/registry-breg-review/src/config.rs b/crates/registry-breg-review/src/config.rs index 88d22d746a..64574af592 100644 --- a/crates/registry-breg-review/src/config.rs +++ b/crates/registry-breg-review/src/config.rs @@ -504,7 +504,7 @@ impl RuntimeConfig { /// and its retired apiVersion. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(RUNTIME_ENVELOPE) .removed_keys(REMOVED_KEYS) .retired_api_versions(RETIRED_RUNTIME_API_VERSIONS) } diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index bf3db8a915..5efadd285a 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -1015,7 +1015,7 @@ fn runtime_stand_in(pointer: &str) -> &'static str { /// position reach the operator. The file is held to the shared 1 MiB bound /// (CFG-YAML-6). const fn runtime_config_loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: RUNTIME_CONFIG_API_VERSION, kind: RUNTIME_CONFIG_KIND, }) @@ -2205,7 +2205,7 @@ impl OidcVerifierConfig { // development and test deployments that run their issuer beside the // registry; every other issuer and key URI is `https`. raw.provider - .check("authentication.oidc", true) + .check_without_posture("authentication.oidc", true) .map_err(|_| RuntimeConfigError::InvalidOidc)?; validate_oidc_value(&raw.access_token_type)?; validate_claim_name(&raw.scope_claim)?; diff --git a/crates/registry-casework/src/config.rs b/crates/registry-casework/src/config.rs index 16bbb92740..b5ac68f348 100644 --- a/crates/registry-casework/src/config.rs +++ b/crates/registry-casework/src/config.rs @@ -886,7 +886,7 @@ impl RuntimeConfig { /// removed keys, and retired apiVersions. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(CASEWORK_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(CASEWORK_RUNTIME_ENVELOPE) .removed_keys(CASEWORK_REMOVED_KEYS) .retired_api_versions(CASEWORK_RETIRED_RUNTIME_API_VERSIONS) .require_trusted_ownership() @@ -1253,7 +1253,7 @@ impl RuntimeConfig { fn check_oidc(&self, findings: &mut Vec) { let oidc = &self.authentication.oidc; - if let Err(error) = oidc.provider.check( + if let Err(error) = oidc.provider.check_without_posture( "authentication.oidc", self.listener.tls_termination == TlsTermination::DevelopmentLoopback, ) { diff --git a/crates/registry-casework/src/task_grants/http_tests.rs b/crates/registry-casework/src/task_grants/http_tests.rs index acc799d00d..070574187b 100644 --- a/crates/registry-casework/src/task_grants/http_tests.rs +++ b/crates/registry-casework/src/task_grants/http_tests.rs @@ -177,6 +177,7 @@ async fn fixture_for_role_with_templates( migration_url_ref: format!("secret:env/{name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let (audit, audit_capture) = crate::CaseworkAudit::capture(); let store = PostgresStore::connect_migration(&config, &secrets) diff --git a/crates/registry-casework/src/task_grants/lock_order_tests.rs b/crates/registry-casework/src/task_grants/lock_order_tests.rs index 84ab0abb8a..77497b8423 100644 --- a/crates/registry-casework/src/task_grants/lock_order_tests.rs +++ b/crates/registry-casework/src/task_grants/lock_order_tests.rs @@ -49,6 +49,7 @@ async fn store_for_schema(schema: &str, application_name: &str) -> PostgresStore migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let store = PostgresStore::connect_runtime(&config, &secrets) .expect("connect lock-order store") diff --git a/crates/registry-casework/src/task_grants/native_exchange_tests.rs b/crates/registry-casework/src/task_grants/native_exchange_tests.rs index 45208e4af6..9e8b1f95b8 100644 --- a/crates/registry-casework/src/task_grants/native_exchange_tests.rs +++ b/crates/registry-casework/src/task_grants/native_exchange_tests.rs @@ -1114,6 +1114,7 @@ async fn fixture( migration_url_ref: format!("secret:env/{name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let store = PostgresStore::connect_migration(&db_config, &secrets) .unwrap() diff --git a/crates/registry-casework/tests/breg_review_journey.rs b/crates/registry-casework/tests/breg_review_journey.rs index caba45b744..fe989a321a 100644 --- a/crates/registry-casework/tests/breg_review_journey.rs +++ b/crates/registry-casework/tests/breg_review_journey.rs @@ -416,6 +416,7 @@ async fn casework_store() -> (PostgresStore, tokio_postgres::Client, String) { migration_url_ref: format!("secret:env/{name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let store = PostgresStore::connect_migration(&config, &secrets) .unwrap() diff --git a/crates/registry-casework/tests/refusal_golden.rs b/crates/registry-casework/tests/refusal_golden.rs index 3194762413..8745163037 100644 --- a/crates/registry-casework/tests/refusal_golden.rs +++ b/crates/registry-casework/tests/refusal_golden.rs @@ -409,6 +409,7 @@ fn unconnected_store(root: &std::path::Path) -> PostgresStore { migration_url_ref: "secret:file/database-url".to_owned(), ca_bundle_ref: None, test_only_plaintext: false, + transport: None, }, &secrets, ) diff --git a/crates/registry-casework/tests/review_acceptance_postgres.rs b/crates/registry-casework/tests/review_acceptance_postgres.rs index 3e9e03b638..9f94729074 100644 --- a/crates/registry-casework/tests/review_acceptance_postgres.rs +++ b/crates/registry-casework/tests/review_acceptance_postgres.rs @@ -217,6 +217,7 @@ impl Fixture { migration_url_ref: format!("secret:env/{variable}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let (audit, capture) = CaseworkAudit::capture(); let migration = PostgresStore::connect_migration(&config, &secrets) diff --git a/crates/registry-casework/tests/review_directory_postgres.rs b/crates/registry-casework/tests/review_directory_postgres.rs index 84dcdb184a..dd08cfd04c 100644 --- a/crates/registry-casework/tests/review_directory_postgres.rs +++ b/crates/registry-casework/tests/review_directory_postgres.rs @@ -107,6 +107,7 @@ async fn fixture() -> Fixture { migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let migration = PostgresStore::connect_migration(&config, &secrets) .expect("migration store") diff --git a/crates/registry-casework/tests/review_http.rs b/crates/registry-casework/tests/review_http.rs index a1ac31e308..750a21d73f 100644 --- a/crates/registry-casework/tests/review_http.rs +++ b/crates/registry-casework/tests/review_http.rs @@ -490,6 +490,7 @@ async fn app_with_project_options( migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; PostgresStore::connect_migration(&database_config, &secrets) .expect("migration store") diff --git a/crates/registry-casework/tests/review_migration_postgres.rs b/crates/registry-casework/tests/review_migration_postgres.rs index 7f2af8e781..0ad431ba37 100644 --- a/crates/registry-casework/tests/review_migration_postgres.rs +++ b/crates/registry-casework/tests/review_migration_postgres.rs @@ -94,6 +94,7 @@ impl Fixture { migration_url_ref: reference, ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; Self::open(database, &url, url.clone(), schema).await } @@ -119,6 +120,7 @@ impl Fixture { migration_url_ref: secret_ref(&url), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; Self::open(database, &url, runtime_url, schema).await } diff --git a/crates/registry-casework/tests/review_payment_fixture_postgres.rs b/crates/registry-casework/tests/review_payment_fixture_postgres.rs index c047d0c618..c1668890a0 100644 --- a/crates/registry-casework/tests/review_payment_fixture_postgres.rs +++ b/crates/registry-casework/tests/review_payment_fixture_postgres.rs @@ -440,6 +440,7 @@ async fn fixture_for_issuer( migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; PostgresStore::connect_migration(&database_config, &secrets) .expect("payment migration store") diff --git a/crates/registry-casework/tests/review_postgres.rs b/crates/registry-casework/tests/review_postgres.rs index eb0c242bbc..31ef02fe46 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -531,6 +531,7 @@ async fn fixture() -> Fixture { migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let migration = PostgresStore::connect_migration(&database_config, &secrets) .expect("migration store") diff --git a/crates/registry-casework/tests/secret_diagnostics.rs b/crates/registry-casework/tests/secret_diagnostics.rs index bab55d5290..ac7dd30407 100644 --- a/crates/registry-casework/tests/secret_diagnostics.rs +++ b/crates/registry-casework/tests/secret_diagnostics.rs @@ -18,6 +18,7 @@ fn database(reference: &str) -> DatabaseConfig { migration_url_ref: reference.to_owned(), ca_bundle_ref: None, test_only_plaintext: false, + transport: None, } } diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 91cc2ab70b..cb56984049 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -1744,6 +1744,102 @@ } ] }, + { + "name": "provision", + "invocation": "adapterctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", + "long_about": null, + "usage": "adapterctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one `apply` reads", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "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": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "schemas", "invocation": "adapterctl schemas", diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index c441bb1011..c4fb06d8e9 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -187,7 +187,8 @@ impl AccessConfig { ) -> Vec { let mut errors = Vec::new(); for result in [ - self.issuer.check("deployment.authentication", local), + self.issuer + .check_without_posture("deployment.authentication", local), self.clients().check("deployment.authentication"), ] { if let Err(error) = result { diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index 60c392205b..727cc6851a 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -544,7 +544,7 @@ fn minimum_observation_interval() -> registry_platform_yaml::BoundedU32<30, 86_4 /// The shared reader checks the envelope before directly decoding RuntimeConfig. impl RuntimeConfig { pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: API_VERSION, kind: KIND, }) diff --git a/crates/registry-coordinator/tests/cli_authoring.rs b/crates/registry-coordinator/tests/cli_authoring.rs index d5467fa175..7f1834761b 100644 --- a/crates/registry-coordinator/tests/cli_authoring.rs +++ b/crates/registry-coordinator/tests/cli_authoring.rs @@ -251,7 +251,7 @@ fn init_names_the_project_after_its_directory_and_writes_runtime_in_reading_orde ] ); assert!(runtime.contains("# Offline check reads references")); - let parsed = registry_platform_config::RuntimeConfigLoader::new( + let parsed = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: registry_coordinator::runtime::API_VERSION, kind: registry_coordinator::runtime::KIND, @@ -683,7 +683,7 @@ fn check_locates_a_missing_binding_without_printing_configured_values() { let directory = path.to_str().unwrap(); assert!(cli(&["init", "--directory", directory]).status.success()); let runtime = path.join("runtime.yaml"); - let mut document: Value = registry_platform_config::RuntimeConfigLoader::new( + let mut document: Value = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: registry_coordinator::runtime::API_VERSION, kind: registry_coordinator::runtime::KIND, diff --git a/crates/registry-coordinator/tests/support/mod.rs b/crates/registry-coordinator/tests/support/mod.rs index 98a13e569f..d25b26659a 100644 --- a/crates/registry-coordinator/tests/support/mod.rs +++ b/crates/registry-coordinator/tests/support/mod.rs @@ -88,6 +88,7 @@ pub fn config( migration_url_ref: "secret:env/COORDINATOR_TEST_DATABASE_URL".into(), ca_bundle_ref: None, test_only_plaintext: false, + transport: None, }, namespace: format!("coordinator_{}", uuid::Uuid::new_v4().simple()), connections: BTreeMap::from([ diff --git a/crates/registry-discovery/src/runtime_config.rs b/crates/registry-discovery/src/runtime_config.rs index c2311d03ed..7b932b5a84 100644 --- a/crates/registry-discovery/src/runtime_config.rs +++ b/crates/registry-discovery/src/runtime_config.rs @@ -169,7 +169,7 @@ pub enum LogLevel { /// retired apiVersions. #[must_use] pub const fn runtime_loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(RUNTIME_ENVELOPE) .removed_keys(REMOVED_RUNTIME_KEYS) .retired_api_versions(RETIRED_RUNTIME_API_VERSIONS) .require_trusted_ownership() diff --git a/crates/registry-documents/src/config.rs b/crates/registry-documents/src/config.rs index 5558cdd50d..cfc71de5fd 100644 --- a/crates/registry-documents/src/config.rs +++ b/crates/registry-documents/src/config.rs @@ -545,7 +545,7 @@ fn refused(findings: &[Finding]) -> String { impl RuntimeConfig { #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(DOCUMENTS_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(DOCUMENTS_RUNTIME_ENVELOPE) .removed_keys(DOCUMENTS_REMOVED_KEYS) .require_trusted_ownership() } @@ -782,7 +782,10 @@ impl RuntimeConfig { fn check_oidc(&self, findings: &mut Vec) { let oidc = &self.authentication.oidc; let development = self.listener.tls_termination == TlsTermination::DevelopmentLoopback; - if let Err(error) = oidc.provider.check("authentication.oidc", development) { + if let Err(error) = oidc + .provider + .check_without_posture("authentication.oidc", development) + { findings.push(Finding::block("/authentication/oidc", &error)); } if let Err(error) = oidc.clients.check("authentication.oidc") { diff --git a/crates/registry-evidence-oid4vci/src/config.rs b/crates/registry-evidence-oid4vci/src/config.rs index 2ec3f988a9..00b09941b3 100644 --- a/crates/registry-evidence-oid4vci/src/config.rs +++ b/crates/registry-evidence-oid4vci/src/config.rs @@ -81,7 +81,7 @@ const REMOVED_KEYS: &[RemovedKey] = &[ /// The shared runtime reader for a delivery runtime file. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: OID4VCI_RUNTIME_API_VERSION, kind: OID4VCI_RUNTIME_KIND, }) diff --git a/crates/registry-evidence-oid4vp/src/config.rs b/crates/registry-evidence-oid4vp/src/config.rs index c3c497d959..09fa8f827b 100644 --- a/crates/registry-evidence-oid4vp/src/config.rs +++ b/crates/registry-evidence-oid4vp/src/config.rs @@ -62,7 +62,7 @@ const REMOVED_KEYS: &[RemovedKey] = &[ /// The shared runtime reader for a runtime file. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: OID4VP_RUNTIME_API_VERSION, kind: OID4VP_RUNTIME_KIND, }) @@ -1321,7 +1321,7 @@ impl VerifierDocument { &self.evidence_credentials.provider, ), ] { - let Err(error) = provider.check(field, false) else { + let Err(error) = provider.check_without_posture(field, false) else { continue; }; let member = error.field().rsplit('.').next().unwrap_or_default(); diff --git a/crates/registry-evidence/src/config.rs b/crates/registry-evidence/src/config.rs index 26393c7a7a..42d3803970 100644 --- a/crates/registry-evidence/src/config.rs +++ b/crates/registry-evidence/src/config.rs @@ -2545,7 +2545,7 @@ impl RuntimeConfig { /// The shared loader configured with the Evidence envelope and the keys /// it no longer accepts. pub fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(EVIDENCE_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(EVIDENCE_RUNTIME_ENVELOPE) .removed_keys(EVIDENCE_RUNTIME_REMOVED_KEYS) .retired_api_versions(EVIDENCE_RETIRED_RUNTIME_API_VERSIONS) } @@ -3524,7 +3524,7 @@ impl OidcAuthenticationConfig { } } self.provider - .check( + .check_without_posture( "authentication.oidc", assurance_profile == AssuranceProfile::Local, ) diff --git a/crates/registry-mcp/src/adapter.rs b/crates/registry-mcp/src/adapter.rs index 016d3fa27e..427f8d6289 100644 --- a/crates/registry-mcp/src/adapter.rs +++ b/crates/registry-mcp/src/adapter.rs @@ -351,7 +351,7 @@ fn input_schema(operation: &Operation) -> Value { impl AdapterContract { fn loaded_bytes_checked(path: &std::path::Path) -> Result, AdapterContractLoadError> { - let loaded = registry_platform_config::RuntimeConfigLoader::new( + let loaded = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: "id.registrystack.org/formats/adapter/effective-contract/v1alpha1", kind: "AdapterEffectiveContract", diff --git a/crates/registry-mcp/src/config.rs b/crates/registry-mcp/src/config.rs index eaaf39b7ee..143765a8e3 100644 --- a/crates/registry-mcp/src/config.rs +++ b/crates/registry-mcp/src/config.rs @@ -149,7 +149,7 @@ pub struct DelegationConfig { impl RuntimeConfig { pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: API_VERSION, kind: KIND, }).removed_keys(&[RemovedKey { diff --git a/crates/registry-messaging/src/config.rs b/crates/registry-messaging/src/config.rs index 69947141f2..a65cf11363 100644 --- a/crates/registry-messaging/src/config.rs +++ b/crates/registry-messaging/src/config.rs @@ -487,7 +487,7 @@ impl RuntimeConfig { #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(MESSAGING_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(MESSAGING_RUNTIME_ENVELOPE) .removed_keys(MESSAGING_REMOVED_KEYS) .retired_api_versions(MESSAGING_RETIRED_API_VERSIONS) .require_trusted_ownership() @@ -677,7 +677,7 @@ impl RuntimeConfig { fn check_oidc(&self, findings: &mut Vec) { let oidc = &self.authentication.oidc; - if let Err(error) = oidc.provider.check( + if let Err(error) = oidc.provider.check_without_posture( "authentication.oidc", self.listener.tls_termination == TlsTermination::DevelopmentLoopback, ) { diff --git a/crates/registry-messaging/tests/postgres_migrate.rs b/crates/registry-messaging/tests/postgres_migrate.rs index 93acdca8c4..23bcd9d4ce 100644 --- a/crates/registry-messaging/tests/postgres_migrate.rs +++ b/crates/registry-messaging/tests/postgres_migrate.rs @@ -77,6 +77,7 @@ fn database(reference: &str) -> DatabaseConfig { migration_url_ref: reference.to_owned(), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, } } diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index b27745cf34..e8fcfd1ce0 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -17,7 +17,10 @@ use std::str::FromStr; use registry_platform_yaml::{BoundedU32, ExternalId, Invalid, LocalId, Url}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use crate::{SecretError, SecretProvider, SecretReference, SecretResolver, MAX_SECRET_BYTES}; +use crate::{ + DevelopmentClass, DevelopmentOnlyRefused, DevelopmentSetting, DevelopmentWitness, Gated, + SecretError, SecretProvider, SecretReference, SecretResolver, MAX_SECRET_BYTES, +}; /// The schema pattern of a field that must name an enabled secret provider. pub const SECRET_PROVIDER_PATTERN: &str = "^secret:(?:env|file)/"; @@ -261,6 +264,12 @@ pub struct DatabaseConfig { /// Allow a plaintext connection. Refused outside test builds. #[serde(default)] pub test_only_plaintext: bool, + /// How the connection is protected. Absent means `verified-tls`. A + /// plaintext transport must match the database hosts, and cannot be + /// written beside `testOnlyPlaintext`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(with = "Gated"))] + pub transport: Option>, } impl fmt::Debug for DatabaseConfig { @@ -274,6 +283,7 @@ impl fmt::Debug for DatabaseConfig { &self.ca_bundle_ref.as_ref().map(|_| ""), ) .field("test_only_plaintext", &self.test_only_plaintext) + .field("transport", &self.transport) .finish() } } @@ -293,6 +303,207 @@ impl DatabaseConfig { } } +/// How a PostgreSQL connection is protected. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum DatabaseTransport { + /// TLS with verification. `caBundleRef` is optional. + #[default] + VerifiedTls, + /// No TLS. Every host must be a Unix socket, a numeric loopback address + /// or `localhost`. + LoopbackPlaintext, + /// No TLS, in development only. Every host must also be loopback, a + /// socket, a private IPv4 address (RFC 1918), an IPv6 unique local + /// address (`fc00::/7`), or a name that resolves only to such addresses. + PrivateNetworkPlaintext, +} + +static DATABASE_PRIVATE_PLAINTEXT: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.database-private-plaintext", + key: "transport", + summary: "The database connection is not encrypted and reaches a private network", + production: "Write database.transport: verified-tls, and give the database a certificate the runtime trusts.", +}; + +impl DevelopmentClass for DatabaseTransport { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&DATABASE_PRIVATE_PLAINTEXT]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + match self { + Self::VerifiedTls | Self::LoopbackPlaintext => None, + Self::PrivateNetworkPlaintext => Some(&DATABASE_PRIVATE_PLAINTEXT), + } + } +} + +/// A host a PostgreSQL URL names, once the secret is resolved and the URL +/// parsed by the product's driver. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum DatabaseHost { + /// A host name or address, with no brackets required around an IPv6 + /// literal. + Tcp(String), + /// A Unix socket directory. + Unix, +} + +/// Why a database transport was refused. No variant repeats a configured +/// value. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DatabaseTransportError { + /// A host is not one the plaintext transport permits. + HostMismatch(DatabaseTransport), + /// The transport is development-only and the caller holds no witness. + DevelopmentOnly(DevelopmentOnlyRefused), + /// `transport` and `testOnlyPlaintext` are both written. + Conflict, + /// `testOnlyPlaintext` in a build that is not a test build. + TestOnlyPlaintext, +} + +impl DatabaseTransportError { + /// The stable code of the refusal (CFG-DIAG-3). + #[must_use] + pub const fn code(&self) -> &'static str { + match self { + Self::HostMismatch(_) => "platform.database.transport-host-mismatch", + Self::DevelopmentOnly(refused) => refused.setting.code, + Self::Conflict => "platform.database.transport-conflict", + Self::TestOnlyPlaintext => "platform.database.test-only-plaintext", + } + } + + /// What to write instead. + #[must_use] + pub const fn suggested_action(&self) -> &'static str { + match self { + Self::HostMismatch(DatabaseTransport::PrivateNetworkPlaintext) => { + "Name a Unix socket, a loopback address, a private-network address or a name that resolves only to such addresses, or write database.transport: verified-tls." + } + Self::HostMismatch(_) => { + "Name a Unix socket, a loopback address or localhost, or write database.transport: verified-tls." + } + Self::DevelopmentOnly(refused) => refused.setting.production, + Self::Conflict => "Remove database.testOnlyPlaintext, and keep database.transport.", + Self::TestOnlyPlaintext => { + "Remove it, and set database.transport for a plaintext connection on the same host." + } + } + } +} + +impl fmt::Display for DatabaseTransportError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::HostMismatch(_) => { + "a database host is not one the configured plaintext transport permits" + } + Self::DevelopmentOnly(_) => { + "the database transport is accepted only when the process declares development" + } + Self::Conflict => "database.transport and database.testOnlyPlaintext are both set", + Self::TestOnlyPlaintext => "database.testOnlyPlaintext is accepted only by test builds", + }) + } +} + +impl std::error::Error for DatabaseTransportError {} + +impl DatabaseConfig { + /// The checks every posture applies to the transport: `transport` is not + /// written beside `testOnlyPlaintext`, and `testOnlyPlaintext` is + /// written only in a test build, which the product states with + /// `test_build`. + pub fn check(&self, test_build: bool) -> Result<(), DatabaseTransportError> { + if self.test_only_plaintext && self.transport.is_some() { + return Err(DatabaseTransportError::Conflict); + } + if self.test_only_plaintext && !test_build { + return Err(DatabaseTransportError::TestOnlyPlaintext); + } + Ok(()) + } + + /// The transport the connection uses, once `hosts` are known: a plaintext + /// transport is returned only when every host is one it permits. A + /// development-only transport is readable with `witness` alone. A name is + /// resolved here, once, so a later re-resolution by the driver is outside + /// the check; a name that does not resolve is refused. + pub fn plaintext_permitted( + &self, + hosts: &[DatabaseHost], + witness: Option<&DevelopmentWitness>, + ) -> Result { + plaintext_permitted_with(self, hosts, witness, &resolve_host) + } +} + +fn resolve_host(name: &str) -> std::io::Result> { + use std::net::ToSocketAddrs; + (name, 0) + .to_socket_addrs() + .map(|addresses| addresses.map(|address| address.ip()).collect()) +} + +pub(crate) fn plaintext_permitted_with( + config: &DatabaseConfig, + hosts: &[DatabaseHost], + witness: Option<&DevelopmentWitness>, + resolve: &dyn Fn(&str) -> std::io::Result>, +) -> Result { + let transport = match &config.transport { + None => DatabaseTransport::VerifiedTls, + Some(gated) => *gated + .get(witness) + .map_err(DatabaseTransportError::DevelopmentOnly)?, + }; + let permitted = |host: &DatabaseHost| match (transport, host) { + (DatabaseTransport::VerifiedTls, _) | (_, DatabaseHost::Unix) => true, + (DatabaseTransport::LoopbackPlaintext, DatabaseHost::Tcp(name)) => { + registry_platform_loopback::loopback_host(name).is_some() + } + (DatabaseTransport::PrivateNetworkPlaintext, DatabaseHost::Tcp(name)) => { + private_network_host(name, resolve) + } + }; + if hosts.iter().all(permitted) { + Ok(transport) + } else { + Err(DatabaseTransportError::HostMismatch(transport)) + } +} + +/// Whether `name` is loopback, a private IPv4 address, an IPv6 unique local +/// address, or a name that resolves, and resolves only, to such addresses. +fn private_network_host( + name: &str, + resolve: &dyn Fn(&str) -> std::io::Result>, +) -> bool { + if registry_platform_loopback::loopback_host(name).is_some() { + return true; + } + let literal = name + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + .unwrap_or(name); + if let Ok(address) = literal.parse::() { + return private_address(address); + } + match resolve(name) { + Ok(addresses) => !addresses.is_empty() && addresses.into_iter().all(private_address), + Err(_) => false, + } +} + +fn private_address(address: IpAddr) -> bool { + match address { + IpAddr::V4(address) => address.is_loopback() || address.is_private(), + IpAddr::V6(address) => address.is_loopback() || is_unique_local(address), + } +} + /// Where a runtime obtains the OIDC issuer's signing keys. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] @@ -449,6 +660,51 @@ fn valid_jwks_uri(value: &Url, allow_loopback_http: bool, allow_insecure_http: b pub struct AuditKeyConfig { /// Secret reference to the audit hash key. pub hash_key_ref: SecretReference, + /// Who provisioned the key. Absent means `operator-provisioned`. + /// `development-generated` marks a key a development tool made. + #[serde( + default = "operator_provisioned", + skip_serializing_if = "is_operator_provisioned" + )] + pub hash_key_custody: Gated, +} + +/// Who provisioned the audit hash key. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum AuditKeyCustody { + /// The operator provisioned the key. + #[default] + OperatorProvisioned, + /// A development tool generated the key. + DevelopmentGenerated, +} + +static GENERATED_AUDIT_KEY: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.generated-audit-key", + key: "hashKeyCustody", + summary: "The audit hash key was generated by a development tool", + production: "Provision an audit hash key, reference it in audit.hashKeyRef, and write audit.hashKeyCustody: operator-provisioned.", +}; + +impl DevelopmentClass for AuditKeyCustody { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&GENERATED_AUDIT_KEY]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + match self { + Self::OperatorProvisioned => None, + Self::DevelopmentGenerated => Some(&GENERATED_AUDIT_KEY), + } + } +} + +fn operator_provisioned() -> Gated { + Gated::wrap(AuditKeyCustody::OperatorProvisioned) +} + +fn is_operator_provisioned(custody: &Gated) -> bool { + custody.development_setting().is_none() } impl AuditKeyConfig { @@ -485,22 +741,67 @@ pub struct OidcIssuerConfig { #[serde(default)] pub jwks_source: JwksSource, /// Permit plain HTTP beyond loopback to the configured issuer and to a - /// JWKS URI declared in configuration. TLS remains required unless the - /// operator explicitly accepts this transport risk. - #[serde(default)] + /// JWKS URI declared in configuration. Loopback needs no setting. The + /// value `true` is a development-only setting: the loader records it, and + /// production refuses it. + #[serde(default, deserialize_with = "deserialize_insecure_http")] + #[cfg_attr( + feature = "schema", + schemars(extend("x-registry-development-only" = ["platform.posture.insecure-issuer-http"])) + )] pub allow_insecure_http: bool, } +/// The value of `allowInsecureHttp`. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(transparent)] +pub struct InsecureHttp(pub bool); + +static INSECURE_ISSUER_HTTP: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.insecure-issuer-http", + key: "allowInsecureHttp", + summary: "Plain http is permitted to an issuer beyond loopback", + production: "Delete allowInsecureHttp and use an https issuer.", +}; + +impl DevelopmentClass for InsecureHttp { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&INSECURE_ISSUER_HTTP]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + self.0.then_some(&INSECURE_ISSUER_HTTP) + } +} + +/// Read `allowInsecureHttp` through [`Gated`], so a loader that collects +/// development-only settings records `true` with its pointer. +fn deserialize_insecure_http<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Gated::::deserialize(deserializer) + .map(|value| value.development_setting().is_some()) +} + impl OidcIssuerConfig { /// The issuer is an absolute `https` URL without credentials, query, or - /// fragment, or a plain `http` one when `allow_insecure_http` is set, the - /// audience is non-empty bounded text without control characters, and - /// the key source passes [`JwksSource::check`]. Without - /// `allow_insecure_http`, a loopback `http` issuer or key URI is accepted - /// only when `allow_loopback_http` is set, for supervised local - /// development. `field` is the dotted path of the block, - /// such as `authentication.oidc`. - pub fn check(&self, field: &str, allow_loopback_http: bool) -> Result<(), ConfigBlockError> { + /// fragment, a loopback `http` one, or a plain `http` one when + /// `allow_insecure_http` is set, the audience is non-empty bounded text + /// without control characters, and the key source passes + /// [`JwksSource::check`]. Loopback needs no setting in any posture. A + /// plain `http` issuer beyond loopback is accepted here when + /// `allow_insecure_http` is set, and the posture decision refuses it in + /// production. `field` is the dotted path of the block, such as + /// `authentication.oidc`. + pub fn check(&self, field: &str) -> Result<(), ConfigBlockError> { + self.check_without_posture(field, true) + } + + /// [`OidcIssuerConfig::check`] for a runtime that has not adopted the + /// posture: a loopback `http` issuer or key URI is accepted only when + /// `allow_loopback_http` is set. + pub fn check_without_posture( + &self, + field: &str, + allow_loopback_http: bool, + ) -> Result<(), ConfigBlockError> { let issuer = self.issuer.to_url(); let issuer_ok = valid_jwks_uri(&self.issuer, allow_loopback_http, self.allow_insecure_http) && issuer.query().is_none() diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index d41d6eb0fa..24cea8b96f 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -237,7 +237,9 @@ fn issuer_and_jwks_uri_are_checked_urls_when_read() { let issuer: OidcIssuerConfig = read_block(&serde_json::json!({"issuer": text, "audience": "api"}).to_string()) .expect("ordinary issuer URL"); - issuer.check("authentication.oidc", false).unwrap(); + issuer + .check_without_posture("authentication.oidc", false) + .unwrap(); assert_eq!(issuer.issuer.as_str(), text); } } @@ -541,14 +543,14 @@ fn the_oidc_issuer_is_an_https_url_and_the_audience_is_bounded_text() { "urn:example:api", JwksSource::default(), ) - .check(field, false) + .check_without_posture(field, false) .expect("https issuer"); issuer("http://127.0.0.1:8082", "api", JwksSource::default()) - .check(field, true) + .check_without_posture(field, true) .expect("supervised loopback issuer"); for loopback in ["http://localhost:8082", "http://[::1]:8082"] { issuer(loopback, "api", JwksSource::default()) - .check(field, true) + .check_without_posture(field, true) .expect("every loopback spelling is admitted"); } @@ -560,7 +562,7 @@ fn the_oidc_issuer_is_an_https_url_and_the_audience_is_bounded_text() { assert!(opted_in.issuer.allow_insecure_http); opted_in .issuer - .check(field, false) + .check_without_posture(field, false) .expect("explicit HTTP issuer opt-in validates"); for (candidate, loopback, expected_field) in [ @@ -615,7 +617,7 @@ fn the_oidc_issuer_is_an_https_url_and_the_audience_is_bounded_text() { ), ] { let error = candidate - .check(field, loopback) + .check_without_posture(field, loopback) .expect_err("refused issuer"); assert_eq!(error.field(), expected_field, "{error}"); assert!(!error.to_string().contains("user:pass"), "{error}"); @@ -644,7 +646,7 @@ fn the_insecure_http_opt_in_also_admits_a_declared_http_jwks_uri() { }, ); let error = candidate - .check(field, false) + .check_without_posture(field, false) .expect_err("a plain HTTP key URI needs the opt-in"); assert_eq!(error.field(), "authentication.oidc.jwksSource.uri"); assert!(error.to_string().contains("allowInsecureHttp: true")); @@ -652,7 +654,7 @@ fn the_insecure_http_opt_in_also_admits_a_declared_http_jwks_uri() { candidate.allow_insecure_http = true; candidate - .check(field, false) + .check_without_posture(field, false) .expect("the opt-in admits a declared HTTP key URI under an HTTPS issuer"); } @@ -664,14 +666,14 @@ fn an_oidc_issuer_with_a_query_is_refused_without_echoing_it() { "api", JwksSource::default(), ) - .check(field, false) + .check_without_posture(field, false) .expect("an issuer with a path"); for candidate in [ "https://issuer.example.test/realms/pilot?tenant=query-canary", "https://issuer.example.test/?", ] { let error = issuer(candidate, "api", JwksSource::default()) - .check(field, false) + .check_without_posture(field, false) .expect_err("an issuer with a query is refused"); assert_eq!(error.field(), "authentication.oidc.issuer", "{error}"); assert!(error.to_string().contains("query"), "{error}"); diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index 1339ad60bc..ca3d3b110f 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -15,6 +15,8 @@ mod metrics_bind; mod offline; pub mod package; mod posture; +#[cfg(test)] +mod posture_load_tests; #[cfg(feature = "schema")] pub mod schema; mod secrets; @@ -25,9 +27,10 @@ use sha2::{Digest, Sha256}; pub use blocks::url_hook_destinations_schema; pub use blocks::{ describe_secret_failure, is_sha256_label, url_hook_destinations, AdmittedClients, - AttachmentVerifierConfig, AttemptTimeoutMilliseconds, AuditKeyConfig, ConfigBlockError, - ConfigBlockErrorKind, DatabaseConfig, EnvironmentSecretProviderConfig, - FileSecretProviderConfig, JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, + AttachmentVerifierConfig, AttemptTimeoutMilliseconds, AuditKeyConfig, AuditKeyCustody, + ConfigBlockError, ConfigBlockErrorKind, DatabaseConfig, DatabaseHost, DatabaseTransport, + DatabaseTransportError, EnvironmentSecretProviderConfig, FileSecretProviderConfig, + InsecureHttp, JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, OidcPackageClientsConfig, PackageClients, PackageClientsError, PackageConfig, PackageDigestMismatch, PrivateListenerConfig, SecretProvidersConfig, TaskGrantStatusConfig, diff --git a/crates/registry-platform-config/src/loader.rs b/crates/registry-platform-config/src/loader.rs index 1bf1307e47..7951da5317 100644 --- a/crates/registry-platform-config/src/loader.rs +++ b/crates/registry-platform-config/src/loader.rs @@ -45,6 +45,10 @@ use registry_platform_yaml::{ }; use serde::de::DeserializeOwned; +use crate::posture::{ + collect_development_settings, DeclaredPosture, DevelopmentWitness, Posture, PostureReport, + PostureSource, +}; use crate::{resolve_config_env_expression, sha256_uri}; /// The default size cap for a runtime configuration document. @@ -168,6 +172,12 @@ impl RuntimeConfigError { Self::from_report(Report::new(diagnostics)).in_file(file) } + /// This refusal with `diagnostics` listed after its own. + pub(crate) fn with_diagnostics(mut self, diagnostics: Vec) -> Self { + self.detail.diagnostics.extend(diagnostics); + self + } + fn from_report(report: Report) -> Self { let diagnostics = report.into_diagnostics(); assert!( @@ -281,6 +291,13 @@ pub struct LoadedRuntimeConfig { /// spelling of an environment expression that resolved to the same value /// carry the same digest. pub effective_digest: String, + /// The declared posture and every development-only setting the document + /// holds. A loader made without a posture reports production and records + /// no setting. + pub posture: PostureReport, + /// Proof that the process declared development: `Some` only then, and + /// the only way to read a value that selects a development-only setting. + pub development: Option, } impl std::fmt::Debug for LoadedRuntimeConfig { @@ -313,16 +330,48 @@ pub struct RuntimeConfigLoader { removed_keys: &'static [RemovedKey], retired_api_versions: &'static [RetiredApiVersion<'static>], trusted_ownership: bool, + /// The posture the process declared. `None` for a loader made without a + /// posture, which refuses and records no development-only setting. + posture: Option, +} + +/// What a parse does with the development-only settings it found. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Decision { + /// Refuse the document when the posture is production and it holds one. + Refuse, + /// Return the document and the settings, for a check that reports them. + Report, } impl RuntimeConfigLoader { + /// A loader for a process that declared `declared`. A document that + /// holds a development-only setting is refused in production, with every + /// such setting listed beside any other problem, and accepted in + /// development, which also yields the witness that reads those settings. #[must_use] - pub const fn new(envelope: RuntimeEnvelope) -> Self { + pub const fn new(envelope: RuntimeEnvelope, declared: DeclaredPosture) -> Self { Self { envelope, removed_keys: &[], retired_api_versions: &[], trusted_ownership: false, + posture: Some(declared), + } + } + + /// A loader that declares no posture. It reports production, never + /// issues the witness, and neither refuses nor records a development-only + /// setting: a runtime that has not adopted the posture keeps the + /// behaviour it had. + #[must_use] + pub const fn new_without_posture(envelope: RuntimeEnvelope) -> Self { + Self { + envelope, + removed_keys: &[], + retired_api_versions: &[], + trusted_ownership: false, + posture: None, } } @@ -377,7 +426,7 @@ impl RuntimeConfigLoader { lookup: impl Fn(&str) -> Option, ) -> Result, RuntimeConfigError> { let bytes = self.read_file(path)?; - self.parse_file(path, &bytes, &lookup) + self.parse_file(path, &bytes, &lookup, Decision::Refuse) } /// The bytes of the file at `path`, read under the file rules: the one @@ -392,9 +441,15 @@ impl RuntimeConfigLoader { path: &Path, bytes: &[u8], lookup: &dyn Fn(&str) -> Option, + decision: Decision, ) -> Result, RuntimeConfigError> { - self.parse(&path.display().to_string(), bytes, Fill::Variables(lookup)) - .map_err(|error| error.in_file(path)) + self.parse( + &path.display().to_string(), + bytes, + Fill::Variables(lookup), + decision, + ) + .map_err(|error| error.in_file(path)) } /// Apply every rule after the file read to the `bytes` read from `path`, @@ -405,9 +460,15 @@ impl RuntimeConfigLoader { path: &Path, bytes: &[u8], stand_in: &dyn Fn(&str) -> String, + decision: Decision, ) -> Result, RuntimeConfigError> { - self.parse(&path.display().to_string(), bytes, Fill::StandIns(stand_in)) - .map_err(|error| error.in_file(path)) + self.parse( + &path.display().to_string(), + bytes, + Fill::StandIns(stand_in), + decision, + ) + .map_err(|error| error.in_file(path)) } /// Apply every rule after the file read to `text`. Used by authoring tools @@ -418,15 +479,70 @@ impl RuntimeConfigLoader { text: &str, lookup: impl Fn(&str) -> Option, ) -> Result, RuntimeConfigError> { - self.parse(BUFFER_NAME, text.as_bytes(), Fill::Variables(&lookup)) + self.parse( + BUFFER_NAME, + text.as_bytes(), + Fill::Variables(&lookup), + Decision::Refuse, + ) } + /// Decode the document, then settle the posture: collect the + /// development-only settings the decode finds, and under + /// [`Decision::Refuse`] refuse them in production. fn parse( &self, file: &str, bytes: &[u8], fill: Fill<'_>, + decision: Decision, ) -> Result, RuntimeConfigError> { + let Some(declared) = self.posture else { + let (config, effective_digest) = self.decode::(file, bytes, fill)?; + return Ok(LoadedRuntimeConfig { + config, + effective_digest, + posture: PostureReport::new(DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Default, + }), + development: None, + }); + }; + let (decoded, found) = collect_development_settings(|| self.decode::(file, bytes, fill)); + let mut posture = PostureReport::new(declared); + for setting in found { + posture.record(setting); + } + let named = Path::new(file); + match decoded { + Ok((config, effective_digest)) => { + if decision == Decision::Refuse { + posture.decide(named)?; + } + Ok(LoadedRuntimeConfig { + config, + effective_digest, + posture, + development: (declared.posture == Posture::Development) + .then(DevelopmentWitness::issue), + }) + } + // The settings found before the failure are still reported, so + // one run lists every problem (CFG-DIAG-5). + Err(error) => Err(match decision { + Decision::Refuse if declared.posture == Posture::Development => error, + _ => error.with_diagnostics(posture.diagnostics(named)), + }), + } + } + + fn decode( + &self, + file: &str, + bytes: &[u8], + fill: Fill<'_>, + ) -> Result<(T, String), RuntimeConfigError> { let removed: Vec<(String, String)> = self .removed_keys .iter() @@ -462,10 +578,7 @@ impl RuntimeConfigLoader { "Write every number as a plain decimal within the range JSON can carry.", ) })?; - Ok(LoadedRuntimeConfig { - config: decoded.value, - effective_digest: sha256_uri(&canonical), - }) + Ok((decoded.value, sha256_uri(&canonical))) } fn read(&self, path: &Path) -> Result, RuntimeConfigError> { diff --git a/crates/registry-platform-config/src/loader_tests.rs b/crates/registry-platform-config/src/loader_tests.rs index 4a1091706b..67ac3f7b18 100644 --- a/crates/registry-platform-config/src/loader_tests.rs +++ b/crates/registry-platform-config/src/loader_tests.rs @@ -64,7 +64,7 @@ struct Audit { } fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(ENVELOPE).removed_keys(REMOVED) + RuntimeConfigLoader::new_without_posture(ENVELOPE).removed_keys(REMOVED) } fn header() -> String { @@ -1094,7 +1094,7 @@ mod files { #[test] fn the_shared_removed_jwks_uri_key_names_jwks_source() { - let loader = RuntimeConfigLoader::new(ENVELOPE) + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE) .removed_keys(std::slice::from_ref(&REMOVED_OIDC_JWKS_URI)); let error = loader .parse_str::( @@ -1119,7 +1119,7 @@ fn the_shared_removed_jwks_uri_key_names_jwks_source() { #[test] fn the_shared_removed_jwks_source_kind_key_names_type() { - let loader = RuntimeConfigLoader::new(ENVELOPE) + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE) .removed_keys(std::slice::from_ref(&REMOVED_OIDC_JWKS_SOURCE_KIND)); let error = loader .parse_str::( diff --git a/crates/registry-platform-config/src/offline.rs b/crates/registry-platform-config/src/offline.rs index 6cfc0aa51d..a350c2d35f 100644 --- a/crates/registry-platform-config/src/offline.rs +++ b/crates/registry-platform-config/src/offline.rs @@ -12,6 +12,7 @@ use registry_platform_yaml::{ }; use serde::de::DeserializeOwned; +use crate::loader::Decision; use crate::{ contains_environment_expression, LoadedRuntimeConfig, RuntimeConfigLoader, UNAVAILABLE_CODE, }; @@ -32,7 +33,10 @@ pub struct RuntimeFileCheck { /// Every loader finding, each naming the file as the path was given. A /// finding that depends on the value of a deferred expression is left /// out; in its place stands a warning, coded [`INCOMPLETE_CODE`], that - /// the check stopped at that member. + /// the check stopped at that member. Under a declared posture, each + /// development-only setting the file holds is one finding: an error in + /// production and a warning in development, with the same code. The + /// file is still decoded, so the product's own checks run beside them. pub diagnostics: Vec, /// The file could not be read at all, as opposed to read and refused. pub unavailable: bool, @@ -224,6 +228,9 @@ impl RuntimeConfigLoader { /// repeat. A member that refuses its stand-in stops the decode: the check /// then reports a warning at that member, coded [`INCOMPLETE_CODE`], for /// the members it did not read. + /// + /// The posture is the loader's: a loader made without a posture reports + /// no development-only setting. pub fn check_offline( &self, path: &Path, @@ -241,15 +248,26 @@ impl RuntimeConfigLoader { }; let loaded = bytes.and_then(|bytes| { if substitute { - self.parse_file::(path, &bytes, &|name| std::env::var(name).ok()) + self.parse_file::( + path, + &bytes, + &|name| std::env::var(name).ok(), + Decision::Report, + ) } else { - self.parse_file_with_stand_ins::(path, &bytes, &|pointer| { - deferred.stand_in(pointer).to_owned() - }) + self.parse_file_with_stand_ins::( + path, + &bytes, + &|pointer| deferred.stand_in(pointer).to_owned(), + Decision::Report, + ) } }); let (loaded, diagnostics, unavailable) = match loaded { - Ok(loaded) => (Some(loaded), Vec::new(), false), + Ok(loaded) => { + let found = loaded.posture.diagnostics(path); + (Some(loaded), found, false) + } Err(error) => ( None, error @@ -413,7 +431,7 @@ mod tests { use serde::Deserialize; use std::fs; - const LOADER: RuntimeConfigLoader = RuntimeConfigLoader::new(RuntimeEnvelope { + const LOADER: RuntimeConfigLoader = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: "registry.registrystack.org/example-runtime/v1alpha1", kind: "ExampleRuntimeConfig", }); diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs index ce2d33ab71..6301f110f8 100644 --- a/crates/registry-platform-config/src/posture.rs +++ b/crates/registry-platform-config/src/posture.rs @@ -123,7 +123,6 @@ pub struct DevelopmentWitness { impl DevelopmentWitness { /// The loader issues the witness to a process that declared development. - #[allow(dead_code)] pub(crate) const fn issue() -> Self { Self { _sealed: () } } @@ -166,9 +165,17 @@ pub struct DevelopmentOnlyRefused { /// /// There is no `Deref` and no way to take the value out: a value that selects /// a development-only setting is unreadable without a [`DevelopmentWitness`]. -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq, Eq)] pub struct Gated(T); +impl Gated { + /// Hold `value`, whatever it selects. Shared blocks use it for the value + /// an omitted member stands for. + pub(crate) const fn wrap(value: T) -> Self { + Self(value) + } +} + impl Gated { /// The value, when it is valid in every posture or the caller holds the /// witness. diff --git a/crates/registry-platform-config/src/posture_load_tests.rs b/crates/registry-platform-config/src/posture_load_tests.rs new file mode 100644 index 0000000000..c21dd2fdcf --- /dev/null +++ b/crates/registry-platform-config/src/posture_load_tests.rs @@ -0,0 +1,528 @@ +//! The loader and the offline check under a declared posture, with the shared +//! blocks that hold development-only settings. + +use std::fs; +use std::net::{IpAddr, Ipv4Addr}; +use std::path::PathBuf; + +use registry_platform_yaml::Severity; +use serde::Deserialize; + +use crate::blocks::{ + plaintext_permitted_with, AuditKeyConfig, AuditKeyCustody, DatabaseConfig, DatabaseHost, + DatabaseTransport, DatabaseTransportError, OidcIssuerConfig, +}; +use crate::{ + DeclaredPosture, Posture, PostureSource, RuntimeConfigLoader, RuntimeEnvelope, DEFAULT_STAND_IN, +}; + +const ENVELOPE: RuntimeEnvelope = RuntimeEnvelope { + api_version: "registry.registrystack.org/example-runtime/v1alpha1", + kind: "ExampleRuntimeConfig", +}; + +const HEAD: &str = + "apiVersion: registry.registrystack.org/example-runtime/v1alpha1\nkind: ExampleRuntimeConfig\n"; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[allow(dead_code)] +struct Example { + database: DatabaseConfig, + authentication: Authentication, + audit: Audit, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Authentication { + oidc: Oidc, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Oidc { + #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-issuer"))] + provider: OidcIssuerConfig, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[allow(dead_code)] +struct Audit { + path: String, + #[serde(rename(deserialize = "registry-platform-yaml/shared-block/audit-key"))] + key: AuditKeyConfig, +} + +const SHARED_CODES: [&str; 3] = [ + "platform.posture.database-private-plaintext", + "platform.posture.insecure-issuer-http", + "platform.posture.generated-audit-key", +]; + +const SHARED_POINTERS: [&str; 3] = [ + "/database/transport", + "/authentication/oidc/allowInsecureHttp", + "/audit/hashKeyCustody", +]; + +/// A file holding every development-only setting the shared blocks have. +fn every_setting() -> String { + format!( + "{HEAD}database:\n runtimeUrlRef: secret:env/DB_RUNTIME\n migrationUrlRef: secret:env/DB_MIGRATION\n transport: private-network-plaintext\nauthentication:\n oidc:\n issuer: http://issuer.example.test\n audience: api\n allowInsecureHttp: true\naudit:\n path: /var/lib/audit\n hashKeyRef: secret:env/AUDIT_KEY\n hashKeyCustody: development-generated\n" + ) +} + +/// The same file with every setting at a value valid in every posture. +fn no_setting() -> String { + format!( + "{HEAD}database:\n runtimeUrlRef: secret:env/DB_RUNTIME\n migrationUrlRef: secret:env/DB_MIGRATION\n transport: verified-tls\nauthentication:\n oidc:\n issuer: https://issuer.example.test\n audience: api\n allowInsecureHttp: false\naudit:\n path: /var/lib/audit\n hashKeyRef: secret:env/AUDIT_KEY\n hashKeyCustody: operator-provisioned\n" + ) +} + +fn declared(posture: Posture) -> DeclaredPosture { + DeclaredPosture { + posture, + source: PostureSource::Flag, + } +} + +fn parse( + loader: &RuntimeConfigLoader, + text: &str, +) -> Result, crate::RuntimeConfigError> { + loader.parse_str::(text, |_| None) +} + +#[test] +fn production_refuses_every_shared_development_setting_and_lists_each_with_its_pointer() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let error = parse(&loader, &every_setting()).expect_err("production refuses"); + let diagnostics = error.diagnostics(); + for (code, pointer) in SHARED_CODES.iter().zip(SHARED_POINTERS) { + let found = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == *code) + .unwrap_or_else(|| panic!("{code} is listed: {diagnostics:?}")); + assert_eq!(found.path, pointer, "{code}"); + assert_eq!(found.severity, Severity::Error, "{code}"); + assert!(found.source.as_ref().unwrap().line.is_some(), "{code}"); + } + assert_eq!(diagnostics.len(), 3, "{diagnostics:?}"); +} + +#[test] +fn a_decode_failure_and_the_settings_found_before_it_are_reported_together() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let text = every_setting().replace("audience: api\n", "audience: api\n unknown: 1\n"); + let error = parse(&loader, &text).expect_err("production refuses"); + let codes: Vec<&str> = error + .diagnostics() + .iter() + .map(|diagnostic| diagnostic.code.as_str()) + .collect(); + assert!(codes.contains(&"config.unknown-key"), "{codes:?}"); + assert!( + codes.contains(&"platform.posture.database-private-plaintext"), + "{codes:?}" + ); +} + +#[test] +fn development_admits_the_settings_lists_them_and_yields_a_witness() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)); + let loaded = parse(&loader, &every_setting()).expect("development admits"); + assert_eq!(loaded.posture.posture(), Posture::Development); + let witness = loaded.development.as_ref().expect("a witness"); + let listed: Vec<(&str, Option<&str>)> = loaded + .posture + .settings() + .iter() + .map(|found| (found.setting.code, found.pointer.as_deref())) + .collect(); + for (code, pointer) in SHARED_CODES.iter().zip(SHARED_POINTERS) { + assert!( + listed.contains(&(*code, Some(pointer))), + "{code}: {listed:?}" + ); + } + assert_eq!(listed.len(), 3); + let warnings = loaded + .posture + .diagnostics(PathBuf::from("runtime.yaml").as_path()); + assert!(warnings + .iter() + .all(|diagnostic| diagnostic.severity == Severity::Warning)); + loaded + .posture + .decide(PathBuf::from("runtime.yaml").as_path()) + .unwrap(); + + let database = &loaded.config.database; + let transport = database.transport.as_ref().expect("written"); + assert_eq!( + transport.get(Some(witness)).unwrap(), + &DatabaseTransport::PrivateNetworkPlaintext + ); + assert!(transport.get(None).is_err()); + assert_eq!( + loaded + .config + .audit + .key + .hash_key_custody + .get(Some(witness)) + .unwrap(), + &AuditKeyCustody::DevelopmentGenerated + ); +} + +#[test] +fn a_file_with_no_development_setting_loads_the_same_in_both_postures_and_only_development_holds_a_witness( +) { + for posture in [Posture::Production, Posture::Development] { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(posture)); + let loaded = parse(&loader, &no_setting()).expect("valid in every posture"); + assert!(loaded.posture.settings().is_empty(), "{posture:?}"); + assert_eq!( + loaded.development.is_some(), + posture == Posture::Development, + "{posture:?}" + ); + } + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + assert!(parse(&loader, &every_setting()).is_err()); +} + +#[test] +fn an_omitted_custody_is_operator_provisioned_and_an_omitted_transport_is_verified_tls() { + let text = no_setting() + .replace(" transport: verified-tls\n", "") + .replace(" hashKeyCustody: operator-provisioned\n", "") + .replace(" allowInsecureHttp: false\n", ""); + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let loaded = parse(&loader, &text).expect("valid"); + assert!(loaded.posture.settings().is_empty()); + assert!(loaded.config.database.transport.is_none()); + assert_eq!( + loaded.config.audit.key.hash_key_custody.get(None).unwrap(), + &AuditKeyCustody::OperatorProvisioned + ); + assert_eq!( + serde_json::to_value(&loaded.config.audit.key).unwrap(), + serde_json::json!({"hashKeyRef": "secret:env/AUDIT_KEY"}), + "an omitted custody is not written back" + ); +} + +#[test] +fn the_entry_point_without_a_posture_admits_what_it_always_admitted_and_reports_production() { + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE); + let loaded = parse(&loader, &every_setting()).expect("admitted, as before"); + assert_eq!(loaded.posture.posture(), Posture::Production); + assert!(loaded.posture.settings().is_empty()); + assert!(loaded.development.is_none()); + assert!( + loaded + .config + .authentication + .oidc + .provider + .allow_insecure_http + ); +} + +fn check_file(loader: &RuntimeConfigLoader, text: &str) -> crate::RuntimeFileCheck { + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let path = directory.path().join("runtime.yaml"); + fs::write(&path, text).unwrap(); + loader.check_offline::(&path, true, |_| DEFAULT_STAND_IN) +} + +#[test] +fn the_offline_check_in_production_decodes_the_file_and_reports_each_setting_as_an_error() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let check = check_file(&loader, &every_setting()); + assert!(check.loaded.is_some(), "product checks still run"); + assert_eq!(check.diagnostics.len(), 3, "{:?}", check.diagnostics); + for (code, pointer) in SHARED_CODES.iter().zip(SHARED_POINTERS) { + let found = check + .diagnostics + .iter() + .find(|diagnostic| diagnostic.code == *code) + .unwrap_or_else(|| panic!("{code}: {:?}", check.diagnostics)); + assert_eq!(found.path, pointer); + assert_eq!(found.severity, Severity::Error); + } + let report = check.report_with("example", Vec::new()); + assert_eq!(report.diagnostics().len(), 3); +} + +#[test] +fn the_offline_check_in_development_reports_the_same_codes_as_warnings() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)); + let check = check_file(&loader, &every_setting()); + assert!(check.loaded.is_some()); + let codes: Vec<&str> = check + .diagnostics + .iter() + .map(|diagnostic| diagnostic.code.as_str()) + .collect(); + assert_eq!(codes.len(), 3, "{codes:?}"); + for code in SHARED_CODES { + assert!(codes.contains(&code), "{code}: {codes:?}"); + } + assert!(check + .diagnostics + .iter() + .all(|diagnostic| diagnostic.severity == Severity::Warning)); +} + +#[test] +fn the_offline_check_without_a_posture_adds_nothing() { + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE); + let check = check_file(&loader, &every_setting()); + assert!(check.loaded.is_some()); + assert!(check.diagnostics.is_empty(), "{:?}", check.diagnostics); +} + +#[test] +fn a_decode_failure_in_a_check_carries_the_settings_found_before_it() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let text = every_setting().replace("audience: api\n", "audience: api\n unknown: 1\n"); + let check = check_file(&loader, &text); + assert!(check.loaded.is_none()); + let codes: Vec<&str> = check + .diagnostics + .iter() + .map(|diagnostic| diagnostic.code.as_str()) + .collect(); + assert!(codes.contains(&"config.unknown-key"), "{codes:?}"); + assert!( + codes.contains(&"platform.posture.database-private-plaintext"), + "{codes:?}" + ); +} + +// The issuer check + +/// One shared block read alone, through the shared reader. +fn read_block(text: &str) -> T { + use registry_platform_yaml::{EnvelopeRule, Expect, FormatSpec, Reader}; + const BLOCK: FormatSpec = FormatSpec { + kind: "SharedRuntimeBlock", + envelope: EnvelopeRule::Exempt { + reason: "a shared runtime block read alone by its unit tests", + }, + removed_keys: &[], + }; + Reader::new("block.yaml") + .decode::(text.as_bytes(), &Expect::one(&BLOCK)) + .expect("the block decodes") + .value +} + +fn issuer(address: &str, allow_insecure_http: bool) -> OidcIssuerConfig { + read_block(&format!( + "issuer: {address}\naudience: api\nallowInsecureHttp: {allow_insecure_http}\n" + )) +} + +#[test] +fn a_loopback_http_issuer_needs_no_setting_and_a_remote_one_needs_the_development_flag() { + for loopback in [ + "http://127.0.0.1:8082", + "http://localhost:8082", + "http://[::1]:8082", + ] { + issuer(loopback, false) + .check("authentication.oidc") + .unwrap_or_else(|error| panic!("{loopback}: {error}")); + } + issuer("http://issuer.example.test", false) + .check("authentication.oidc") + .expect_err("remote plain http is refused without the flag"); + issuer("http://issuer.example.test", true) + .check("authentication.oidc") + .expect("the flag admits it; the posture decision refuses it in production"); + issuer("https://issuer.example.test", false) + .check("authentication.oidc") + .expect("https"); +} + +#[test] +fn the_check_without_a_posture_keeps_the_loopback_argument() { + let loopback = issuer("http://127.0.0.1:8082", false); + loopback + .check_without_posture("authentication.oidc", true) + .expect("admitted when asked"); + loopback + .check_without_posture("authentication.oidc", false) + .expect_err("refused when not asked"); +} + +// Database transport + +fn database(transport: Option<&str>, test_only_plaintext: bool) -> DatabaseConfig { + let mut text = String::from( + "runtimeUrlRef: secret:env/DB_RUNTIME\nmigrationUrlRef: secret:env/DB_MIGRATION\n", + ); + if let Some(transport) = transport { + text.push_str(&format!("transport: {transport}\n")); + } + if test_only_plaintext { + text.push_str("testOnlyPlaintext: true\n"); + } + read_block(&text) +} + +fn resolve(name: &str) -> std::io::Result> { + match name { + "db.internal" => Ok(vec![IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3))]), + "db.mixed" => Ok(vec![ + IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), + IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)), + ]), + "db.example.com" => Ok(vec![IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34))]), + _ => Err(std::io::Error::other("no such name")), + } +} + +fn tcp(host: &str) -> Vec { + vec![DatabaseHost::Tcp(host.to_owned())] +} + +#[test] +fn plaintext_permitted_answers_each_host_for_each_transport() { + use DatabaseTransport::{LoopbackPlaintext, PrivateNetworkPlaintext, VerifiedTls}; + let witness_holder = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)) + .parse_str::(&every_setting(), |_| None) + .unwrap(); + let witness = witness_holder.development.as_ref(); + + let hosts: Vec<(&str, Vec)> = vec![ + ("socket", vec![DatabaseHost::Unix]), + ("127.0.0.1", tcp("127.0.0.1")), + ("::1", tcp("::1")), + ("[::1]", tcp("[::1]")), + ("localhost", tcp("localhost")), + ("10.0.0.5", tcp("10.0.0.5")), + ("172.16.0.1", tcp("172.16.0.1")), + ("192.168.1.1", tcp("192.168.1.1")), + ("fd00::1", tcp("fd00::1")), + ("db.internal", tcp("db.internal")), + ("db.mixed", tcp("db.mixed")), + ("db.example.com", tcp("db.example.com")), + ("172.32.0.1", tcp("172.32.0.1")), + ("8.8.8.8", tcp("8.8.8.8")), + ("2001:db8::1", tcp("2001:db8::1")), + ("unresolvable", tcp("unresolvable")), + ]; + // (host, loopback-plaintext permits, private-network-plaintext permits) + let expected = [ + ("socket", true, true), + ("127.0.0.1", true, true), + ("::1", true, true), + ("[::1]", true, true), + ("localhost", true, true), + ("10.0.0.5", false, true), + ("172.16.0.1", false, true), + ("192.168.1.1", false, true), + ("fd00::1", false, true), + ("db.internal", false, true), + ("db.mixed", false, false), + ("db.example.com", false, false), + ("172.32.0.1", false, false), + ("8.8.8.8", false, false), + ("2001:db8::1", false, false), + ("unresolvable", false, false), + ]; + for ((name, hosts), (expected_name, loopback, private)) in hosts.iter().zip(expected) { + assert_eq!(*name, expected_name); + for (transport, permitted) in [ + ("loopback-plaintext", loopback), + ("private-network-plaintext", private), + ] { + let config = database(Some(transport), false); + let answer = plaintext_permitted_with(&config, hosts, witness, &resolve); + assert_eq!(answer.is_ok(), permitted, "{name} under {transport}"); + if !permitted { + assert!( + matches!(answer, Err(DatabaseTransportError::HostMismatch(_))), + "{name} under {transport}: {answer:?}" + ); + } + } + // `verified-tls`, written or omitted, takes every host. + for transport in [Some("verified-tls"), None] { + let config = database(transport, false); + assert_eq!( + plaintext_permitted_with(&config, hosts, witness, &resolve), + Ok(VerifiedTls), + "{name}" + ); + } + } + let config = database(Some("loopback-plaintext"), false); + assert_eq!( + plaintext_permitted_with(&config, &[DatabaseHost::Unix], None, &resolve), + Ok(LoopbackPlaintext) + ); + let config = database(Some("private-network-plaintext"), false); + assert_eq!( + plaintext_permitted_with(&config, &tcp("10.0.0.5"), witness, &resolve), + Ok(PrivateNetworkPlaintext) + ); +} + +#[test] +fn a_private_network_transport_is_unreadable_without_the_witness() { + let config = database(Some("private-network-plaintext"), false); + let answer = plaintext_permitted_with(&config, &tcp("10.0.0.5"), None, &resolve); + assert!( + matches!(answer, Err(DatabaseTransportError::DevelopmentOnly(_))), + "{answer:?}" + ); + assert_eq!( + answer.unwrap_err().code(), + "platform.posture.database-private-plaintext" + ); +} + +#[test] +fn a_transport_beside_test_only_plaintext_is_a_conflict_in_every_build() { + let both = database(Some("loopback-plaintext"), true); + for test_build in [false, true] { + assert_eq!( + both.check(test_build), + Err(DatabaseTransportError::Conflict), + "{test_build}" + ); + } + assert_eq!( + DatabaseTransportError::Conflict.code(), + "platform.database.transport-conflict" + ); +} + +#[test] +fn test_only_plaintext_is_refused_outside_test_builds() { + let config = database(None, true); + assert_eq!( + config.check(false), + Err(DatabaseTransportError::TestOnlyPlaintext) + ); + assert_eq!(config.check(true), Ok(())); + let error = DatabaseTransportError::TestOnlyPlaintext; + assert_eq!(error.code(), "platform.database.test-only-plaintext"); + assert_eq!( + error.to_string(), + "database.testOnlyPlaintext is accepted only by test builds" + ); + assert_eq!( + error.suggested_action(), + "Remove it, and set database.transport for a plaintext connection on the same host." + ); + assert_eq!(database(None, false).check(false), Ok(())); +} diff --git a/crates/registry-platform-config/src/posture_tests.rs b/crates/registry-platform-config/src/posture_tests.rs index 7fa3e205a3..aa5a787768 100644 --- a/crates/registry-platform-config/src/posture_tests.rs +++ b/crates/registry-platform-config/src/posture_tests.rs @@ -111,7 +111,7 @@ fn declared(posture: Posture) -> DeclaredPosture { fn load(body: &str) -> (Result<(), String>, Vec) { let text = format!("{HEAD}{body}"); let (result, found) = collect_development_settings(|| { - RuntimeConfigLoader::new(ENVELOPE).parse_str::(&text, |_| None) + RuntimeConfigLoader::new_without_posture(ENVELOPE).parse_str::(&text, |_| None) }); (result.map(|_| ()).map_err(|error| error.to_string()), found) } diff --git a/crates/registry-render/src/runtime.rs b/crates/registry-render/src/runtime.rs index 1230b00f7f..03f126e354 100644 --- a/crates/registry-render/src/runtime.rs +++ b/crates/registry-render/src/runtime.rs @@ -758,7 +758,7 @@ impl AuditRuntime { /// retired apiVersion. #[must_use] pub const fn runtime_loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RENDER_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(RENDER_RUNTIME_ENVELOPE) .removed_keys(RENDER_REMOVED_KEYS) .retired_api_versions(RETIRED_RUNTIME_API_VERSIONS) .require_trusted_ownership() @@ -1136,7 +1136,7 @@ fn findings( } match (&runtime.authentication.oidc, &runtime.authentication.api_key_ref) { (Some(oidc), None) => { - findings.extend([oidc.provider.check("authentication.oidc", true), oidc.clients.check("authentication.oidc")].iter().filter_map(|result| result.as_ref().err()).map(block_finding)); + findings.extend([oidc.provider.check_without_posture("authentication.oidc", true), oidc.clients.check("authentication.oidc")].iter().filter_map(|result| result.as_ref().err()).map(block_finding)); if let registry_platform_config::JwksSource::Static { document_ref } = &oidc.provider.jwks_source { if let Err(error) = runtime.secret_providers.check_reference("authentication.oidc.jwksSource.documentRef", document_ref) { findings.push(block_finding(&error)); } } diff --git a/crates/registry-scheduling/src/config.rs b/crates/registry-scheduling/src/config.rs index 868763eaea..56f57dd031 100644 --- a/crates/registry-scheduling/src/config.rs +++ b/crates/registry-scheduling/src/config.rs @@ -717,7 +717,7 @@ impl RuntimeConfig { /// removed keys, and retired apiVersions. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(SCHEDULING_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(SCHEDULING_RUNTIME_ENVELOPE) .removed_keys(SCHEDULING_REMOVED_KEYS) .retired_api_versions(SCHEDULING_RETIRED_RUNTIME_API_VERSIONS) .require_trusted_ownership() @@ -968,7 +968,7 @@ impl RuntimeConfig { fn check_oidc(&self, findings: &mut Vec) { let oidc = &self.authentication.oidc; - if let Err(error) = oidc.provider.check( + if let Err(error) = oidc.provider.check_without_posture( "authentication.oidc", self.listener.tls_termination == TlsTermination::DevelopmentLoopback, ) { diff --git a/crates/registry-scheduling/tests/postgres_commitments.rs b/crates/registry-scheduling/tests/postgres_commitments.rs index 6259488ad0..a9911a58ed 100644 --- a/crates/registry-scheduling/tests/postgres_commitments.rs +++ b/crates/registry-scheduling/tests/postgres_commitments.rs @@ -387,6 +387,7 @@ async fn fixture_publishing_with_hook_and_status( migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let migration_store = PostgresStore::connect_migration(&database, &secrets).expect("the migration store"); @@ -10102,6 +10103,7 @@ async fn refuses_a_pre_1_0_ledger_at_migrate_and_readiness(version: i64) { migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let store = PostgresStore::connect_migration(&database, &secrets).expect("the migration store"); diff --git a/products/adapter/schemas/runtime.v1alpha1.schema.json b/products/adapter/schemas/runtime.v1alpha1.schema.json index ffd2e7fa7b..c9a3ef65b3 100644 --- a/products/adapter/schemas/runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/runtime.v1alpha1.schema.json @@ -67,6 +67,13 @@ "default": false, "description": "Allow a plaintext connection. Refused outside test builds.", "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] } }, "required": [ @@ -75,6 +82,26 @@ ], "type": "object" }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, "EndpointBinding": { "additionalProperties": false, "description": "The environment binding of one pack endpoint: its base URL, its\ncredentials matching the endpoint's declared kind, and the optional TLS\nadditions.", @@ -305,8 +332,11 @@ "properties": { "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "audience": { "description": "The audience every accepted access token must carry in `aud`.", diff --git a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json index 1de24b21dc..7ecd14df72 100644 --- a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json @@ -53,6 +53,13 @@ "default": "file", "description": "Where audit lines go: `file` or `stdout`." }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -118,6 +125,21 @@ } ] }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "DetailsConfig": { "additionalProperties": false, "description": "The Record type holding the citizen's own record, found through the agent\nprofile's linked lookup.", diff --git a/products/breg/generated/review-runtime/review-runtime.schema.json b/products/breg/generated/review-runtime/review-runtime.schema.json index f4768ad0f2..14a3d68106 100644 --- a/products/breg/generated/review-runtime/review-runtime.schema.json +++ b/products/breg/generated/review-runtime/review-runtime.schema.json @@ -24,6 +24,13 @@ "default": "file", "description": "Where audit lines go: `file` or `stdout`." }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -89,6 +96,21 @@ } ] }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "EnvironmentSecretProviderConfig": { "additionalProperties": false, "description": "The environment secret provider. It takes no settings.", diff --git a/products/breg/generated/runtime/runtime.schema.json b/products/breg/generated/runtime/runtime.schema.json index 9263da931f..b6cc828e75 100644 --- a/products/breg/generated/runtime/runtime.schema.json +++ b/products/breg/generated/runtime/runtime.schema.json @@ -88,6 +88,21 @@ } ] }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "Cidr": { "description": "A private network range in `addr/prefix` form, for example 10.0.0.0/8.", "pattern": "^[0-9a-fA-F.:]+/[0-9]{1,3}$", @@ -120,6 +135,26 @@ } ] }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, "Digest": { "description": "A SHA-256 digest: `sha256:` followed by 64 lowercase hex digits.", "pattern": "^sha256:[0-9a-f]{64}$", @@ -992,6 +1027,13 @@ "default": "file", "description": "`file` (the default) writes a durable, rotated JSON Lines file at\n`path`; `stdout` writes one JSON line per entry to standard output." }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -1498,8 +1540,11 @@ }, "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "allowedAlgorithm": { "$ref": "#/$defs/AccessTokenAlgorithm" @@ -1744,6 +1789,13 @@ "default": false, "description": "Allow a plaintext connection. Refused outside test builds.", "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] } }, "required": [ diff --git a/products/casework/generated/runtime/runtime.schema.json b/products/casework/generated/runtime/runtime.schema.json index 7dfe7cc1a6..9175ae0e65 100644 --- a/products/casework/generated/runtime/runtime.schema.json +++ b/products/casework/generated/runtime/runtime.schema.json @@ -24,6 +24,13 @@ "default": "file", "description": "Where audit entries go: a rotated `file` (the default) or `stdout`." }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -89,6 +96,21 @@ } ] }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "AuthenticationConfig": { "additionalProperties": false, "properties": { @@ -174,6 +196,13 @@ "default": false, "description": "Allow a plaintext connection. Refused outside test builds.", "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] } }, "required": [ @@ -182,6 +211,26 @@ ], "type": "object" }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, "DelegatedDisplayExchangeBinding": { "additionalProperties": false, "description": "Dedicated per-call delegation for staff-subject source disclosure. This is\nseparate from the provider's status and task-context service credential.", @@ -458,8 +507,11 @@ "properties": { "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "allowedClients": { "$ref": "#/$defs/OidcAllowedClients", diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index ccabc57ffc..200f4b2b82 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -6,8 +6,11 @@ "properties": { "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "assertionIssuers": { "additionalProperties": { @@ -555,6 +558,13 @@ "default": false, "description": "Allow a plaintext connection. Refused outside test builds.", "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] } }, "required": [ @@ -563,6 +573,26 @@ ], "type": "object" }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, "DecisionAuthorization": { "description": "Explicit service identity. Local authorization is limited to numeric loopback.", "oneOf": [ diff --git a/products/documents/generated/runtime/runtime.schema.json b/products/documents/generated/runtime/runtime.schema.json index c4e2131757..7933501e9e 100644 --- a/products/documents/generated/runtime/runtime.schema.json +++ b/products/documents/generated/runtime/runtime.schema.json @@ -9,6 +9,13 @@ "default": "file", "description": "Where audit entries go: a rotated `file` (the default) or `stdout`." }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -53,6 +60,21 @@ } ] }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "AuthenticationConfig": { "additionalProperties": false, "properties": { @@ -156,6 +178,13 @@ "default": false, "description": "Allow a plaintext connection. Refused outside test builds.", "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] } }, "required": [ @@ -164,6 +193,26 @@ ], "type": "object" }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, "DestinationsConfig": { "additionalProperties": false, "description": "Where the project's hooks deliver, by destination id.", @@ -320,8 +369,11 @@ "properties": { "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "allowedClients": { "description": "The clients whose access tokens are admitted. Required in every\nfile: `from-package` admits the requester clients of the package's access\nprofiles, and a list of at least one distinct client must cover them. An\nomitted or empty list, an empty or repeated client, and `unrestricted` are\nrefused.", diff --git a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json index 5290f38fc4..d3c56f7926 100644 --- a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json +++ b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json @@ -32,6 +32,13 @@ "$ref": "#/$defs/AuditDestinationKind", "default": "file" }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -58,6 +65,21 @@ ], "type": "object" }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "ClaimNamesDocument": { "additionalProperties": false, "description": "The contextual claim names an offer-token issuer uses. Each is distinct,\nand none is a registered or authentication claim.", diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index b3082762a7..06758de8d5 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -29,8 +29,11 @@ }, "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "audience": { "description": "The audience every accepted access token must carry in `aud`.", @@ -92,6 +95,13 @@ "$ref": "#/$defs/AuditDestinationKind", "default": "file" }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -118,6 +128,21 @@ ], "type": "object" }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "ClaimQueryDocument": { "additionalProperties": false, "description": "One claim a credential query asks for.", @@ -330,8 +355,11 @@ }, "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "allowedClient": { "$ref": "#/$defs/ExternalId", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 6410934589..f3541c440c 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -4896,7 +4896,7 @@ }, "artifact": { "path": "products/adapter/schemas/runtime.v1alpha1.schema.json", - "sha256": "e488b0c50b714031f9505241b6a5c9cb15b9f50e823ef68e6a18fb343353380c", + "sha256": "de83cc5d1e6fd93c2a3f624ba02a44e7f8eaf08d2a48ec8ca8ad25aa1baae5f6", "mediaType": "application/schema+json" } }, @@ -5112,7 +5112,7 @@ }, "artifact": { "path": "products/breg/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "f760f95858307c972c65cda16b659021c608afefff75854c25bafdb975d9505b", + "sha256": "4a9161e749da012552829c6c6e1f58a365d457fd30db7bca4a4f6342e4af9318", "mediaType": "application/schema+json" } }, @@ -5256,7 +5256,7 @@ }, "artifact": { "path": "products/breg/generated/review-runtime/review-runtime.schema.json", - "sha256": "1c547522ee09c598590eaa302615aaabb5e5628516f85f2f5558989af25210b1", + "sha256": "4b912d75812d2ae988192dd50ca4ce54e9c72da2ba9e62b614aeff188b1cae92", "mediaType": "application/schema+json" } }, @@ -5292,7 +5292,7 @@ }, "artifact": { "path": "products/breg/generated/runtime/runtime.schema.json", - "sha256": "4a02526d00324efad59aca20e47c48401af4e281930d651e10c22ae570d63b96", + "sha256": "2e1a00a54542705141801fef4112443d715fdbde6842e2684fa801a3f5388392", "mediaType": "application/schema+json" } }, @@ -5400,7 +5400,7 @@ }, "artifact": { "path": "products/casework/generated/runtime/runtime.schema.json", - "sha256": "ac880ee5cadd7b3bf63acb087fba76bd2bf83136a468e05036470e6e08ed529f", + "sha256": "035b9d0040bf61f7bfff4f8827547e711b05bdafe2b5da4561f73db46dbf85c1", "mediaType": "application/schema+json" } }, @@ -5432,11 +5432,11 @@ "description": "Registry Coordinator runtime configuration JSON Schema.", "source": { "path": "crates/registry-coordinator/src/runtime.rs", - "sha256": "5a9e84b169d847669e97d8d53073ddbb98928c92470ee167f9020df98120fd6b" + "sha256": "c6718ea853224e33df0d64a1ad65a8a4b4acd317e53c59089f0c89d95130e844" }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", - "sha256": "6597f692f6eec4c68b186613eaae85ca5d99d8d87985a2653dafa7613f8596c6", + "sha256": "a6da5b7691382e9e412b9e67233228d6c18bf76a44cad0fd75c3b1dbbdae7429", "mediaType": "application/schema+json" } }, @@ -5616,7 +5616,7 @@ }, "artifact": { "path": "products/documents/generated/runtime/runtime.schema.json", - "sha256": "c132d0dea03c4d33a9387b5e0ddfb5b9dc7b6384287c7133e3c06d51114716ce", + "sha256": "1207d9ae54688fbc9b2cf69a75baed8008b0eedb0bfd8c7722629726e43016bc", "mediaType": "application/schema+json" } }, @@ -5778,7 +5778,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json", - "sha256": "4412d9e39955ffbb3d89e1c5fba790b5519ffb57861a1292ef14e95500808e04", + "sha256": "17c5085d53455e203add38e01b2eed330ec53b03bd0e242126b15ad2a58ffd79", "mediaType": "application/schema+json" } }, @@ -5796,7 +5796,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "933ad51331aaf9586f238fbc8bb5f0171ea09fa0f61052e71c36e685e5b521a9", + "sha256": "6efae3b628362ddeb7c9e470cb7ee9c0dcd9b61431580836cf873d45c21b75dd", "mediaType": "application/schema+json" } }, @@ -6012,7 +6012,7 @@ }, "artifact": { "path": "products/messaging/generated/runtime/runtime.schema.json", - "sha256": "daa1af1db5b235398feaa98417f8cf682a60703557065df61552d0579d97819a", + "sha256": "6d75d4e0abeeae4b5b6dfbec8d6fdc6576199654ff5f8b4720dea634230ee241", "mediaType": "application/schema+json" } }, @@ -6156,7 +6156,7 @@ }, "artifact": { "path": "products/platform/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "663f3c356b9df64ae410244797eac2abb488fa3ca87454f21c9618aab4fc0817", + "sha256": "2a4c006f8666d8ec3f9d1a9a511041525753ffa97526f4275ce22a64ca0c4531", "mediaType": "application/schema+json" } }, @@ -6264,7 +6264,7 @@ }, "artifact": { "path": "products/render/schemas/runtime.schema.json", - "sha256": "8db0c75502d68d1a6ecfffdf1ffce77136df2f87a832d5829b2bf14afa65ead3", + "sha256": "dbf6eb70c49c15e54ad435adc77446eebbe2a1dbd16f2eb707465c6bc89effd6", "mediaType": "application/schema+json" } }, @@ -6372,7 +6372,7 @@ }, "artifact": { "path": "products/scheduling/generated/runtime/runtime.schema.json", - "sha256": "9f7a0846f8fb02c785b0663f3d96cc473b32a2c47d2fbc6dd21f6354faa9d58a", + "sha256": "319d14d8c66ea2eee3d77577d0b8924478b4b5e86893dce390533298cd9910d1", "mediaType": "application/schema+json" } }, diff --git a/products/messaging/generated/runtime/runtime.schema.json b/products/messaging/generated/runtime/runtime.schema.json index 3f0255e36b..152461c5cc 100644 --- a/products/messaging/generated/runtime/runtime.schema.json +++ b/products/messaging/generated/runtime/runtime.schema.json @@ -9,6 +9,13 @@ "default": "file", "description": "Where audit entries go: a rotated `file` (the default) or `stdout`." }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -53,6 +60,21 @@ } ] }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "AuthenticationConfig": { "additionalProperties": false, "properties": { @@ -186,6 +208,13 @@ "default": false, "description": "Allow a plaintext connection. Refused outside test builds.", "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] } }, "required": [ @@ -194,6 +223,26 @@ ], "type": "object" }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, "Digest": { "description": "A SHA-256 digest: `sha256:` followed by 64 lowercase hex digits.", "pattern": "^sha256:[0-9a-f]{64}$", @@ -517,8 +566,11 @@ "properties": { "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "allowedClients": { "description": "The clients whose access tokens are admitted. Required in every\nfile: `from-package` admits the requester clients of the package's access\nprofiles, and a list of at least one distinct client must cover them. An\nomitted or empty list, an empty or repeated client, and `unrestricted` are\nrefused.", diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 0952025849..b077744520 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -35,6 +35,33 @@ diagnostic: one that names a posture code is refused with `config.check-acceptance-not-acceptable`. No runtime uses the gate yet. +- BREAKING (Rust API): `RuntimeConfigLoader::new` takes the + `DeclaredPosture`. In production it refuses every development-only setting + the file holds, listed beside any other problem in the file, and in + development it admits them, and `LoadedRuntimeConfig` carries the + `PostureReport` and, in development only, the `DevelopmentWitness`. + `check_offline` reports each such setting as an error in production and a + warning in development, under the same code, and still decodes the file. + Migration: call `RuntimeConfigLoader::new_without_posture(envelope)`, which + behaves as `new` did, until the runtime adopts the posture; add + `transport: None` to a `DatabaseConfig` literal; and call + `OidcIssuerConfig::check_without_posture(field, allow_loopback_http)` where + `check` was called. + +- The shared database block adds `database.transport`: `verified-tls`, the + default, `loopback-plaintext`, for a Unix socket, a numeric loopback + address or `localhost`, and `private-network-plaintext`, development only, + for loopback or private addresses. `DatabaseConfig::plaintext_permitted` + checks the hosts against the value, and `DatabaseConfig::check` refuses + `transport` beside `testOnlyPlaintext`, and `testOnlyPlaintext` outside a + test build. The shared audit block adds `audit.hashKeyCustody`: + `operator-provisioned`, the default, or `development-generated`, + development only. `authentication.oidc.allowInsecureHttp: true` is + recorded as a development-only setting. The shared and product runtime + schemas mark these members `x-registry-development-only`. No runtime reads + the new members yet, and a runtime that has not adopted the posture + behaves as before. + - `registry-cli-report` adds `Report::with_posture`, which writes `posture.value` and `posture.source` (`flag`, `environment` or `default`) into a CLI report body after the command members. A report built without it diff --git a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json index f8086a2e14..8f1cdc5b7c 100644 --- a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json @@ -77,6 +77,13 @@ "default": "file", "description": "Where audit lines go: `file` or `stdout`." }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -142,6 +149,21 @@ } ] }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "Binding": { "additionalProperties": false, "properties": { diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index 3f0bff16bf..f4238f38f8 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -38,6 +38,13 @@ "additionalProperties": false, "description": "The key for the keyed references an audit record carries in place of raw\nidentifiers, written `audit.hashKeyRef` beside the product's own audit\nsettings.", "properties": { + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -48,6 +55,21 @@ ], "type": "object" }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "DatabaseConfig": { "additionalProperties": false, "description": "The PostgreSQL connection a stateful runtime uses. Both URLs are secret\nreferences and may name the same secret.", @@ -68,6 +90,13 @@ "default": false, "description": "Allow a plaintext connection. Refused outside test builds.", "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] } }, "required": [ @@ -76,6 +105,26 @@ ], "type": "object" }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, "Digest": { "description": "A SHA-256 digest: `sha256:` followed by 64 lowercase hex digits.", "pattern": "^sha256:[0-9a-f]{64}$", @@ -323,8 +372,11 @@ "properties": { "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "audience": { "description": "The audience every accepted access token must carry in `aud`.", diff --git a/products/platform/scripts/check-config-conformance.py b/products/platform/scripts/check-config-conformance.py index b814d3d623..435165ae7b 100755 --- a/products/platform/scripts/check-config-conformance.py +++ b/products/platform/scripts/check-config-conformance.py @@ -56,7 +56,7 @@ ) GENERATOR_COMMAND = " ".join((*GENERATOR_ARGUMENTS, GENERATOR_OUTPUT)) LEGACY_EXPANSION = re.compile(r"\bexpand_config_env_vars\w*\b") -LOADER_USE = re.compile(r"\bRuntimeConfigLoader\s*::\s*new\s*\(") +LOADER_USE = re.compile(r"\bRuntimeConfigLoader\s*::\s*new(?:_without_posture)?\s*\(") PLATFORM_CRATE = "registry_platform_config" # Keywords a hand-written copy of a shared block may add: each one only # describes or narrows what the canonical block accepts. diff --git a/products/render/schemas/runtime.schema.json b/products/render/schemas/runtime.schema.json index 13c41fbe66..bcc483eb62 100644 --- a/products/render/schemas/runtime.schema.json +++ b/products/render/schemas/runtime.schema.json @@ -360,8 +360,11 @@ "properties": { "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "allowedClients": { "$ref": "#/$defs/OidcAllowedClients", diff --git a/products/scheduling/generated/runtime/runtime.schema.json b/products/scheduling/generated/runtime/runtime.schema.json index 3ff24dc620..fdbfcc1afe 100644 --- a/products/scheduling/generated/runtime/runtime.schema.json +++ b/products/scheduling/generated/runtime/runtime.schema.json @@ -24,6 +24,13 @@ "default": "file", "description": "Where audit entries go: a rotated `file` (the default) or `stdout`." }, + "hashKeyCustody": { + "$ref": "#/$defs/AuditKeyCustody", + "description": "Who provisioned the key. Absent means `operator-provisioned`.\n`development-generated` marks a key a development tool made.", + "x-registry-development-only": [ + "platform.posture.generated-audit-key" + ] + }, "hashKeyRef": { "$ref": "#/$defs/SecretReference", "description": "Secret reference to the audit hash key." @@ -89,6 +96,21 @@ } ] }, + "AuditKeyCustody": { + "description": "Who provisioned the audit hash key.", + "oneOf": [ + { + "const": "operator-provisioned", + "description": "The operator provisioned the key.", + "type": "string" + }, + { + "const": "development-generated", + "description": "A development tool generated the key.", + "type": "string" + } + ] + }, "AuthenticationConfig": { "additionalProperties": false, "properties": { @@ -185,6 +207,13 @@ "default": false, "description": "Allow a plaintext connection. Refused outside test builds.", "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] } }, "required": [ @@ -193,6 +222,26 @@ ], "type": "object" }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, "DestinationsConfig": { "additionalProperties": false, "description": "Where due reminder and lifecycle-hook intents are dispatched. An absent\nreminders destination and an empty hook map are supported: intents stay\nlocal, so an operator can adopt the product before wiring delivery buses.", @@ -344,8 +393,11 @@ "properties": { "allowInsecureHttp": { "default": false, - "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. TLS remains required unless the\noperator explicitly accepts this transport risk.", - "type": "boolean" + "description": "Permit plain HTTP beyond loopback to the configured issuer and to a\nJWKS URI declared in configuration. Loopback needs no setting. The\nvalue `true` is a development-only setting: the loader records it, and\nproduction refuses it.", + "type": "boolean", + "x-registry-development-only": [ + "platform.posture.insecure-issuer-http" + ] }, "allowedClients": { "description": "Client identifiers whose access tokens are admitted. Required in every\nfile; an omitted or empty list, a repeated client, and `unrestricted`\nare refused.", From be809db357714b69cb9ffc7b67c3c2349178d63c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:10:41 +0100 Subject: [PATCH 049/136] feat(platform): let a scope refusal line name the declared scope `record_refusal!` takes an optional `DeclaredScope`: the scope claim name, the scope the operation needs and the access profile id, all from configuration or the reviewed package. The line carries them only for a `scope` refusal, each cut to 128 bytes. Nothing from the caller's token reaches the line, and the existing macro forms are unchanged. Signed-off-by: Jeremi Joslin --- .../registry-platform-authcommon/src/lib.rs | 5 +- .../src/refusal.rs | 198 +++++++++++++++++- products/platform/CHANGELOG.md | 9 + 3 files changed, 205 insertions(+), 7 deletions(-) diff --git a/crates/registry-platform-authcommon/src/lib.rs b/crates/registry-platform-authcommon/src/lib.rs index 5d8b5b516e..ec05f4df45 100644 --- a/crates/registry-platform-authcommon/src/lib.rs +++ b/crates/registry-platform-authcommon/src/lib.rs @@ -6,11 +6,12 @@ pub mod refusal; #[doc(hidden)] pub use refusal::__refusal_trace_id_seal; -pub use refusal::{FailedCheck, RefusalTraceId}; #[cfg(feature = "refusal-recorder")] pub use refusal::{ - RefusalLine, RefusalNote, RefusalRecorder, REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, + DeclaredScope, RefusalLine, RefusalNote, RefusalRecorder, DECLARED_VALUE_MAX_BYTES, + REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, }; +pub use refusal::{FailedCheck, RefusalTraceId}; #[cfg(feature = "refusal-recorder")] pub use tracing as __tracing; diff --git a/crates/registry-platform-authcommon/src/refusal.rs b/crates/registry-platform-authcommon/src/refusal.rs index 9e1f05c2d3..2320909947 100644 --- a/crates/registry-platform-authcommon/src/refusal.rs +++ b/crates/registry-platform-authcommon/src/refusal.rs @@ -147,18 +147,92 @@ pub mod __refusal_trace_id_seal { #[cfg(feature = "refusal-recorder")] pub use recorder::{ - RefusalLine, RefusalNote, RefusalRecorder, REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, + DeclaredScope, RefusalLine, RefusalNote, RefusalRecorder, DECLARED_VALUE_MAX_BYTES, + REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, }; #[cfg(feature = "refusal-recorder")] mod recorder { - use std::sync::{Mutex, PoisonError}; + use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, Instant}; use registry_platform_metrics::{CounterVec, LabelSpace, MetricsError}; use super::FailedCheck; + /// The most bytes one declared value contributes to a refusal line. + pub const DECLARED_VALUE_MAX_BYTES: usize = 128; + + /// Values the operator declared that a scope refusal line may name: the + /// name of the claim that carries scopes, the scope the operation needs, + /// and the access profile that was applied. + /// + /// Each value comes from the runtime configuration or the reviewed + /// package, never from the caller's token. The recording layer passes it + /// to [`record_refusal!`](crate::record_refusal) beside the note, and the + /// line carries it only when the failed check is + /// [`FailedCheck::Scope`]. A product attaches it to the refusal answer's + /// extensions, which are never written to the response. + #[derive(Clone, Debug, PartialEq, Eq)] + pub struct DeclaredScope { + scope_claim: Arc, + required_scope: Option>, + access_profile: Option>, + } + + impl DeclaredScope { + /// `scope_claim` is the claim name the deployment configured, for + /// example `authentication.oidc.scopeClaim`. + pub fn new(scope_claim: impl AsRef) -> Self { + Self { + scope_claim: bounded(scope_claim.as_ref()), + required_scope: None, + access_profile: None, + } + } + + /// The scope the operation needs, as the configuration or package + /// declares it. + #[must_use] + pub fn with_required_scope(self, scope: impl AsRef) -> Self { + Self { + required_scope: Some(bounded(scope.as_ref())), + ..self + } + } + + /// The identifier of the access profile the configuration applied. + #[must_use] + pub fn with_access_profile(self, profile: impl AsRef) -> Self { + Self { + access_profile: Some(bounded(profile.as_ref())), + ..self + } + } + + pub fn scope_claim(&self) -> &str { + &self.scope_claim + } + + pub fn required_scope(&self) -> Option<&str> { + self.required_scope.as_deref() + } + + pub fn access_profile(&self) -> Option<&str> { + self.access_profile.as_deref() + } + } + + /// Cut a value to [`DECLARED_VALUE_MAX_BYTES`] on a character boundary. + /// The log formatter escapes what remains, so a value stays on one line. + fn bounded(value: &str) -> Arc { + let mut end = value.len().min(DECLARED_VALUE_MAX_BYTES); + while !value.is_char_boundary(end) { + end -= 1; + } + Arc::from(&value[..end]) + } + /// The length of one log window for one check. pub const REFUSAL_LOG_WINDOW: Duration = Duration::from_secs(60); /// The most lines one check may write in one window. @@ -322,19 +396,33 @@ mod recorder { /// every span that encloses the event. Do not call this macro inside a /// span that records request values (a URI, query, header, client id or /// subject), or those values reach the refusal line through the span. + /// + /// A scope refusal may also pass `declared = Some(&scope)`, a + /// [`DeclaredScope`](crate::DeclaredScope) built from configuration. The + /// line then carries `scope_claim`, and `required_scope` and + /// `access_profile` when they were declared. They are written only when + /// the note's check is [`FailedCheck::Scope`](crate::FailedCheck::Scope). #[macro_export] macro_rules! record_refusal { - (@write $recorder:expr, $note:expr, $trace_id:expr) => {{ + (@write $recorder:expr, $note:expr, $trace_id:expr, $declared:expr) => {{ let note: $crate::RefusalNote = $note; let trace_id: ::core::option::Option<&dyn $crate::RefusalTraceId> = $trace_id; + let declared: ::core::option::Option<&$crate::DeclaredScope> = $declared; if let Some(line) = $recorder.record(note.check) { let trace_id = trace_id.map($crate::__tracing::field::display); + let declared = declared.filter(|_| note.check == $crate::FailedCheck::Scope); + let scope_claim = declared.map($crate::DeclaredScope::scope_claim); + let required_scope = declared.and_then($crate::DeclaredScope::required_scope); + let access_profile = declared.and_then($crate::DeclaredScope::access_profile); match note.remedy { Some(remedy) => $crate::__tracing::info!( decision = "refused", failed_check = line.failed_check, suppressed = line.suppressed, remedy, + scope_claim, + required_scope, + access_profile, trace_id, "request refused" ), @@ -342,6 +430,9 @@ mod recorder { decision = "refused", failed_check = line.failed_check, suppressed = line.suppressed, + scope_claim, + required_scope, + access_profile, trace_id, "request refused" ), @@ -349,11 +440,24 @@ mod recorder { } }}; ($recorder:expr, $note:expr) => { - $crate::record_refusal!(@write $recorder, $note, ::core::option::Option::None) + $crate::record_refusal!( + @write $recorder, $note, ::core::option::Option::None, ::core::option::Option::None + ) + }; + ($recorder:expr, $note:expr, declared = $declared:expr) => { + $crate::record_refusal!(@write $recorder, $note, ::core::option::Option::None, $declared) }; ($recorder:expr, $note:expr, trace_id = $trace_id:expr) => {{ let typed: &dyn $crate::RefusalTraceId = &$trace_id; - $crate::record_refusal!(@write $recorder, $note, ::core::option::Option::Some(typed)) + $crate::record_refusal!( + @write $recorder, $note, ::core::option::Option::Some(typed), ::core::option::Option::None + ) + }}; + ($recorder:expr, $note:expr, trace_id = $trace_id:expr, declared = $declared:expr) => {{ + let typed: &dyn $crate::RefusalTraceId = &$trace_id; + $crate::record_refusal!( + @write $recorder, $note, ::core::option::Option::Some(typed), $declared + ) }}; } } @@ -672,6 +776,90 @@ mod recorder_tests { assert!(output.contains("trace_id=0af7651916cd43dd8448eb211c80319c")); } + #[test] + fn a_scope_refusal_names_the_declared_scope_and_no_token_value() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let token_scope = "canary-token-scope-9c1e"; + let declared = DeclaredScope::new("scope") + .with_required_scope("registry.read") + .with_access_profile("caseworker"); + let output = captured(|| { + let _ = token_scope; + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + trace_id = ServerTraceId("4bf92f3577b34da6a3ce929d0e0e4736"), + declared = Some(&declared) + ); + }); + assert_eq!(output.lines().count(), 1, "{output}"); + assert!(output.contains("failed_check=\"scope\""), "{output}"); + assert!(output.contains("scope_claim=\"scope\""), "{output}"); + assert!( + output.contains("required_scope=\"registry.read\""), + "{output}" + ); + assert!(output.contains("access_profile=\"caseworker\""), "{output}"); + assert!(output.contains("trace_id=4bf92f3577b34da6a3ce929d0e0e4736")); + assert!(!output.contains("canary"), "{output}"); + + // Only the members that were declared are written. + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope).with_remedy("check scopeClaim"), + declared = Some(&DeclaredScope::new("scp")) + ); + }); + assert!(output.contains("scope_claim=\"scp\""), "{output}"); + assert!(output.contains("remedy=\"check scopeClaim\""), "{output}"); + assert!(!output.contains("required_scope"), "{output}"); + assert!(!output.contains("access_profile"), "{output}"); + } + + #[test] + fn declared_scope_values_are_written_only_for_a_scope_refusal() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let declared = DeclaredScope::new("scope").with_required_scope("registry.read"); + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::TokenAudience), + declared = Some(&declared) + ); + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + declared = None + ); + }); + assert_eq!(output.lines().count(), 2, "{output}"); + assert!(!output.contains("scope_claim"), "{output}"); + assert!(!output.contains("required_scope"), "{output}"); + } + + #[test] + fn a_declared_value_is_bounded_and_kept_on_one_line() { + let long = "s".repeat(DECLARED_VALUE_MAX_BYTES + 50); + let declared = DeclaredScope::new(long.as_str()) + .with_required_scope("é".repeat(DECLARED_VALUE_MAX_BYTES)) + .with_access_profile("line\nbreak"); + assert_eq!(declared.scope_claim().len(), DECLARED_VALUE_MAX_BYTES); + let required = declared.required_scope().unwrap(); + assert!(required.len() <= DECLARED_VALUE_MAX_BYTES); + assert!(required.chars().all(|c| c == 'é')); + + let recorder = RefusalRecorder::new("breg").unwrap(); + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + declared = Some(&declared) + ); + }); + assert_eq!(output.lines().count(), 1, "{output}"); + } + #[test] fn the_macro_is_bounded() { let recorder = RefusalRecorder::new("breg").unwrap(); diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index b077744520..ae63661b9c 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -158,6 +158,15 @@ feature, and authcommon does not depend on httpsec. Alert on the counter, not on the log line. +- A scope refusal's `request refused` line can name what the operator + declared: `record_refusal!(.., declared = Some(&scope))` takes a + `registry_platform_authcommon::DeclaredScope` and writes `scope_claim`, and + `required_scope` and `access_profile` when they were declared. The values + come from the runtime configuration or the reviewed package, never from the + caller's token, and the line carries them only when the failed check is + `scope`. Each value is cut to 128 bytes. Products attach it to the refusal + answer's extensions, which are never written to the response. + - A token whose header `alg` does not fit the key its `kid` names, or whose `kid` names an encryption key such as an RSA-OAEP `use: enc` key, now fails as `OidcError::AlgorithmNotAllowed` (`token-algorithm`) instead of From a9b09ad8070cc17d757fca857fe4d3729b8d818a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:21:03 +0100 Subject: [PATCH 050/136] fix(evidence): classify bearer headers and name declared scope on refusals Evidence counts an Authorization header naming another scheme under credential-missing, and a header that is only the start of Bearer under credential-malformed. Evidence OID4VCI counts an unreadable header, or Bearer with no token, under credential-malformed. OID4VCI and OID4VP build every 401 and 403 with its failed check, and a debug build catches one built without. When the failed check is scope, the request refused line of Evidence, OID4VCI and OID4VP names the configured scope claim and required scopes. Nothing the caller's token carried is written, and no answer changes. Signed-off-by: Jeremi Joslin --- crates/registry-evidence-client/src/client.rs | 2 + .../registry-evidence-client/src/profile.rs | 2 + .../src/profile_file.rs | 2 + .../src/authorizer.rs | 42 +++- .../registry-evidence-oid4vci/src/config.rs | 3 +- .../src/observability.rs | 17 +- .../registry-evidence-oid4vci/src/service.rs | 228 ++++++++++++++++-- .../src/service/draft13.rs | 8 +- crates/registry-evidence-oid4vp/src/auth.rs | 15 +- .../registry-evidence-oid4vp/src/service.rs | 87 ++++++- .../tests/refusal_recording.rs | 11 + crates/registry-evidence/src/auth.rs | 30 ++- crates/registry-evidence/src/observability.rs | 18 +- .../src/refusal_recording_tests.rs | 46 ++++ crates/registry-evidence/src/runtime.rs | 17 +- crates/registry-evidence/src/runtime_tests.rs | 6 +- crates/registry-evidence/src/server.rs | 30 ++- crates/registry-evidencectl/src/client.rs | 3 + products/evidence/CHANGELOG.md | 11 + 19 files changed, 526 insertions(+), 52 deletions(-) diff --git a/crates/registry-evidence-client/src/client.rs b/crates/registry-evidence-client/src/client.rs index a968e9d5ca..5c0023043a 100644 --- a/crates/registry-evidence-client/src/client.rs +++ b/crates/registry-evidence-client/src/client.rs @@ -1695,6 +1695,8 @@ fn authorization_server_metadata_is_compatible( } fn validate_metadata_url(url: &Url, trust: &TrustProfile) -> Result<(), EvidenceClientError> { + // Exactly `127.0.0.1`, the address a supervised development service binds, + // so metadata the service publishes cannot name another local listener. let exact_local_loopback = url.scheme() == "http" && url.host_str() == Some("127.0.0.1") && url.port().is_some_and(|port| port != 0); diff --git a/crates/registry-evidence-client/src/profile.rs b/crates/registry-evidence-client/src/profile.rs index 7052506477..fd94fefbad 100644 --- a/crates/registry-evidence-client/src/profile.rs +++ b/crates/registry-evidence-client/src/profile.rs @@ -152,6 +152,8 @@ impl EvidenceClientProfile { return Err(profile_error()); } let origin_only = self.base_url == base_url.origin().ascii_serialization(); + // Exactly `127.0.0.1`, the address a supervised development service + // binds, so a profile names the origin it will reach. let local_loopback = base_url.scheme() == "http" && base_url.host_str() == Some("127.0.0.1") && base_url.port().is_some_and(|port| port != 0); diff --git a/crates/registry-evidence-client/src/profile_file.rs b/crates/registry-evidence-client/src/profile_file.rs index d3f797b14a..0af699ade9 100644 --- a/crates/registry-evidence-client/src/profile_file.rs +++ b/crates/registry-evidence-client/src/profile_file.rs @@ -295,6 +295,8 @@ impl ProfileDocument { } match self.trust { Some(TrustMember::LocalLoopbackDiscovery {}) => { + // Exactly `127.0.0.1`, the address a supervised development + // service binds, so a profile names the origin it will reach. let loopback = parsed.scheme() == "http" && parsed.host_str() == Some("127.0.0.1") && parsed.port().is_some_and(|port| port != 0); diff --git a/crates/registry-evidence-oid4vci/src/authorizer.rs b/crates/registry-evidence-oid4vci/src/authorizer.rs index 8f13472049..afbd0e64a1 100644 --- a/crates/registry-evidence-oid4vci/src/authorizer.rs +++ b/crates/registry-evidence-oid4vci/src/authorizer.rs @@ -18,7 +18,7 @@ use std::{collections::HashSet, sync::Arc, time::Duration}; use async_trait::async_trait; -use registry_platform_authcommon::FailedCheck; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ grant_claims, ClaimNames, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcError, @@ -29,6 +29,9 @@ use crate::config::{OfferAuthorizationConfig, ValidationMode}; /// The access-token types this service accepts, which are the two spellings /// RFC 9068 permits for a JWT access token. +/// The claim the platform verifier reads scopes from unless configured. +const DEFAULT_SCOPE_CLAIM: &str = "scope"; + const ACCESS_TOKEN_TYPES: [&str; 2] = ["at+jwt", "application/at+jwt"]; /// What a verified offer token established. @@ -77,6 +80,12 @@ impl AuthorizationError { #[async_trait] pub trait OfferAuthorizer: Send + Sync { async fn authorize(&self, credential: &str) -> Result; + + /// What a scope refusal may say about the deployment, when the authorizer + /// has a scope gate. Both values are configured, never read from a token. + fn declared_scope(&self) -> Option { + None + } } /// The configured issuer's access-token verifier. @@ -88,6 +97,8 @@ pub struct MintResourceServer { /// token's scope set after verification, with the same closed refusal a /// refused client gets, before any offer is stored or Evidence contacted. required_scopes: Vec, + /// The claim the verifier reads scopes from. + scope_claim: String, } impl MintResourceServer { @@ -107,9 +118,12 @@ impl MintResourceServer { fetch_url_policy(config, mode), )); let required_scopes = config.required_scopes.items().to_vec(); + let profile = verifier_profile(config); + let scope_claim = profile.scope_claim.clone(); Self { - verifier: Arc::new(TokenVerifier::new(verifier_profile(config), fetcher)), + verifier: Arc::new(TokenVerifier::new(profile, fetcher)), required_scopes, + scope_claim, claims: config.claims.clone(), } } @@ -122,6 +136,7 @@ impl MintResourceServer { Self { verifier, required_scopes: Vec::new(), + scope_claim: DEFAULT_SCOPE_CLAIM.to_owned(), claims: ClaimNames::default(), } } @@ -192,6 +207,13 @@ fn fetch_url_policy(config: &OfferAuthorizationConfig, mode: ValidationMode) -> #[async_trait] impl OfferAuthorizer for MintResourceServer { + fn declared_scope(&self) -> Option { + (!self.required_scopes.is_empty()).then(|| { + DeclaredScope::new(&self.scope_claim) + .with_required_scope(self.required_scopes.join(" ")) + }) + } + async fn authorize(&self, credential: &str) -> Result { if credential.is_empty() { return Err(AuthorizationError::Missing); @@ -315,6 +337,22 @@ mod tests { assert_eq!(server.authorize("").await, Err(AuthorizationError::Missing)); } + #[test] + fn the_declared_scope_is_the_configured_claim_and_scopes() { + let mut config = valid_config(); + config.offers.required_scopes = + crate::config::Restriction::Listed(vec!["offers:create".to_owned()]); + let server = MintResourceServer::from_config(&config.offers, config.validation_mode); + let declared = server.declared_scope().expect("a scope gate is declared"); + assert_eq!(declared.scope_claim(), "scope"); + assert_eq!(declared.required_scope(), Some("offers:create")); + assert_eq!(declared.access_profile(), None); + + config.offers.required_scopes = crate::config::Restriction::Unrestricted; + let server = MintResourceServer::from_config(&config.offers, config.validation_mode); + assert_eq!(server.declared_scope(), None); + } + #[test] fn the_resource_server_is_built_from_the_offer_document_alone() { // The construction takes the offer boundary and the validation mode. diff --git a/crates/registry-evidence-oid4vci/src/config.rs b/crates/registry-evidence-oid4vci/src/config.rs index 00b09941b3..5860b1a52a 100644 --- a/crates/registry-evidence-oid4vci/src/config.rs +++ b/crates/registry-evidence-oid4vci/src/config.rs @@ -1643,7 +1643,8 @@ fn credential_issuer_findings(issuer: &str, findings: &mut Vec) { } } -/// Accept a plain loopback HTTP endpoint, with an optional path and nothing +/// Accept a plain HTTP endpoint on exactly `127.0.0.1`, the address a +/// supervised development service binds, with an optional path and nothing /// else that could vary between what is configured and what is reached. fn is_supervised_local_endpoint(origin: &Url) -> bool { let url = origin.to_url(); diff --git a/crates/registry-evidence-oid4vci/src/observability.rs b/crates/registry-evidence-oid4vci/src/observability.rs index fa56a46693..76cfa74032 100644 --- a/crates/registry-evidence-oid4vci/src/observability.rs +++ b/crates/registry-evidence-oid4vci/src/observability.rs @@ -23,7 +23,7 @@ use axum::{ Router, }; -use registry_platform_authcommon::{RefusalNote, RefusalRecorder}; +use registry_platform_authcommon::{DeclaredScope, RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ Exposition, HistogramSnapshot, MetricKind, SumCountOrder, CONTENT_TYPE as METRICS_MEDIA_TYPE, }; @@ -141,6 +141,8 @@ pub(crate) struct Metrics { store_capacity: usize, cleanup_expired: AtomicU64, refusals: RefusalRecorder, + /// The configured values a scope refusal's log line names. + declared_scope: Option, } impl Metrics { @@ -152,13 +154,24 @@ impl Metrics { store_capacity, cleanup_expired: AtomicU64::new(0), refusals: RefusalRecorder::new("evidence_oid4vci").expect(DECLARATION), + declared_scope: None, } } + /// Name the configured values a scope refusal's log line carries. + pub(crate) fn with_declared_scope(mut self, declared_scope: Option) -> Self { + self.declared_scope = declared_scope; + self + } + /// Count a refused request under its check and write the admitted log /// line. fn record_refusal(&self, note: RefusalNote) { - registry_platform_authcommon::record_refusal!(self.refusals, note); + registry_platform_authcommon::record_refusal!( + self.refusals, + note, + declared = self.declared_scope.as_ref() + ); } /// The recorder that counts each refused request under its check. diff --git a/crates/registry-evidence-oid4vci/src/service.rs b/crates/registry-evidence-oid4vci/src/service.rs index b86d33c2cd..3008926864 100644 --- a/crates/registry-evidence-oid4vci/src/service.rs +++ b/crates/registry-evidence-oid4vci/src/service.rs @@ -398,7 +398,10 @@ impl DeliveryService { ) -> Self { let store = Arc::new(OfferStore::new(&config.store)); let nonces = NonceMinter::new(config.store.nonce_lifetime_seconds); - let metrics = Arc::new(Metrics::new(config.store.maximum_offers)); + let metrics = Arc::new( + Metrics::new(config.store.maximum_offers) + .with_declared_scope(authorizer.declared_scope()), + ); let limits = Limits::new(&config.rate_limits); Self { config, @@ -1139,11 +1142,9 @@ async fn credential( headers: HeaderMap, body: Bytes, ) -> Response { - let Some(access_token) = bearer_credential(&headers) else { - return unauthorized( - FailedCheck::CredentialMissing, - "a bearer access token is required", - ); + let access_token = match bearer_credential(&headers) { + Ok(access_token) => access_token, + Err(check) => return unauthorized(check, "a bearer access token is required"), }; let access_token = Zeroizing::new(access_token.to_owned()); stage.mark_claiming_token(); @@ -1518,7 +1519,8 @@ async fn authorize_offer( service: &DeliveryService, headers: &HeaderMap, ) -> Result { - let credential = bearer_credential(headers).unwrap_or_default(); + let credential = bearer_credential(headers) + .map_err(|check| unauthorized(check, "a bearer access token is required"))?; service .authorizer .authorize(credential) @@ -1544,15 +1546,31 @@ async fn authorize_offer( }) } -/// The bearer credential a request presented, if it presented one. -fn bearer_credential(headers: &HeaderMap) -> Option<&str> { - let value = headers.get(AUTHORIZATION)?.to_str().ok()?; - let (scheme, credential) = value.split_once(' ')?; +/// The bearer credential a request presented, or the check its header failed: +/// no header, or one naming another scheme, is a missing credential. An +/// unreadable header, or the Bearer scheme with no token after it, is a +/// malformed credential. +fn bearer_credential(headers: &HeaderMap) -> Result<&str, FailedCheck> { + let value = headers + .get(AUTHORIZATION) + .ok_or(FailedCheck::CredentialMissing)? + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + let Some((scheme, credential)) = value.split_once(' ') else { + return Err(if value.eq_ignore_ascii_case("Bearer") { + FailedCheck::CredentialMalformed + } else { + FailedCheck::CredentialMissing + }); + }; if !scheme.eq_ignore_ascii_case("Bearer") { - return None; + return Err(FailedCheck::CredentialMissing); } let credential = credential.trim(); - (!credential.is_empty()).then_some(credential) + if credential.is_empty() { + return Err(FailedCheck::CredentialMalformed); + } + Ok(credential) } /// The system clock, which is the reading a serving process takes. @@ -1642,12 +1660,10 @@ fn warn_on_unusable_issuance(error: &IssuanceError) { fn issuance_response(service: &DeliveryService, error: &IssuanceError) -> Response { record_issuance_outcome(service, error); match error { - IssuanceError::Refused => refused( - problem( - StatusCode::FORBIDDEN, - "invalid_credential_request", - "the credential source refused this request", - ), + IssuanceError::Refused => refusal( + StatusCode::FORBIDDEN, + "invalid_credential_request", + "the credential source refused this request", FailedCheck::SourceAuthority, ), IssuanceError::NotAvailable => problem( @@ -1724,16 +1740,53 @@ fn refused(mut response: Response, check: FailedCheck) -> Response { } fn unauthorized(check: FailedCheck, description: &'static str) -> Response { - let mut response = problem(StatusCode::UNAUTHORIZED, "invalid_token", description); + let mut response = problem_answer(StatusCode::UNAUTHORIZED, "invalid_token", description); response .headers_mut() .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); refused(response, check) } +/// Whether a status is an authentication or authorization refusal, which names +/// the check that failed. +fn is_refusal_status(status: StatusCode) -> bool { + matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) +} + +/// An authentication or authorization refusal with the check that failed. +fn refusal( + status: StatusCode, + error: &'static str, + description: impl Into>, + check: FailedCheck, +) -> Response { + refused(problem_answer(status, error, description), check) +} + +/// One error shape for every answer that is not an authentication or +/// authorization refusal. Those are built by [`refusal`] and [`unauthorized`], +/// which take the failed check. +fn problem( + status: StatusCode, + error: &'static str, + description: impl Into>, +) -> Response { + if is_refusal_status(status) { + tracing::error!( + target: "registry_evidence_oid4vci::service", + "a refusal was built without naming its failed check" + ); + debug_assert!( + false, + "a refusal is built with `refusal`, which names its check" + ); + } + problem_answer(status, error, description) +} + /// One error shape for every refusal: the OAuth members a wallet already reads, /// carrying fixed text chosen here and never any part of the request. -fn problem( +fn problem_answer( status: StatusCode, error: &'static str, description: impl Into>, @@ -1801,6 +1854,78 @@ async fn add_no_store(request: Request, next: Next) -> Response { mod tests { use super::*; + #[test] + fn a_bearer_header_is_classified_by_what_it_lacks() { + let classify = |value: Option<&[u8]>| { + let mut headers = HeaderMap::new(); + if let Some(value) = value { + headers.insert( + AUTHORIZATION, + HeaderValue::from_bytes(value).expect("test header is valid"), + ); + } + bearer_credential(&headers).map(str::to_owned) + }; + assert_eq!(classify(Some(b"Bearer abc")), Ok("abc".to_owned())); + assert_eq!(classify(Some(b"bearer abc")), Ok("abc".to_owned())); + assert_eq!(classify(None), Err(FailedCheck::CredentialMissing)); + assert_eq!( + classify(Some(b"Basic abc")), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + classify(Some(b"Basic")), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + classify(Some(b"Bearer ")), + Err(FailedCheck::CredentialMalformed) + ); + assert_eq!( + classify(Some(b"Bearer")), + Err(FailedCheck::CredentialMalformed) + ); + assert_eq!( + classify(Some(&[0xff, 0xfe])), + Err(FailedCheck::CredentialMalformed) + ); + } + + #[test] + fn refusal_answers_carry_their_failed_check() { + for status in [StatusCode::UNAUTHORIZED, StatusCode::FORBIDDEN] { + let response = refusal( + status, + "invalid_token", + "refused", + FailedCheck::CredentialMissing, + ); + assert_eq!(response.status(), status); + assert!(response.extensions().get::().is_some()); + } + let response = unauthorized(FailedCheck::CredentialMissing, "refused"); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert!(response.extensions().get::().is_some()); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal is built with `refusal`")] + fn an_unauthorized_answer_built_without_a_failed_check_is_caught() { + let _ = problem(StatusCode::UNAUTHORIZED, "invalid_token", "refused"); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal is built with `refusal`")] + fn a_forbidden_answer_built_without_a_failed_check_is_caught() { + let _ = problem( + StatusCode::FORBIDDEN, + "invalid_credential_request", + "refused", + ); + } + use std::{ fs, io::Write, @@ -1935,6 +2060,24 @@ mod tests { } } + /// An authorizer that refuses every credential for its scope and declares + /// the scope gate it enforces. + struct ScopeGateAuthorizer; + + #[async_trait] + impl OfferAuthorizer for ScopeGateAuthorizer { + async fn authorize(&self, _: &str) -> Result { + Err(AuthorizationError::Refused(FailedCheck::Scope)) + } + + fn declared_scope(&self) -> Option { + Some( + registry_platform_authcommon::DeclaredScope::new("scope") + .with_required_scope("offers:create"), + ) + } + } + /// An authorizer whose issuer key set cannot be reached. struct UnreachableKeySetAuthorizer; @@ -3821,6 +3964,49 @@ mod tests { /// The failed check reaches the operator log as well, with the same fixed /// wording and none of the proof's contents. + #[tokio::test] + async fn a_scope_refusal_logs_the_declared_values_and_none_of_the_tokens() { + let buffer = TestLogBuffer::default(); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_writer(buffer.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + + let directory = canonical_tempdir(); + let service = DeliveryService::with_halves( + load_deployment(directory.path()), + Arc::new(ScopeGateAuthorizer), + Arc::new(RecordingIssuer::new()), + test_audit(), + ); + let server = TestServer::new(build_app(Arc::new(service))); + let refused = server + .post(OFFERS_PATH) + .add_header("authorization", "Bearer scope-canary-held-by-the-token") + .json(&offer_body(false)) + .await; + assert_eq!(refused.status_code(), StatusCode::UNAUTHORIZED); + + let rendered = String::from_utf8(buffer.0.lock().expect("log buffer lock").clone()) + .expect("logs are UTF-8"); + assert!(rendered.contains("request refused"), "logs: {rendered}"); + assert!( + rendered.contains("failed_check=\"scope\""), + "logs: {rendered}" + ); + assert!( + rendered.contains("scope_claim=\"scope\""), + "logs: {rendered}" + ); + assert!( + rendered.contains("required_scope=\"offers:create\""), + "logs: {rendered}" + ); + assert!(!rendered.contains("scope-canary"), "logs: {rendered}"); + } + #[tokio::test] async fn a_refused_proof_logs_the_failed_check_without_the_proof_or_nonce() { let buffer = TestLogBuffer::default(); diff --git a/crates/registry-evidence-oid4vci/src/service/draft13.rs b/crates/registry-evidence-oid4vci/src/service/draft13.rs index c134a76345..dacfbbb874 100644 --- a/crates/registry-evidence-oid4vci/src/service/draft13.rs +++ b/crates/registry-evidence-oid4vci/src/service/draft13.rs @@ -108,11 +108,9 @@ async fn credential( headers: HeaderMap, body: Bytes, ) -> Response { - let Some(access_token) = bearer_credential(&headers) else { - return unauthorized( - FailedCheck::CredentialMissing, - "a bearer access token is required", - ); + let access_token = match bearer_credential(&headers) { + Ok(access_token) => access_token, + Err(check) => return unauthorized(check, "a bearer access token is required"), }; let access_token = Zeroizing::new(access_token.to_owned()); stage.mark_claiming_token(); diff --git a/crates/registry-evidence-oid4vp/src/auth.rs b/crates/registry-evidence-oid4vp/src/auth.rs index 184be04511..2f12ca6c7e 100644 --- a/crates/registry-evidence-oid4vp/src/auth.rs +++ b/crates/registry-evidence-oid4vp/src/auth.rs @@ -9,7 +9,9 @@ use std::{sync::Arc, time::Duration}; -use registry_platform_authcommon::{parse_bearer_token, BearerParseError, FailedCheck}; +use registry_platform_authcommon::{ + parse_bearer_token, BearerParseError, DeclaredScope, FailedCheck, +}; use registry_platform_config::{JwksSource, SecretResolver}; use registry_platform_oidc::{ parse_static_jwks, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, @@ -63,6 +65,8 @@ pub struct TokenAuthenticator { verifier: TokenVerifier, issuer: String, required_scope: String, + /// The claim the verifier reads scopes from. + scope_claim: String, } impl std::fmt::Debug for TokenAuthenticator { @@ -137,13 +141,22 @@ impl TokenAuthenticator { if let Some(client) = &config.allowed_client { profile = profile.with_allowed_clients(vec![client.clone()]); } + let scope_claim = profile.scope_claim.clone(); Ok(Self { verifier: TokenVerifier::new(profile, Arc::new(fetcher)), issuer, required_scope: config.required_scope.clone(), + scope_claim, }) } + /// What a scope refusal may say about this gate: the configured claim and + /// the configured scope, never a value the token carried. + #[must_use] + pub fn declared_scope(&self) -> DeclaredScope { + DeclaredScope::new(&self.scope_claim).with_required_scope(&self.required_scope) + } + /// Authenticate the value of an `Authorization` header. pub async fn authenticate(&self, authorization: Option<&str>) -> Result { let header = authorization.ok_or(AuthError::Refused(FailedCheck::CredentialMissing))?; diff --git a/crates/registry-evidence-oid4vp/src/service.rs b/crates/registry-evidence-oid4vp/src/service.rs index c176fbc9ec..9cc7a91c75 100644 --- a/crates/registry-evidence-oid4vp/src/service.rs +++ b/crates/registry-evidence-oid4vp/src/service.rs @@ -23,7 +23,7 @@ use axum::{ Json, Router, }; use chrono::{DateTime, SecondsFormat, Utc}; -use registry_platform_authcommon::{FailedCheck, RefusalNote, RefusalRecorder}; +use registry_platform_authcommon::{DeclaredScope, FailedCheck, RefusalNote, RefusalRecorder}; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit, security_headers, CspBuilder, @@ -500,7 +500,30 @@ async fn normalize_rejections(request: Request, next: Next) -> Response { response } +/// Whether the answer to this problem is an authentication or authorization +/// refusal, which names the check that failed. +fn is_refusal(status: StatusCode) -> bool { + matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) +} + +/// A problem answer that is not an authentication or authorization refusal. +/// Those are built by [`unauthorized`], which takes the failed check. fn problem(code: ProblemCode, detail: &str) -> Response { + let response = problem_answer(code, detail); + if is_refusal(response.status()) { + tracing::error!( + target: "registry_evidence_oid4vp::service", + "a refusal was built without naming its failed check" + ); + debug_assert!( + false, + "a refusal is built with `unauthorized`, which names its check" + ); + } + response +} + +fn problem_answer(code: ProblemCode, detail: &str) -> Response { let status = StatusCode::from_u16(code.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); Problem::new(&code.type_uri(), code.title(), status) @@ -524,7 +547,7 @@ fn refused(mut response: Response, check: FailedCheck) -> Response { /// The 401 a caller without an acceptable bearer credential receives. fn unauthorized(check: FailedCheck) -> Response { - let mut response = problem( + let mut response = problem_answer( ProblemCode::Unauthorized, "a valid bearer token is required", ); @@ -534,6 +557,18 @@ fn unauthorized(check: FailedCheck) -> Response { refused(response, check) } +/// The 401 for a caller the authenticator refused. A scope refusal also +/// carries the gate's configured values for the operator's log line. +fn refused_by(check: FailedCheck, authenticator: &TokenAuthenticator) -> Response { + let mut response = unauthorized(check); + if check == FailedCheck::Scope { + response + .extensions_mut() + .insert(authenticator.declared_scope()); + } + response +} + /// The 503 a caller receives when the issuer's key set cannot be used. fn issuer_unavailable_answer() -> Response { refused( @@ -557,12 +592,18 @@ async fn record_refusals( ) -> Response { let response = next.run(request).await; if let Some(note) = response.extensions().get::() { + let declared = response.extensions().get::(); match registry_platform_httpsec::response_trace_id(response.headers()) { Ok(trace) => { - registry_platform_authcommon::record_refusal!(refusals, *note, trace_id = trace); + registry_platform_authcommon::record_refusal!( + refusals, + *note, + trace_id = trace, + declared = declared + ); } Err(_) => { - registry_platform_authcommon::record_refusal!(refusals, *note); + registry_platform_authcommon::record_refusal!(refusals, *note, declared = declared); } } } @@ -651,7 +692,7 @@ async fn applicant(service: &VerifierService, headers: &HeaderMap) -> Result { service.metrics.record(Event::SessionRefusedAuthentication); - Err(unauthorized(check)) + Err(refused_by(check, &service.applicants)) } } } @@ -1225,7 +1266,7 @@ async fn read_presentation( } Err(AuthError::Refused(check)) => { service.metrics.record(Event::ReadRefusedAuthentication); - return unauthorized(check); + return refused_by(check, &service.evidence_credentials); } }; if let Err(response) = admit( @@ -1503,3 +1544,37 @@ async fn wait_for_stop(mut stopped: watch::Receiver) { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_unauthorized_answer_carries_its_failed_check() { + let response = unauthorized(FailedCheck::CredentialMissing); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert!(response.extensions().get::().is_some()); + } + + #[test] + fn every_problem_code_answered_as_a_refusal_is_built_by_unauthorized() { + for &code in ProblemCode::ALL { + let status = problem_answer(code, "detail").status(); + assert_eq!( + is_refusal(status), + code == ProblemCode::Unauthorized, + "{code:?} answers {status}" + ); + } + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal is built with `unauthorized`")] + fn a_refusal_built_without_a_failed_check_is_caught() { + let _ = problem( + ProblemCode::Unauthorized, + "a valid bearer token is required", + ); + } +} diff --git a/crates/registry-evidence-oid4vp/tests/refusal_recording.rs b/crates/registry-evidence-oid4vp/tests/refusal_recording.rs index 5aa87ca0ba..a19b576c2f 100644 --- a/crates/registry-evidence-oid4vp/tests/refusal_recording.rs +++ b/crates/registry-evidence-oid4vp/tests/refusal_recording.rs @@ -420,4 +420,15 @@ async fn each_refusal_is_counted_and_logged_under_its_check() { form(&server).into_future(), ) .await; + + // A scope refusal names the claim and the scopes the configuration + // declares for each gate, and none of the scopes the tokens held. + let text = logs.text(); + assert!(text.contains("scope_claim=\"scope\""), "{text}"); + assert!( + text.contains("required_scope=\"oid4vp:read-result\""), + "{text}" + ); + assert!(text.contains("required_scope=\"oid4vp:session\""), "{text}"); + assert!(!text.contains("something:else"), "{text}"); } diff --git a/crates/registry-evidence/src/auth.rs b/crates/registry-evidence/src/auth.rs index ae9c0686d2..3f01e8a082 100644 --- a/crates/registry-evidence/src/auth.rs +++ b/crates/registry-evidence/src/auth.rs @@ -7,7 +7,7 @@ use std::{ #[cfg(test)] use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; -use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; +use registry_platform_authcommon::{validate_compact_access_token, DeclaredScope, FailedCheck}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ actor_kind, grant_claims, ActorKind, Audience, ClaimError, ClaimNames, GrantClaims, @@ -76,6 +76,8 @@ pub struct Authenticator { /// Resource identifiers accepted by the verifier. A task grant must name /// the one member that actually matched the token audience. resources: Vec, + /// The claim the verifier reads scopes from, as the configuration names it. + scope_claim: String, key_source: Arc>, } @@ -273,6 +275,9 @@ impl AuthenticationError { /// possession, such as DPoP or mutual TLS. const CONFIRMATION_CLAIM: &str = "cnf"; +/// The claim the platform verifier reads scopes from unless configured. +const DEFAULT_SCOPE_CLAIM: &str = "scope"; + impl Authenticator { /// Build the one strict resource-server profile from the loaded bundle. /// @@ -326,6 +331,7 @@ impl Authenticator { jwks_fetch_policy(config), issuer_roots, )); + let scope_claim = verifier_config.scope_claim.clone(); let verifier = Arc::new(TokenVerifier::new(verifier_config, fetcher)); let claims = AuthenticationClaimsConfig { principal_claim: config.principal_claim.clone(), @@ -335,6 +341,7 @@ impl Authenticator { actor_claim: config.actor_claim.clone(), }; Self::new(verifier, claims) + .with_scope_claim(scope_claim) .with_required_scopes(config.required_scopes.admitted()) .with_resources(vec![config.audience().to_owned()]) } @@ -345,6 +352,7 @@ impl Authenticator { claims, required_scopes: Vec::new(), resources: Vec::new(), + scope_claim: DEFAULT_SCOPE_CLAIM.to_owned(), key_source: Arc::new(Mutex::new(KeySourceState::default())), } } @@ -358,6 +366,24 @@ impl Authenticator { self } + /// Name the claim the verifier reads scopes from. The platform verifier + /// reads `scope` unless told otherwise. + #[must_use] + pub fn with_scope_claim(mut self, scope_claim: String) -> Self { + self.scope_claim = scope_claim; + self + } + + /// What a scope refusal may say about the deployment: the claim name and + /// the scopes the configuration requires. Both are configured values, so + /// the line they appear in carries nothing the caller's token held. + pub fn declared_scope(&self) -> Option { + (!self.required_scopes.is_empty()).then(|| { + DeclaredScope::new(&self.scope_claim) + .with_required_scope(self.required_scopes.join(" ")) + }) + } + #[must_use] pub fn with_resources(mut self, resources: Vec) -> Self { self.resources = resources; @@ -485,7 +511,7 @@ impl Authenticator { .jwks_uri() .unwrap_or(STATIC_KEY_SOURCE), cause = describe_causes(error), - "the access-token issuer key set could not be retrieved; every request is rejected until it can be" + "the access-token issuer key set could not be retrieved or used" ); } diff --git a/crates/registry-evidence/src/observability.rs b/crates/registry-evidence/src/observability.rs index 4b6e663744..e0e88d26f9 100644 --- a/crates/registry-evidence/src/observability.rs +++ b/crates/registry-evidence/src/observability.rs @@ -48,7 +48,7 @@ use axum::{ routing::get, Router, }; -use registry_platform_authcommon::{record_refusal, RefusalNote, RefusalRecorder}; +use registry_platform_authcommon::{record_refusal, DeclaredScope, RefusalNote, RefusalRecorder}; use registry_platform_httpsec::{TraceContext, TraceId}; use registry_platform_metrics::{ Exposition, HistogramSnapshot, MetricKind, SumCountOrder, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -263,7 +263,12 @@ pub(crate) async fn observe( fn record_response_refusal(metrics: &Metrics, response: &Response, operation: &OperationId) { match response.extensions().get::() { Some(note) => { - record_refusal!(metrics.refusals, *note, trace_id = operation.trace_id()); + record_refusal!( + metrics.refusals, + *note, + trace_id = operation.trace_id(), + declared = metrics.declared_scope.as_ref() + ); } None => { if response @@ -352,6 +357,8 @@ pub(crate) struct Metrics { /// Counts refusals by the check that failed and bounds the log lines they /// write. Keyed by no request value. refusals: RefusalRecorder, + /// The configured values a scope refusal's log line names. + declared_scope: Option, } impl Default for Metrics { @@ -362,6 +369,7 @@ impl Default for Metrics { rate_limiter: None, source_diagnostics: None, refusals: RefusalRecorder::new("evidence").expect(DECLARATION), + declared_scope: None, } } } @@ -406,6 +414,12 @@ impl Metrics { } } + /// Name the configured values a scope refusal's log line carries. + pub(crate) fn with_declared_scope(mut self, declared_scope: Option) -> Self { + self.declared_scope = declared_scope; + self + } + fn record( &self, route: &'static str, diff --git a/crates/registry-evidence/src/refusal_recording_tests.rs b/crates/registry-evidence/src/refusal_recording_tests.rs index 1ba5e5dc7f..6acf2b010e 100644 --- a/crates/registry-evidence/src/refusal_recording_tests.rs +++ b/crates/registry-evidence/src/refusal_recording_tests.rs @@ -539,3 +539,49 @@ async fn a_request_over_the_rate_budget_is_counted_under_rate_limit() { ); assert_eq!(counted(&metrics.render(), FailedCheck::RateLimit), 1); } + +/// A scope refusal names the claim and the scopes the configuration declares. +/// Nothing the token carried reaches the line, whatever scopes it held. +#[test] +fn a_scope_refusal_logs_the_declared_values_and_none_of_the_tokens() { + const SCOPE_CANARY: &str = "scope-canary-held-by-the-token"; + let scenario = evidence( + "token-lacks-the-required-scope", + Credential::Token(access_token(Some(json!({"scope": SCOPE_CANARY})))), + adult_request(), + StatusCode::UNAUTHORIZED, + FailedCheck::Scope, + ); + let answered: Arc>> = Arc::new(Mutex::new(None)); + let sink = Arc::clone(&answered); + let emitted = capture_evidence_logs(|| async { + let fixture = acceptance_runtime_with( + authenticator().with_required_scopes(vec!["evidence:invoke".to_owned()]), + ) + .await; + let (app, _metrics) = build_app_with_metrics(Arc::clone(&fixture.runtime)); + let response = app + .oneshot(build_request(&scenario)) + .await + .expect("the router answers"); + *sink.lock().expect("status slot") = Some(response.status()); + }); + assert_eq!( + answered.lock().expect("status slot").take(), + Some(StatusCode::UNAUTHORIZED) + ); + let refused: Vec<&Value> = emitted + .iter() + .filter(|record| record["fields"]["decision"] == json!("refused")) + .collect(); + assert_eq!(refused.len(), 1, "{refused:?}"); + let fields = &refused[0]["fields"]; + assert_eq!(fields["failed_check"], json!("scope")); + assert_eq!(fields["scope_claim"], json!("scope")); + assert_eq!(fields["required_scope"], json!("evidence:invoke")); + let raw = serde_json::to_string(&emitted).expect("captured records serialize"); + assert!( + !raw.contains(SCOPE_CANARY), + "a log line carried the token's scope" + ); +} diff --git a/crates/registry-evidence/src/runtime.rs b/crates/registry-evidence/src/runtime.rs index 2e8652295f..d66d432d48 100644 --- a/crates/registry-evidence/src/runtime.rs +++ b/crates/registry-evidence/src/runtime.rs @@ -13,7 +13,7 @@ use async_trait::async_trait; use chrono::{SubsecRound as _, Utc}; use registry_adapter_engine::route::EvidenceHttpDiagnostic; use registry_platform_audit::{AuditDestination, AuditError, AuditProfile}; -use registry_platform_authcommon::FailedCheck; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_crypto::{ LocalJwkSigner, PrivateJwk, SigningProvider, TransitInitializationError, TransitSigner, TransitSignerConfig, @@ -524,6 +524,12 @@ pub(crate) trait RuntimeAuthenticator: Send + Sync { async fn announce_key_source(&self); async fn key_source_ready(&self) -> bool; + + /// What a scope refusal may say about the deployment, when it has a scope + /// gate. + fn declared_scope(&self) -> Option { + None + } } #[async_trait] @@ -543,6 +549,10 @@ impl RuntimeAuthenticator for Authenticator { Authenticator::announce_key_source(self).await; } + fn declared_scope(&self) -> Option { + Authenticator::declared_scope(self) + } + async fn key_source_ready(&self) -> bool { Authenticator::key_source_ready(self).await } @@ -852,6 +862,11 @@ impl EvidenceRuntime { /// The per-source diagnostics whose counters back the /// `evidence_source_shape_drift_total` series on the metrics listener. + /// The configured values a scope refusal's log line may name. + pub(crate) fn declared_scope(&self) -> Option { + self.authenticator.declared_scope() + } + pub(crate) fn source_diagnostics(&self) -> Arc { Arc::clone(&self.source_diagnostics) } diff --git a/crates/registry-evidence/src/runtime_tests.rs b/crates/registry-evidence/src/runtime_tests.rs index 6f4e35fcc9..fc714d6573 100644 --- a/crates/registry-evidence/src/runtime_tests.rs +++ b/crates/registry-evidence/src/runtime_tests.rs @@ -9827,9 +9827,13 @@ fn acceptance_case_time( } async fn acceptance_runtime() -> AcceptanceRuntime { + acceptance_runtime_with(authenticator()).await +} + +async fn acceptance_runtime_with(authenticator: Authenticator) -> AcceptanceRuntime { let prepared = prepare_acceptance("subject-binding-secret-canary-32-bytes-minimum").await; let runtime = Arc::new( - EvidenceRuntime::initialize_with_authenticator(&prepared.runtime_path, authenticator()) + EvidenceRuntime::initialize_with_authenticator(&prepared.runtime_path, authenticator) .await .expect("one immutable acceptance runtime initializes"), ); diff --git a/crates/registry-evidence/src/server.rs b/crates/registry-evidence/src/server.rs index 119432442b..9a6518cd82 100644 --- a/crates/registry-evidence/src/server.rs +++ b/crates/registry-evidence/src/server.rs @@ -157,6 +157,7 @@ fn build_app_with_tracker_at( // use, on the separate opt-in metrics listener. let rate_limiter = runtime.rate_limiter(); let source_diagnostics = runtime.source_diagnostics(); + let declared_scope = runtime.declared_scope(); let state = Arc::new(ServerState { runtime, maximum_request_bytes, @@ -212,7 +213,9 @@ fn build_app_with_tracker_at( authentication_challenge, attach_authentication_challenge, )); - let metrics = Arc::new(Metrics::new(rate_limiter, source_diagnostics)); + let metrics = Arc::new( + Metrics::new(rate_limiter, source_diagnostics).with_declared_scope(declared_scope), + ); ( response_layers(routes, Arc::clone(&metrics)), evaluations, @@ -1155,24 +1158,32 @@ fn parse_evidence_request_batch(bytes: &[u8]) -> Result Result<&str, FailedCheck> { let mut values = headers.get_all(AUTHORIZATION).iter(); let value = values.next().ok_or(FailedCheck::CredentialMissing)?; if values.next().is_some() { return Err(FailedCheck::CredentialMalformed); } - parse_bearer_token( - value - .to_str() - .map_err(|_| FailedCheck::CredentialMalformed)?, - ) - .map_err(|error| match error { + let value = value + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + parse_bearer_token(value).map_err(|error| match error { BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + BearerParseError::Malformed if !is_scheme_prefix(value) => FailedCheck::CredentialMissing, _ => FailedCheck::CredentialMalformed, }) } +/// Whether the value is the start of the `Bearer` scheme name, compared ASCII +/// case-insensitively. +fn is_scheme_prefix(value: &str) -> bool { + const SCHEME: &[u8] = b"Bearer"; + value.len() <= SCHEME.len() && SCHEME[..value.len()].eq_ignore_ascii_case(value.as_bytes()) +} + fn has_exact_content_type(headers: &HeaderMap, expected: &str) -> bool { let mut values = headers.get_all(CONTENT_TYPE).iter(); let Some(value) = values.next() else { @@ -1392,6 +1403,9 @@ mod tests { for (invalid, check) in [ ("Basic three.parts.value", FailedCheck::CredentialMissing), + ("Basic", FailedCheck::CredentialMissing), + ("Bear", FailedCheck::CredentialMalformed), + ("bearer", FailedCheck::CredentialMalformed), ("Bearer", FailedCheck::CredentialMalformed), ( "Bearer three.parts.value", diff --git a/crates/registry-evidencectl/src/client.rs b/crates/registry-evidencectl/src/client.rs index e206112c86..b516bb3732 100644 --- a/crates/registry-evidencectl/src/client.rs +++ b/crates/registry-evidencectl/src/client.rs @@ -413,6 +413,9 @@ fn validate_base_url(url: &Url, allow_local_loopback: bool) -> Result<()> { } } +/// Exactly `127.0.0.1`, the only loopback address a client profile accepts +/// for local-loopback discovery, so a profile written here is one the client +/// library reads back. fn is_loopback_host(host: url::Host<&str>) -> bool { match host { url::Host::Ipv4(address) => address == std::net::Ipv4Addr::LOCALHOST, diff --git a/products/evidence/CHANGELOG.md b/products/evidence/CHANGELOG.md index 4fcd87ee1c..3225251867 100644 --- a/products/evidence/CHANGELOG.md +++ b/products/evidence/CHANGELOG.md @@ -22,10 +22,21 @@ `access-profile` unless it presented a task grant. The key-source `WARN` line now follows the same classification as the `key-source-unavailable` count. +- The `request refused` line of Evidence, Evidence OID4VCI and Evidence OID4VP + names the configured scope claim and the scope or scopes the configuration + requires when the failed check is `scope`, as `scope_claim` and + `required_scope`. Nothing the caller's token carried is written. No response + status, header or body changes. - Evidence OID4VP states the rule a refused static key set broke in its startup message, still under `evidence.oid4vp.issuer-unavailable`. A request whose `Authorization` header is present but unreadable as text counts under `credential-malformed`. The answer is unchanged. +- Evidence counts an `Authorization` header that names another scheme, such as + `Basic`, under `credential-missing`, and a header that is only the start of + `Bearer` under `credential-malformed`. Evidence OID4VCI counts an unreadable + header, or `Bearer` with no token, under `credential-malformed`. The + key-source `WARN` text says the key set could not be retrieved or used, and + no longer says every request is rejected. No answer changes. - `evidencectl suggest` accepts an IPv4-mapped IPv6 loopback address, for example `[::ffff:127.0.0.1]`, for a plain-HTTP base URL or OpenAPI URL, as the shared loopback rule does. The name `localhost` is still refused there. From 5da928931be9d2368d46abb534570c7bd7589e50 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:21:08 +0100 Subject: [PATCH 051/136] docs: explain where authority lives across token, configuration and records The page states which of the three decides identity, profile reach and row reach, what membership boundaries cover today, and how Casework keeps BReg disclosure under the reviewer's identity. Linked from the security overview. Signed-off-by: Jeremi Joslin --- docs/site/astro.config.mjs | 1 + .../explanation/where-authority-lives.mdx | 87 +++++++++++++++++++ docs/site/src/content/docs/security/index.mdx | 1 + 3 files changed, 89 insertions(+) create mode 100644 docs/site/src/content/docs/explanation/where-authority-lives.mdx diff --git a/docs/site/astro.config.mjs b/docs/site/astro.config.mjs index 7bb1a4ea8b..ea07b9d1c3 100644 --- a/docs/site/astro.config.mjs +++ b/docs/site/astro.config.mjs @@ -1043,6 +1043,7 @@ export default defineConfig({ items: [ { label: 'Architecture', slug: 'explanation/architecture' }, { label: 'Where each rule lives', slug: 'explanation/where-each-rule-lives' }, + { label: 'Where authority lives', slug: 'explanation/where-authority-lives' }, { label: 'Data minimization', slug: 'explanation/data-minimization-and-purpose-limitation' }, { label: 'DPI safeguards', slug: 'explanation/dpi-safeguards-alignment' }, { label: 'Retired products', slug: 'decisions/registry-relay-retirement-2026-10-03' }, diff --git a/docs/site/src/content/docs/explanation/where-authority-lives.mdx b/docs/site/src/content/docs/explanation/where-authority-lives.mdx new file mode 100644 index 0000000000..0b7d04a87e --- /dev/null +++ b/docs/site/src/content/docs/explanation/where-authority-lives.mdx @@ -0,0 +1,87 @@ +--- +title: Where authority lives +description: Which of the token, the configuration and the records decides who a caller is, what a profile may do, and which rows and teams a caller reaches, and what holds today. +status: current +owner: registry-docs +source_repos: + - registry-stack +last_reviewed: "2026-11-27" +doc_type: explanation +locale: en +standards_referenced: [] +--- + +Every Registry Stack product asks the same three questions about a request. Each question has one +home. Knowing the home tells you where to change an answer, and which answer takes effect first. + +## One rule + +- The token says who the caller is. Your issuer signs it, and the product verifies it. +- Configuration says what a profile may do. The access profile lists operations, fields and purposes. +- Records say which rows and which teams. Today this holds only in part, as the next sections show. + +A caller cannot widen its own reach. A request field is never an authorisation decision, and a +product inherits no authority from another product. + +{/* Evidence: crates/registry-breg/src/access.rs; crates/registry-platform-oidc/src/lib.rs. */} + +## Row authority today comes from token claims + +A [row boundary](../../reference/glossary/#row-boundary) compares a Record field with a claim in +the verified token. Base Registry Engine (BReg) declares it with `rowBoundaries` on a record +permission. The rows a caller reaches therefore depend on what your issuer put in the token. + +This has two consequences. + +- Your issuer must be one you trust to assert the claim. +- A change to a caller's reach takes effect when the caller next receives a token, not when you + change a record. + +The compiled form shows the limit of this design. An empty list of boundaries permits every row, and +the authored `rowBoundaries: unrestricted` compiles to that empty list. + +See [BReg access profiles](../../configure/breg-access/) for the fields and examples. + +{/* Evidence: crates/registry-breg/src/contract.rs row_boundaries; crates/registry-breg/src/access.rs; + crates/registry-breg/src/authority.rs. */} + +## Membership boundaries read records, for reads only + +A membership boundary moves the decision into records. A row is readable only while a current, +active membership Record names the caller. Deactivate the membership and the next request no longer +sees the row. No token expiry is involved. + +Membership boundaries support `get`, `lookup`, `list`, `revisions` and `snapshot` only. Today BReg +refuses a profile that combines a membership boundary with any other operation, or with +`writableFields`. The compiler reports `breg.access.membership-read-only` and tells you to use a +separate, directly authorised profile for writes and proposal application. + +So a registry that must restrict writes by team still uses `rowBoundaries` and token claims for the +write profile. Membership records cannot yet carry write authority. + +Two more limits apply today: + +- A profile with a membership boundary cannot enable spatial bounding-box queries. +- A profile declares at most eight membership boundaries. + +{/* Evidence: crates/registry-breg/src/membership.rs validate(); + crates/registry-breg/tests/membership_access.rs membership_boundaries_refuse_unenforced_authority_paths. */} + +## Casework keeps BReg disclosure under the reviewer's identity + +Registry Casework decides who may review a task. It does not decide what a reviewer may see in +BReg. When Casework shows a reviewer the current record, BReg answers under the reviewer's own +identity and its own access profile. Casework adds no disclosure authority. + +Today, by default, Casework forwards the reviewer's bearer token to BReg for that read. A provider +that declares `humanSourceAuthentication` can use a separate source credential for the same +reviewer instead. On either path BReg applies its own profile to the identity it receives. + +{/* Evidence: crates/registry-casework/src/review.rs; crates/registry-casework-breg/src/lib.rs human_display(); + crates/registry-casework/src/http/source_credentials.rs. */} + +## Continue + +- [BReg access profiles](../../configure/breg-access/) +- [Where each rule lives](../where-each-rule-lives/) +- [Security model](../../security/) diff --git a/docs/site/src/content/docs/security/index.mdx b/docs/site/src/content/docs/security/index.mdx index 79607ab78f..f12e42933e 100644 --- a/docs/site/src/content/docs/security/index.mdx +++ b/docs/site/src/content/docs/security/index.mdx @@ -240,6 +240,7 @@ provisions and runs. ## Continue - [Threat model](../explanation/threat-model/) +- [Where authority lives](../explanation/where-authority-lives/) - [Production hardening checklist](hardening-checklist/) - [Known limitations](../explanation/known-limitations/) - [Report a vulnerability](report-a-vulnerability/) From 3215b8e2bd9b8523068a3b085c1c9f08cf9b3c34 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:25:21 +0100 Subject: [PATCH 052/136] fix(scheduling): count non-attendable refusals as visibility and name declared scope Recording attendance on an appointment that takes none in its current state keeps the same 403 and counts under visibility, not ownership. A scope refusal line names the configured scope claim, the scope the route needs and the source-busy profile id when one applies, never a scope the token carries. The task grant reference names which operations need a listed authority, the API reference and the createAppointment description say an appointment can be created without a hold, the OpenAPI generator stops when its refusal marker is missing, and the changelog's upgrade advice now says to upgrade clients first. Signed-off-by: Jeremi Joslin --- crates/registry-scheduling/src/auth.rs | 32 +++++++++++- crates/registry-scheduling/src/http.rs | 49 ++++++++++++++++--- crates/registry-scheduling/src/refusal.rs | 1 + crates/registry-scheduling/src/service.rs | 37 ++++++++------ crates/registry-scheduling/src/store.rs | 4 ++ .../src/store/attendance.rs | 2 +- .../tests/postgres_commitments/attendance.rs | 47 ++++++++++++++++++ .../review_regressions.rs | 27 ++++++++++ .../reference/apis/registry-scheduling.mdx | 2 +- .../docs/reference/scheduling-task-grants.mdx | 2 +- .../src/content/docs/security/scheduling.mdx | 1 + products/scheduling/CHANGELOG.md | 12 +++-- .../contracts/recorded-decisions.yaml | 1 - .../registry-scheduling.openapi.json | 2 +- .../scheduling/scripts/generate_openapi.py | 9 ++-- .../scripts/test_generate_openapi.py | 16 ++++++ 16 files changed, 212 insertions(+), 32 deletions(-) diff --git a/crates/registry-scheduling/src/auth.rs b/crates/registry-scheduling/src/auth.rs index f78eee21d7..79f3481b80 100644 --- a/crates/registry-scheduling/src/auth.rs +++ b/crates/registry-scheduling/src/auth.rs @@ -35,7 +35,9 @@ use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use chrono::{DateTime, Utc}; -use registry_platform_authcommon::{validate_compact_access_token, FailedCheck, RefusalRecorder}; +use registry_platform_authcommon::{ + validate_compact_access_token, DeclaredScope, FailedCheck, RefusalRecorder, +}; use registry_platform_oidc::{ actor_kind, grant_claims, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, @@ -57,6 +59,7 @@ pub struct SchedulingAuthenticator { verifier: TokenVerifier, claim_names: ClaimNames, audience: String, + scope_claim: String, reads_scope: String, explain_scope: String, appointment_read_profiles: BTreeMap, @@ -87,6 +90,7 @@ impl SchedulingAuthenticator { verifier: TokenVerifier::new(verifier, keys), claim_names, audience: oidc.provider.audience.clone(), + scope_claim: oidc.scope_claim.clone(), reads_scope: oidc.reads_scope.clone(), explain_scope: oidc.explain_scope.clone(), appointment_read_profiles: oidc.appointment_read_profiles.clone(), @@ -98,6 +102,32 @@ impl SchedulingAuthenticator { } } + /// The configured values a reads-scope refusal's log line names. + #[must_use] + pub fn declared_reads_scope(&self) -> DeclaredScope { + DeclaredScope::new(&self.scope_claim).with_required_scope(&self.reads_scope) + } + + /// The configured values an explain-scope refusal's log line names. + #[must_use] + pub fn declared_explain_scope(&self) -> DeclaredScope { + DeclaredScope::new(&self.scope_claim).with_required_scope(&self.explain_scope) + } + + /// The configured values a source-busy scope refusal's log line names: + /// the profile's scope, and the profile id when the deployment declares + /// that profile. + #[must_use] + pub fn declared_busy_scope(&self, profile_selector: &str) -> DeclaredScope { + let declared = DeclaredScope::new(&self.scope_claim); + match self.busy_import_profiles.get(profile_selector) { + Some(profile) => declared + .with_required_scope(&profile.scope) + .with_access_profile(profile_selector), + None => declared, + } + } + /// The profile every catalogue, availability, and owned-record read /// demands: the caller holds the configured reads scope. pub async fn authenticate_read(&self, token: &str) -> Result { diff --git a/crates/registry-scheduling/src/http.rs b/crates/registry-scheduling/src/http.rs index 14e13d92f9..f64705e3b8 100644 --- a/crates/registry-scheduling/src/http.rs +++ b/crates/registry-scheduling/src/http.rs @@ -33,7 +33,8 @@ use axum::routing::{delete, get, post, put}; use axum::{Json, Router}; use chrono::{DateTime, Utc}; use registry_platform_authcommon::{ - parse_bearer_token, record_refusal, BearerParseError, FailedCheck, RefusalNote, RefusalRecorder, + parse_bearer_token, record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, + RefusalRecorder, }; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, @@ -180,7 +181,10 @@ async fn authenticate_busy_source( .authenticator .authenticate_busy_source(token, profile) .await - .map_err(authentication_problem) + .map_err(|error| { + authentication_problem(error) + .with_declared_scope(state.authenticator.declared_busy_scope(profile)) + }) } fn busy_request_problem(error: BusyRequestError) -> HttpError { @@ -884,7 +888,11 @@ async fn authenticate_read(state: &HttpState, headers: &HeaderMap) -> Result Result { @@ -905,7 +916,11 @@ async fn authenticate_explain(state: &HttpState, headers: &HeaderMap) -> Result< .authenticator .authenticate_explain(token) .await - .map_err(|error| authentication_problem(error).with_scope_remedy()) + .map_err(|error| { + authentication_problem(error) + .with_scope_remedy() + .with_declared_scope(state.authenticator.declared_explain_scope()) + }) } async fn authenticate_mutate(state: &HttpState, headers: &HeaderMap) -> Result { @@ -1074,6 +1089,8 @@ fn idempotency_key(headers: &HeaderMap) -> Result<&str, HttpError> { pub struct HttpError { problem: ProblemCode, note: Option, + /// The operator-declared scope values a scope refusal's log line names. + declared: Option, } impl HttpError { @@ -1090,6 +1107,7 @@ impl HttpError { Self { problem, note: None, + declared: None, } } @@ -1098,6 +1116,7 @@ impl HttpError { Self { problem: code.problem(), note: Some(RefusalNote::new(check)), + declared: None, } } @@ -1106,9 +1125,18 @@ impl HttpError { Self { problem: ProblemCode::ServiceUnavailable, note: Some(RefusalNote::new(check)), + declared: None, } } + /// Attach the values the operator declared for the scope this route + /// demands. They ride in the response extensions and are written to the + /// log line only for a scope refusal. + fn with_declared_scope(mut self, declared: DeclaredScope) -> Self { + self.declared = Some(declared); + self + } + /// Name the setting the operator checks when this is a scope refusal of /// a read or explain route. fn with_scope_remedy(mut self) -> Self { @@ -1141,6 +1169,9 @@ impl IntoResponse for HttpError { if let Some(note) = self.note { response.extensions_mut().insert(note); } + if let Some(declared) = self.declared { + response.extensions_mut().insert(declared); + } response } } @@ -1165,7 +1196,13 @@ async fn record_refusals( let response = next.run(request).await; if let Some(note) = response.extensions().get::().copied() { let trace = current_trace(); - record_refusal!(recorder, note, trace_id = &trace.trace_id); + let declared = response.extensions().get::(); + record_refusal!( + recorder, + note, + trace_id = &trace.trace_id, + declared = declared + ); } response } diff --git a/crates/registry-scheduling/src/refusal.rs b/crates/registry-scheduling/src/refusal.rs index 7899c22b10..a1a9ab73ff 100644 --- a/crates/registry-scheduling/src/refusal.rs +++ b/crates/registry-scheduling/src/refusal.rs @@ -36,6 +36,7 @@ impl RefusalCode { /// code, so a code added to the vocabulary does not compile until it is /// sorted here. The vocabulary test in `http.rs` pins the refusal set. #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] pub const fn of(problem: ProblemCode) -> Option { match problem { ProblemCode::AuthenticationRefused => Some(Self::AuthenticationRefused), diff --git a/crates/registry-scheduling/src/service.rs b/crates/registry-scheduling/src/service.rs index 6ebc524474..cec2e7f17e 100644 --- a/crates/registry-scheduling/src/service.rs +++ b/crates/registry-scheduling/src/service.rs @@ -2912,9 +2912,9 @@ impl SchedulingService { CommitError::KeyReused | CommitError::KeyExpired => { Unanswered::Unfinished(key_refusal_reason(&error)) } - CommitError::Unauthorized | CommitError::GrantLapsed => { - Unanswered::Denied("authorization.refused") - } + CommitError::Unauthorized + | CommitError::NotAttendable + | CommitError::GrantLapsed => Unanswered::Denied("authorization.refused"), CommitError::Refused(_) | CommitError::HoldCeiling | CommitError::RevisionMismatch @@ -3015,16 +3015,18 @@ impl SchedulingService { }; self.record_refusal(correlation, record).await?; Err(match RefusalCode::of(problem) { - // `CommitError::Unauthorized` and `CommitError::GrantLapsed` - // are the only commit failures that refuse authority: the - // target is not this caller's to change, or the grant or - // its access token lapsed inside the transaction. + // `CommitError::Unauthorized`, `CommitError::NotAttendable` + // and `CommitError::GrantLapsed` are the only commit + // failures that refuse authority: the target is not this + // caller's to change, the appointment takes no attendance + // in its current state, or the grant or its access token + // lapsed inside the transaction. Some(code) => ServiceError::Refused { code, - check: if matches!(error, CommitError::GrantLapsed) { - FailedCheck::TaskGrantExpired - } else { - FailedCheck::Ownership + check: match error { + CommitError::GrantLapsed => FailedCheck::TaskGrantExpired, + CommitError::NotAttendable => FailedCheck::Visibility, + _ => FailedCheck::Ownership, }, }, None => ServiceError::Problem(problem), @@ -3878,7 +3880,9 @@ fn problem_of(error: &CommitError) -> ProblemCode { CommitError::KeyReused => ProblemCode::IdempotencyKeyReused, CommitError::KeyExpired => ProblemCode::IdempotencyExpired, CommitError::HoldCeiling => ProblemCode::CapacityExhausted, - CommitError::Unauthorized | CommitError::GrantLapsed => ProblemCode::OperationNotAuthorized, + CommitError::Unauthorized | CommitError::NotAttendable | CommitError::GrantLapsed => { + ProblemCode::OperationNotAuthorized + } CommitError::RevisionMismatch => ProblemCode::RevisionMismatch, CommitError::ObservationInFuture => ProblemCode::RequestUnprocessable, CommitError::CutoffPassed => ProblemCode::CancellationCutoffPassed, @@ -3893,8 +3897,9 @@ fn problem_of(error: &CommitError) -> ProblemCode { /// The decision a stored receipt carries, as its replay's `response` entry /// records it. A success receipt was allowed. A refusal receipt was written /// only for a decision the ledger took, so it keeps the reason its first -/// answer recorded: a lapsed grant is `authorization.refused`, every other -/// ledger refusal `authorization.profile`. +/// answer recorded: an `operation.not-authorized` receipt (a lapsed grant, or +/// a target the caller does not manage) is `authorization.refused`, every +/// other ledger refusal `authorization.profile`. fn replayed_decision(status_code: u16, receipt: &Value) -> (AuthorizationOutcome, &'static str) { if status_code < 400 { return (AuthorizationOutcome::Allowed, "authorization.allowed"); @@ -4589,6 +4594,10 @@ mod tests { problem_of(&CommitError::Unauthorized), ProblemCode::OperationNotAuthorized ); + assert_eq!( + problem_of(&CommitError::NotAttendable), + ProblemCode::OperationNotAuthorized + ); assert_eq!( problem_of(&CommitError::GrantLapsed), ProblemCode::OperationNotAuthorized diff --git a/crates/registry-scheduling/src/store.rs b/crates/registry-scheduling/src/store.rs index 4e1c63fecf..180c5723f2 100644 --- a/crates/registry-scheduling/src/store.rs +++ b/crates/registry-scheduling/src/store.rs @@ -900,6 +900,10 @@ pub enum CommitError { /// its source manager differs. #[error("the target is not managed by this caller")] Unauthorized, + /// The appointment is absent or not in a state that takes attendance. + /// The caller may own it, so this is no ownership decision. + #[error("the appointment does not take attendance")] + NotAttendable, /// The task grant, or the access token that carried it, lapsed before the /// commitment. #[error("the task grant lapsed before the commitment")] diff --git a/crates/registry-scheduling/src/store/attendance.rs b/crates/registry-scheduling/src/store/attendance.rs index c372e4f86e..a134678878 100644 --- a/crates/registry-scheduling/src/store/attendance.rs +++ b/crates/registry-scheduling/src/store/attendance.rs @@ -50,7 +50,7 @@ impl PostgresStore { claim.kind == LedgerKind::Booking && matches!(claim.state, ClaimState::Active | ClaimState::Cancelled) }) - .ok_or(CommitError::Unauthorized)?; + .ok_or(CommitError::NotAttendable)?; let appointment_revision = i64::try_from(request.observed_appointment_revision) .map_err(|_| CommitError::RevisionMismatch)?; if claim.revision != appointment_revision { diff --git a/crates/registry-scheduling/tests/postgres_commitments/attendance.rs b/crates/registry-scheduling/tests/postgres_commitments/attendance.rs index 5a577a35fa..5775cd50d4 100644 --- a/crates/registry-scheduling/tests/postgres_commitments/attendance.rs +++ b/crates/registry-scheduling/tests/postgres_commitments/attendance.rs @@ -865,3 +865,50 @@ async fn attendance_commit_captures_one_minimized_signed_after_event() { } } } + +/// A caller recording attendance on its own booking after the booking left an +/// attendance state is refused with the same 403 as any other attendance +/// refusal. The check the operator's log line names is `visibility`: the +/// target is the caller's own, so it is not an `ownership` refusal. +#[tokio::test] +async fn attendance_on_the_callers_own_closed_booking_is_not_counted_as_ownership() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let (appointment_id, appointment_revision) = + booked(&fx, 300, 440, "attendance-closed-booking").await; + let appointment_uuid = Uuid::parse_str(&appointment_id).expect("an appointment UUID"); + begin_current_test_writer(&fx.admin).await; + fx.admin + .execute( + "UPDATE scheduling_claims SET state='released' WHERE claim_id=$1", + &[&appointment_uuid], + ) + .await + .expect("the booking leaves its attendance states"); + commit_current_test_writer(&fx.admin).await; + let recorder = attendance_token("attendance-desk", &["attendance.record"], pinned_now()); + let captured = CapturedDiagnosticLogs::default(); + let (status, refusal) = put_attendance( + &fx, + &appointment_id, + &recorder, + "attendance-closed", + appointment_revision, + 0, + "arrived", + pinned_now() - TimeDelta::minutes(5), + ) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refusal}"); + assert_eq!(refusal["code"], "operation.not-authorized"); + let lines: Vec = captured + .text() + .lines() + .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) + .filter(|event| event["fields"]["message"] == "request refused") + .collect(); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "visibility"); +} diff --git a/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs b/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs index b6d57359dc..e3db358684 100644 --- a/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs +++ b/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs @@ -637,3 +637,30 @@ async fn a_reads_scope_caller_reading_another_owners_appointment_is_an_ownership assert_eq!(lines.len(), 1); assert_eq!(lines[0]["fields"]["failed_check"], "ownership"); } + +/// A read refused for its scope names the values the operator declared: the +/// claim that carries scopes and the scope the route needs. The scope the +/// token carries never reaches the line, and the answer is the same 403. +#[tokio::test] +async fn a_scope_refusal_line_names_the_declared_scope_and_none_of_the_tokens() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let canary = "canary-token-scope-4d8e"; + let holder = operational_token("principal-canary", canary); + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .get("/v1/offerings", &holder) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{answer}"); + assert_eq!(answer["code"], "profile.not-authorized"); + let rendered = captured.text(); + assert!(!rendered.contains(canary), "{rendered}"); + let lines = refusal_lines(&rendered); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "scope"); + assert_eq!(lines[0]["fields"]["scope_claim"], "registry_scopes"); + assert_eq!(lines[0]["fields"]["required_scope"], "scheduling-read"); + assert!(lines[0]["fields"].get("access_profile").is_none()); +} diff --git a/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx b/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx index 828af7e367..51b0b3dce3 100644 --- a/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx +++ b/docs/site/src/content/docs/reference/apis/registry-scheduling.mdx @@ -166,7 +166,7 @@ exact identity, bounds, signed subjects, and deadline. An inactive, mismatched, unlisted, or incompletely bound grant answers `operation.not-authorized`; an authority or service credential outage, including an unusable authority response, answers `service.unavailable`. On the offline path (`unchecked-final-fifteen-minutes`), an unexpired grant with more than 900 seconds left answers -`grant.lifetime-too-long` once its bounds have matched when it creates a hold or an appointment, and +`grant.lifetime-too-long` once its bounds have matched when it creates a hold, or an appointment without a hold, and `operation.not-authorized` on a request that names an existing hold or appointment, the same answer as an unknown one; an expired grant answers `operation.not-authorized`. Positive answers are not cached, and the complete attempt is limited to ten seconds. No capacity lock is held during the outbound call. diff --git a/docs/site/src/content/docs/reference/scheduling-task-grants.mdx b/docs/site/src/content/docs/reference/scheduling-task-grants.mdx index e44d238f56..40797677c9 100644 --- a/docs/site/src/content/docs/reference/scheduling-task-grants.mdx +++ b/docs/site/src/content/docs/reference/scheduling-task-grants.mdx @@ -130,7 +130,7 @@ No authority is asked, no revocation is observed, and Registry Scheduling accept An unexpired grant with more than 900 seconds remaining answers `grant.lifetime-too-long` when it creates a hold or an appointment, so the caller knows to present a grant that expires sooner. An expired grant answers `operation.not-authorized`. The lifetime answer follows the bounds match: a caller with no grant, or whose grant does not cover the offering, still answers `operation.not-authorized`. A listed authority never answers `grant.lifetime-too-long`. A route that names an existing hold or appointment, which is releasing a hold, confirming a hold, rescheduling, recording attendance, and cancelling, answers `operation.not-authorized` for that grant, the same answer an unknown identifier gives, so the answer never says whether the identifier exists. -The appointment detail read, and every operation on a source-managed or assisted hold or appointment, needs a listed authority and so never answers `grant.lifetime-too-long`. +The appointment detail read needs a listed authority, and so does creating, releasing, confirming, rescheduling or cancelling a source-managed or assisted hold or appointment. None of them answers `grant.lifetime-too-long`. Recording attendance needs no listed authority: it takes the offline path for every appointment. A list of authorities disables that path for every source, including an unlisted one, which is refused even with less than 15 minutes left. The token does not name its authorisation mode, so the final 15 minutes of an originally deferred grant can use the offline path on a deployment that writes the keyword. List the task authorities for every deployment that accepts deferred grants. diff --git a/docs/site/src/content/docs/security/scheduling.mdx b/docs/site/src/content/docs/security/scheduling.mdx index dc76985668..89d1f220a9 100644 --- a/docs/site/src/content/docs/security/scheduling.mdx +++ b/docs/site/src/content/docs/security/scheduling.mdx @@ -54,6 +54,7 @@ callers holding bearer tokens from a configured issuer. ([metrics](../../operate/scheduling/#watch-the-metrics)). The `check` label is a closed set of 45 names, every one published at zero, and no caller value becomes a label. + An answer replayed from a stored receipt is not counted again. Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. diff --git a/products/scheduling/CHANGELOG.md b/products/scheduling/CHANGELOG.md index 539f40568a..2c5a34e4c9 100644 --- a/products/scheduling/CHANGELOG.md +++ b/products/scheduling/CHANGELOG.md @@ -23,8 +23,13 @@ under the same idempotency key is not counted again, because the decision was counted when it was made. A grant or access token that lapses while a commitment waits inside the capacity transaction counts under - `task-grant-expired`, and a hold or appointment that another caller or - source manager holds counts under `ownership`. + `task-grant-expired`, a hold or appointment that another caller or + source manager holds counts under `ownership`, and an appointment that takes + no attendance in its current state counts under `visibility`. +- A `request refused` line for a scope refusal names the scope claim the + deployment configured, the scope the route needs, and the source-busy + profile id when one applies. It never names a scope the token carries. + Answers are unchanged. - A static key set that the shared key set rule refuses is refused at startup under `scheduling.runtime.unreadable-jwks-secret`, with the rule it broke, in place of `scheduling.runtime-dependency.unavailable`. The rule refuses a @@ -55,7 +60,8 @@ so the answer does not say whether the identifier exists. Clients that branch on the code gain the new member in `SchedulingProblemCode`. A client from before this release reports the code as a protocol error with an - unknown outcome, so upgrade the client before shortening grants. + unknown outcome, so upgrade clients before upgrading the server if their + grants can have more than 900 seconds left on the offline path. ## 0.47.0 - 2026-11-21 diff --git a/products/scheduling/contracts/recorded-decisions.yaml b/products/scheduling/contracts/recorded-decisions.yaml index 07601c2b70..8e6bc8bd7f 100644 --- a/products/scheduling/contracts/recorded-decisions.yaml +++ b/products/scheduling/contracts/recorded-decisions.yaml @@ -44,7 +44,6 @@ decisions: - {path: crates/registry-scheduling/tests/postgres_commitments.rs, name: release_hold_refuses_indistinguishably_for_missing_and_unauthorized_holds} - {path: crates/registry-scheduling/tests/postgres_commitments.rs, name: confirm_appointment_refuses_indistinguishably_for_missing_and_unauthorized_holds} - {path: crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs, name: an_id_addressed_route_answers_an_existing_and_an_unknown_id_alike_under_a_long_grant} - - {path: crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs, name: an_id_addressed_route_answers_an_existing_and_an_unknown_id_alike_under_a_long_grant} - id: SCHEDULING-DEC-02 subject: Cancellation never answers policy.changed decision: >- diff --git a/products/scheduling/generated/registry-scheduling.openapi.json b/products/scheduling/generated/registry-scheduling.openapi.json index d8f61ee27f..6da3f7c625 100644 --- a/products/scheduling/generated/registry-scheduling.openapi.json +++ b/products/scheduling/generated/registry-scheduling.openapi.json @@ -3395,7 +3395,7 @@ "x-scheduling-authority": "reads-scope" }, "post": { - "description": "Carries exactly one of hold or admission. Confirming transfers the hold's own reservation: the hold must still be active and unexpired, its policy revision still current, and its owner or source-manager binding must match. Exact-time confirmation also checks current physical supply: the selected resource still exists, carries the required capabilities, is available over the entire occupied interval, and satisfies the offering's current opening coverage. It does not re-run new-request start-grid, lead-time or horizon rules for an already admitted hold. A direct create is evaluated against the live ledger like a hold, and commits instead of reserving. Both branches demand a complete task grant naming the offering's service, location, and appointment.create. Source-managed creation or confirmation instead requires appointment.create-for, the same verified manager binding and fresh online grant status.", + "description": "Carries exactly one of hold or admission. Confirming transfers the hold's own reservation: the hold must still be active and unexpired, its policy revision still current, and its owner or source-manager binding must match. Exact-time confirmation also checks current physical supply: the selected resource still exists, carries the required capabilities, is available over the entire occupied interval, and satisfies the offering's current opening coverage. It does not re-run new-request start-grid, lead-time or horizon rules for an already admitted hold. A direct create is evaluated against the live ledger like a hold, and commits instead of reserving. Both branches demand a complete task grant naming the offering's service, location, and appointment.create. Source-managed creation or confirmation instead requires appointment.create-for, the same verified manager binding and fresh online grant status. Only a direct create answers `grant.lifetime-too-long`. Confirming a hold answers `operation.not-authorized` for the same grant.", "operationId": "createAppointment", "parameters": [ { diff --git a/products/scheduling/scripts/generate_openapi.py b/products/scheduling/scripts/generate_openapi.py index e95e9eaa10..31ffff220f 100644 --- a/products/scheduling/scripts/generate_openapi.py +++ b/products/scheduling/scripts/generate_openapi.py @@ -1121,7 +1121,7 @@ def document(contract: dict) -> dict: status="201", body="CreateAppointmentRequest", idempotency=True, - description="Carries exactly one of hold or admission. Confirming transfers the hold's own reservation: the hold must still be active and unexpired, its policy revision still current, and its owner or source-manager binding must match. Exact-time confirmation also checks current physical supply: the selected resource still exists, carries the required capabilities, is available over the entire occupied interval, and satisfies the offering's current opening coverage. It does not re-run new-request start-grid, lead-time or horizon rules for an already admitted hold. A direct create is evaluated against the live ledger like a hold, and commits instead of reserving. Both branches demand a complete task grant naming the offering's service, location, and appointment.create. Source-managed creation or confirmation instead requires appointment.create-for, the same verified manager binding and fresh online grant status.", + description="Carries exactly one of hold or admission. Confirming transfers the hold's own reservation: the hold must still be active and unexpired, its policy revision still current, and its owner or source-manager binding must match. Exact-time confirmation also checks current physical supply: the selected resource still exists, carries the required capabilities, is available over the entire occupied interval, and satisfies the offering's current opening coverage. It does not re-run new-request start-grid, lead-time or horizon rules for an already admitted hold. A direct create is evaluated against the live ledger like a hold, and commits instead of reserving. Both branches demand a complete task grant naming the offering's service, location, and appointment.create. Source-managed creation or confirmation instead requires appointment.create-for, the same verified manager binding and fresh online grant status. Only a direct create answers `grant.lifetime-too-long`. Confirming a hold answers `operation.not-authorized` for the same grant.", )}, "/v1/appointments/receipt": {"post": operation( "Read the original appointment receipt", @@ -1577,7 +1577,10 @@ def produced_problem_codes(repository_root: Path, variants: dict[str, str]) -> s # The refusal codes are answered through `RefusalCode::problem`. The # classification after it names every code and so says nothing about # which are produced. - refusals = production_source(repository_root, REFUSAL_SOURCE).split("pub const fn of", 1)[0] + refusal_source = production_source(repository_root, REFUSAL_SOURCE) + if "pub const fn of" not in refusal_source: + raise ValueError("Rust function is missing: RefusalCode::of") + refusals = refusal_source.split("pub const fn of", 1)[0] produced |= { variants[name] for name in re.findall(r"ProblemCode::([A-Z][A-Za-z0-9]*)", refusals) } @@ -1891,7 +1894,7 @@ def verify_source(repository_root: Path) -> None: "CommitError::KeyReused => ProblemCode::IdempotencyKeyReused", "CommitError::KeyExpired => ProblemCode::IdempotencyExpired", "CommitError::HoldCeiling => ProblemCode::CapacityExhausted", - "CommitError::Unauthorized | CommitError::GrantLapsed => ProblemCode::OperationNotAuthorized", + "CommitError::Unauthorized | CommitError::NotAttendable | CommitError::GrantLapsed => {\n ProblemCode::OperationNotAuthorized\n }", "CommitError::RevisionMismatch => ProblemCode::RevisionMismatch", "CommitError::CutoffPassed => ProblemCode::CancellationCutoffPassed", ): diff --git a/products/scheduling/scripts/test_generate_openapi.py b/products/scheduling/scripts/test_generate_openapi.py index 3152d876b8..bf76780c5c 100644 --- a/products/scheduling/scripts/test_generate_openapi.py +++ b/products/scheduling/scripts/test_generate_openapi.py @@ -316,6 +316,22 @@ def test_only_a_reachable_code_is_documented_as_an_answer(self) -> None: self.assertEqual(set(), set(GENERATOR.UNPRODUCED_PROBLEMS) & produced) self.assertIn("resource.unavailable", produced) + def test_a_missing_refusal_classification_marker_stops_the_generator(self) -> None: + real = GENERATOR.production_source + + def without_marker(root: Path, relative: str) -> str: + source = real(root, relative) + if relative == GENERATOR.REFUSAL_SOURCE: + return source.replace("pub const fn of", "pub const fn sorted") + return source + + GENERATOR.production_source = without_marker + try: + with self.assertRaisesRegex(ValueError, "RefusalCode::of"): + GENERATOR.produced_problem_codes(ROOT, self.variants) + finally: + GENERATOR.production_source = real + def test_every_route_is_described_by_exactly_one_operation(self) -> None: documented = { (method.upper(), path) From c41b42640c09da5a58665646e173b69fc5d9f749 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:29:07 +0100 Subject: [PATCH 053/136] fix: name declared scope on Render, Adapter and MCP edge scope refusals A scope refusal line on Render, the MCP edge, the Adapter facade and the Adapter payment routes names the configured scope claim, the required scope and, where one applies, the access profile or payment connection. Nothing the caller's token carried is written, and no answer changes. Render, the Adapter facade, the payment routes and the Adapter job hook listener catch a 401 or 403 built without its failed check in a debug build and log it. The MCP edge's admit fault line counts the lines it held back. One shared function makes a facade path concrete for authoring checks, compile and the engine, so a record-type placeholder inside a segment is substituted everywhere the same way. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-core/src/checks.rs | 10 +- crates/registry-adapter-core/src/profile.rs | 26 ++++ .../src/effective_contract.rs | 5 +- crates/registry-adapter-engine/src/load.rs | 10 +- .../registry-adapter-job/src/hook_ingress.rs | 53 ++++++- crates/registry-adapter/src/facade.rs | 146 +++++++++++++++++- crates/registry-adapter/src/metrics.rs | 77 ++++++++- crates/registry-adapter/src/payments/http.rs | 52 ++++++- .../registry-adapter/src/payments/service.rs | 33 +++- .../src/compile/document.rs | 39 +++-- crates/registry-mcp-edge/src/inbound.rs | 50 ++++-- .../src/inbound/refusal_tests.rs | 63 +++++++- crates/registry-render/src/auth.rs | 3 + crates/registry-render/src/server.rs | 97 ++++++++++-- products/adapter/CHANGELOG.md | 7 + products/platform/CHANGELOG.md | 3 + products/render/CHANGELOG.md | 3 + 17 files changed, 601 insertions(+), 76 deletions(-) diff --git a/crates/registry-adapter-core/src/checks.rs b/crates/registry-adapter-core/src/checks.rs index bb2bd8438d..6d0a9360eb 100644 --- a/crates/registry-adapter-core/src/checks.rs +++ b/crates/registry-adapter-core/src/checks.rs @@ -4751,8 +4751,9 @@ pub fn check_project(workspace: &Workspace<'_>) -> Vec { // itself, so a binding whose concrete path is one of them would be // advertised and never served. if let Some(operation) = operation { - let concrete = operation.path.replace( - &format!("{{{}}}", operation.record_type_parameter.as_str()), + let concrete = crate::concrete_facade_path( + &operation.path, + operation.record_type_parameter.as_str(), binding.record_type.as_str(), ); if [ @@ -5934,8 +5935,9 @@ fn async_status_path_collision_checks(workspace: &Workspace<'_>) -> Vec Deserialize<'de> for ProfileOperation { } } +/// The facade path of one bound operation: the record type in place of the +/// record-type parameter's placeholder, wherever the placeholder sits in the +/// path. The listener, the effective contract and the checks read the path +/// through this one rule. +#[must_use] +pub fn concrete_facade_path(path: &str, record_type_parameter: &str, record_type: &str) -> String { + path.replace(&format!("{{{record_type_parameter}}}"), record_type) +} + impl ProfileOperation { /// Whether the operation only reads: a GET, or a POST declaring /// `readOnly`. @@ -603,6 +612,23 @@ fn default_success_status() -> registry_platform_yaml::BoundedU32<200, 299> { #[cfg(test)] mod tests { + #[test] + fn the_concrete_facade_path_substitutes_a_whole_or_partial_segment() { + use super::concrete_facade_path; + assert_eq!( + concrete_facade_path("/v1/{type}/{id}", "type", "case"), + "/v1/case/{id}" + ); + assert_eq!( + concrete_facade_path("/v1/{type}.json", "type", "case"), + "/v1/case.json" + ); + assert_eq!( + concrete_facade_path("/v1/cases", "type", "case"), + "/v1/cases" + ); + } + use super::*; #[test] diff --git a/crates/registry-adapter-engine/src/effective_contract.rs b/crates/registry-adapter-engine/src/effective_contract.rs index 46824c148b..9bc611ab47 100644 --- a/crates/registry-adapter-engine/src/effective_contract.rs +++ b/crates/registry-adapter-engine/src/effective_contract.rs @@ -316,8 +316,9 @@ fn effective_operation( .operations .get(&served.operation) .ok_or_else(|| ContractError::MissingOperation(served.operation.clone()))?; - let concrete_path = served.method_path.replace( - &format!("{{{}}}", served.record_type_parameter), + let concrete_path = registry_adapter_core::concrete_facade_path( + &served.method_path, + &served.record_type_parameter, &served.record_type, ); let target = served.target_contract.as_ref(); diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index acb31614f2..30312b003a 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -341,8 +341,9 @@ fn path_conflict(served: &[ServedOperation], candidate: &ServedOperation) -> Opt /// The facade path a served operation answers, with its record type in /// place of the record-type parameter. fn concrete_path(operation: &ServedOperation) -> String { - operation.method_path.replace( - &format!("{{{}}}", operation.record_type_parameter), + registry_adapter_core::concrete_facade_path( + &operation.method_path, + &operation.record_type_parameter, &operation.record_type, ) } @@ -1226,8 +1227,9 @@ fn compile_binding( "the binding names no profile operation", ) })?; - let concrete_method_path = operation.path.replace( - &format!("{{{}}}", operation.record_type_parameter.as_str()), + let concrete_method_path = registry_adapter_core::concrete_facade_path( + &operation.path, + operation.record_type_parameter.as_str(), binding.record_type.as_str(), ); if [ diff --git a/crates/registry-adapter-job/src/hook_ingress.rs b/crates/registry-adapter-job/src/hook_ingress.rs index 2bfd6a8cb2..845d2ce49a 100644 --- a/crates/registry-adapter-job/src/hook_ingress.rs +++ b/crates/registry-adapter-job/src/hook_ingress.rs @@ -481,12 +481,9 @@ async fn answer_hook( ); } if let Err(check) = authenticated(request.headers(), &source.credential) { - return noted( - response( - StatusCode::UNAUTHORIZED, - "adapter.job.hook-unauthenticated", - None, - ), + return refusal( + StatusCode::UNAUTHORIZED, + "adapter.job.hook-unauthenticated", check, ); } @@ -588,7 +585,28 @@ async fn discard_body(body: Body) -> Result { Ok(total) } +/// A refused caller's answer, carrying the check that refused it. Every 401 +/// or 403 is built here. +fn refusal(status: StatusCode, code: &'static str, check: FailedCheck) -> Response { + noted(answer(status, code, None), check) +} + +/// An answer that is not a refusal of the caller. A refusal status that +/// arrives here has no check to count, which a debug build refuses outright +/// and a release build logs. fn response(status: StatusCode, code: &'static str, retry_after: Option) -> Response { + if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + status = status.as_u16(), + code, + "a refusal was answered without its failed check" + ); + } + answer(status, code, retry_after) +} + +fn answer(status: StatusCode, code: &'static str, retry_after: Option) -> Response { let body = match code { "started" => r#"{"status":"started"}"#, "joined" => r#"{"status":"joined"}"#, @@ -628,6 +646,29 @@ mod tests { use std::io::Write as _; use std::os::unix::fs::PermissionsExt as _; + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn an_unauthorized_answer_without_its_check_is_not_built() { + let _ = response( + StatusCode::UNAUTHORIZED, + "adapter.job.hook-unauthenticated", + None, + ); + } + + #[test] + fn an_unauthorized_answer_carries_its_check_and_challenge() { + let answer = refusal( + StatusCode::UNAUTHORIZED, + "adapter.job.hook-unauthenticated", + FailedCheck::SharedSecret, + ); + assert_eq!(answer.status(), StatusCode::UNAUTHORIZED); + assert!(answer.headers().contains_key(WWW_AUTHENTICATE)); + assert!(answer.extensions().get::().is_some()); + } + async fn test_server( path: &str, burst: u32, diff --git a/crates/registry-adapter/src/facade.rs b/crates/registry-adapter/src/facade.rs index 4072562fca..99b55ea458 100644 --- a/crates/registry-adapter/src/facade.rs +++ b/crates/registry-adapter/src/facade.rs @@ -68,7 +68,7 @@ use crate::idempotent::{ }; use crate::journal::{self, JournalEvent}; use crate::serve::{Authenticator, Caller, CallerRefusal}; -use registry_platform_authcommon::{FailedCheck, RefusalNote}; +use registry_platform_authcommon::{DeclaredScope, FailedCheck, RefusalNote}; const REQUEST_ID_HEADER: &str = "x-registry-request-id"; const WRITE_REQUEST_DIGEST_DOMAIN: &[u8] = b"registry-adapter:write-request:v2\0"; @@ -647,7 +647,7 @@ async fn answer_async_status( metadata.profile_operation(), metadata.record_type(), ) { - return refuse_call( + let response = refuse_call( state, operation, &caller, @@ -658,6 +658,13 @@ async fn answer_async_status( Some(check), ) .await; + return with_declared_scope( + response, + check, + &state.loaded.project, + metadata.profile_operation(), + metadata.record_type(), + ); } let event = |kind: &'static str, detail: Option, at: SystemTime| { ( @@ -1244,7 +1251,7 @@ async fn answer( operation.operation.as_str(), operation.record_type.as_str(), ) { - return refuse_call( + let response = refuse_call( state, operation, &caller, @@ -1255,6 +1262,13 @@ async fn answer( Some(check), ) .await; + return with_declared_scope( + response, + check, + &state.loaded.project, + operation.operation.as_str(), + operation.record_type.as_str(), + ); } if !effective_contract_matches(headers, &state.effective_contract.digest) { return refuse_contract_pin(state, operation, &caller, &request_id).await; @@ -3480,6 +3494,74 @@ fn bearer_token(headers: &HeaderMap) -> Result<&str, FailedCheck> { Ok(token) } +/// Guard for every answer built from a status and an optional failed check: +/// a 401 or 403 names the check that refused the caller. One that arrives +/// without it has nothing to count, which a debug build refuses outright and a +/// release build logs. +pub(crate) fn require_refusal_check(status: StatusCode, check: Option) { + if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) && check.is_none() { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + status = status.as_u16(), + "a refusal was answered without its failed check" + ); + } +} + +/// The claim the verifier reads a caller's scopes from. +pub(crate) const SCOPE_CLAIM: &str = "scope"; + +/// The values the operator declared for a scope refusal of the operation on +/// the record type: the scope claim, and the access profile that names the +/// operation and record type with the scopes it requires. When no profile or +/// more than one names them, only the claim is declared. Nothing here comes +/// from the caller's token. +fn declared_scope(project: &AdapterProject, operation: &str, record_type: &str) -> DeclaredScope { + let mut naming = project.access_profiles.iter().filter(|profile| { + profile.operations.iter().any(|id| id.as_str() == operation) + && profile + .record_types + .iter() + .any(|name| name.as_str() == record_type) + }); + let declared = DeclaredScope::new(SCOPE_CLAIM); + match (naming.next(), naming.next()) { + (Some(profile), None) => { + let declared = declared.with_access_profile(profile.id.as_str()); + if profile.scopes.is_empty() { + declared + } else { + declared.with_required_scope( + profile + .scopes + .iter() + .map(|scope| scope.as_str()) + .collect::>() + .join(" "), + ) + } + } + _ => declared, + } +} + +/// Attach the declared scope values to a scope refusal, for the recording +/// layer. Any other refusal is returned as it is. +fn with_declared_scope( + mut response: Response, + check: FailedCheck, + project: &AdapterProject, + operation: &str, + record_type: &str, +) -> Response { + if check == FailedCheck::Scope { + response + .extensions_mut() + .insert(declared_scope(project, operation, record_type)); + } + response +} + /// Mark a response as the refusal of `check`, for the recording layer. fn noted(mut response: Response, check: FailedCheck) -> Response { response.extensions_mut().insert(RefusalNote::new(check)); @@ -4657,6 +4739,7 @@ async fn refuse_call( status: StatusCode, check: Option, ) -> Response { + require_refusal_check(status, check); let profile = state.loaded.problems(); tracing::warn!( class = class.class(), @@ -5311,6 +5394,63 @@ mod generated_properties; mod tests { use super::*; + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn a_forbidden_answer_without_its_check_is_not_built() { + require_refusal_check(StatusCode::FORBIDDEN, None); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn an_unauthorized_answer_without_its_check_is_not_built() { + require_refusal_check(StatusCode::UNAUTHORIZED, None); + } + + #[test] + fn answers_with_a_check_or_that_are_not_caller_refusals_are_built() { + require_refusal_check(StatusCode::FORBIDDEN, Some(FailedCheck::Scope)); + require_refusal_check(StatusCode::NOT_FOUND, None); + require_refusal_check(StatusCode::NOT_ACCEPTABLE, None); + } + + #[test] + fn a_scope_refusal_declares_the_claim_and_the_profile_that_names_the_operation() { + let project = example_project(json!(["records.read"])); + let named = declared_scope(&project, "records-get", "person"); + assert_eq!(named.scope_claim(), "scope"); + assert_eq!(named.required_scope(), Some("records.read")); + assert_eq!(named.access_profile(), Some("records-reader")); + // No profile names the operation, so only the claim is declared. + let unnamed = declared_scope(&project, "records-purge", "person"); + assert_eq!(unnamed.scope_claim(), "scope"); + assert_eq!(unnamed.required_scope(), None); + assert_eq!(unnamed.access_profile(), None); + } + + #[test] + fn only_a_scope_refusal_carries_declared_values() { + let project = example_project(json!(["records.read"])); + let answer = || StatusCode::FORBIDDEN.into_response(); + let scope = with_declared_scope( + answer(), + FailedCheck::Scope, + &project, + "records-get", + "person", + ); + assert!(scope.extensions().get::().is_some()); + let operation = with_declared_scope( + answer(), + FailedCheck::Operation, + &project, + "records-get", + "person", + ); + assert!(operation.extensions().get::().is_none()); + } + fn lookup_filters(value: &str) -> serde_json::Map { json!({"selector": "by-record-id", "values": {"record-id": value}}) .as_object() diff --git a/crates/registry-adapter/src/metrics.rs b/crates/registry-adapter/src/metrics.rs index 24269f5d15..7b9428e703 100644 --- a/crates/registry-adapter/src/metrics.rs +++ b/crates/registry-adapter/src/metrics.rs @@ -31,7 +31,7 @@ use axum::response::{IntoResponse, Response}; use axum::routing::get; use axum::Router; use registry_adapter_core::ErrorClass; -use registry_platform_authcommon::{RefusalNote, RefusalRecorder}; +use registry_platform_authcommon::{DeclaredScope, RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, CONTENT_TYPE as METRICS_CONTENT_TYPE, }; @@ -254,7 +254,8 @@ pub async fn record_refusals( ) -> Response { let response = next.run(request).await; if let Some(note) = response.extensions().get::() { - registry_platform_authcommon::record_refusal!(recorder, *note); + let declared = response.extensions().get::(); + registry_platform_authcommon::record_refusal!(recorder, *note, declared = declared); } response } @@ -400,6 +401,78 @@ mod tests { assert_eq!(declared, registry_platform_authcommon::FailedCheck::COUNT); } + /// The refusal line a scope refusal writes, driven through the recording + /// layer with the scope values the answer carries. + async fn refusal_line(check: registry_platform_authcommon::FailedCheck) -> String { + use registry_platform_testing::CapturedDiagnosticLogs; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + let recorder = Arc::new(RefusalRecorder::new("adapter_test").expect("recorder")); + let app = Router::new() + .route( + "/", + get(move || async move { + let mut response = StatusCode::FORBIDDEN.into_response(); + response.extensions_mut().insert(RefusalNote::new(check)); + response.extensions_mut().insert( + DeclaredScope::new("scope") + .with_required_scope("records.read") + .with_access_profile("records-reader"), + ); + response + }), + ) + .layer(axum::middleware::from_fn_with_state( + recorder, + record_refusals, + )); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("a loopback test listener"); + let address = listener.local_addr().expect("the bound address"); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + let logs = CapturedDiagnosticLogs::default(); + let _guard = tracing::dispatcher::set_default(&logs.subscriber()); + let mut stream = tokio::net::TcpStream::connect(address) + .await + .expect("connect"); + stream + .write_all( + b"GET / HTTP/1.1\r\nhost: test\r\nauthorization: Bearer canary-token-scope\r\nconnection: close\r\n\r\n", + ) + .await + .expect("send"); + let mut answer = Vec::new(); + stream.read_to_end(&mut answer).await.expect("read"); + assert!(answer.starts_with(b"HTTP/1.1 403")); + logs.text() + } + + #[tokio::test] + async fn a_scope_refusal_line_names_the_declared_values_and_no_token_value() { + let text = refusal_line(registry_platform_authcommon::FailedCheck::Scope).await; + assert!(text.contains("\"scope_claim\":\"scope\""), "{text}"); + assert!( + text.contains("\"required_scope\":\"records.read\""), + "{text}" + ); + assert!( + text.contains("\"access_profile\":\"records-reader\""), + "{text}" + ); + assert!(!text.contains("canary-token-scope"), "{text}"); + } + + #[tokio::test] + async fn a_refusal_other_than_scope_names_no_declared_values() { + let text = refusal_line(registry_platform_authcommon::FailedCheck::Operation).await; + assert!(text.contains("request refused"), "{text}"); + assert!(!text.contains("scope_claim"), "{text}"); + assert!(!text.contains("required_scope"), "{text}"); + } + fn text_has(metrics: &Metrics, line: &str) -> bool { metrics.render().lines().any(|found| found == line) } diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index 9f9b52cd85..d3898bb1c6 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -33,7 +33,7 @@ use registry_payment_protocol::{ PaymentProblem, PaymentProblemCode as Error, ProviderConfirmation, RecordProviderConfirmation, RecordReceipt, RequestCollection, RequestDisbursement, }; -use registry_platform_authcommon::{FailedCheck, RefusalNote}; +use registry_platform_authcommon::{DeclaredScope, FailedCheck, RefusalNote}; use registry_platform_config::{ RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, SecretResolver, }; @@ -689,9 +689,9 @@ async fn g2p_connection<'a>( FailedCheck::RequesterClient, )) } else if !caller.scopes.contains(&connection.required_scope) { - Err(PaymentFailure::refused( - Error::Forbidden, - FailedCheck::Scope, + Err(PaymentFailure::scope_refused( + &connection.id, + &connection.required_scope, )) } else { Ok(connection) @@ -1010,15 +1010,21 @@ fn audited_attempt(result: &Result) -> Option struct HttpError { code: Error, check: Option, + declared: Option, } impl HttpError { fn plain(code: Error) -> Self { - Self { code, check: None } + Self { + code, + check: None, + declared: None, + } } fn refused(code: Error, check: FailedCheck) -> Self { Self { code, check: Some(check), + declared: None, } } } @@ -1027,6 +1033,7 @@ impl From for HttpError { Self { code: failure.code, check: failure.check, + declared: failure.declared, } } } @@ -1035,6 +1042,7 @@ impl IntoResponse for HttpError { let problem = PaymentProblem::from(self.code); let status = StatusCode::from_u16(problem.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + crate::facade::require_refusal_check(status, self.check); let mut response = (status, Json(problem)).into_response(); response.headers_mut().insert( "content-type", @@ -1043,6 +1051,9 @@ impl IntoResponse for HttpError { if let Some(check) = self.check { response.extensions_mut().insert(RefusalNote::new(check)); } + if let Some(declared) = self.declared { + response.extensions_mut().insert(declared); + } headers(response) } } @@ -1076,6 +1087,37 @@ mod refusal_tests; mod tests { use super::*; + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn a_forbidden_payment_answer_without_its_check_is_not_built() { + let _ = HttpError::plain(Error::Forbidden).into_response(); + } + + #[test] + fn a_payment_scope_refusal_carries_the_connection_and_its_declared_scope() { + let response = HttpError::from(PaymentFailure::scope_refused( + "mifos-main", + "payments.write", + )) + .into_response(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let declared = response + .extensions() + .get::() + .expect("the declared scope values"); + assert_eq!(declared.scope_claim(), "scope"); + assert_eq!(declared.required_scope(), Some("payments.write")); + assert_eq!(declared.access_profile(), Some("mifos-main")); + } + + #[test] + fn a_forbidden_payment_answer_carries_its_check() { + let response = HttpError::refused(Error::Forbidden, FailedCheck::Scope).into_response(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(response.extensions().get::().is_some()); + } + #[test] fn payment_body_requires_a_closed_json_object() { let mut headers = HeaderMap::new(); diff --git a/crates/registry-adapter/src/payments/service.rs b/crates/registry-adapter/src/payments/service.rs index d6a8b9515c..e7c364a5af 100644 --- a/crates/registry-adapter/src/payments/service.rs +++ b/crates/registry-adapter/src/payments/service.rs @@ -25,7 +25,7 @@ use registry_payment_protocol::{ RegistryReceipt, RequestCollection, }; use registry_payment_simulator_connector::{ConnectorError, Observation, SimulatorClient}; -use registry_platform_authcommon::FailedCheck; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_config::SecretResolver; use registry_platform_httputil::client::BearerToken; use registry_platform_httputil::{read_bounded, validate_response_headers, ServiceBaseUrl}; @@ -641,9 +641,9 @@ impl PaymentService { )); } if !caller.scopes.contains(&connection.required_scope) { - return Err(PaymentFailure::refused( - Error::Forbidden, - FailedCheck::Scope, + return Err(PaymentFailure::scope_refused( + &connection.id, + &connection.required_scope, )); } Ok(connection) @@ -1150,10 +1150,13 @@ fn validate_key(key: &str) -> Result<(), Error> { } /// A payment error and, when the caller was refused, the check it failed. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct PaymentFailure { pub code: Error, pub check: Option, + /// For a scope refusal, the values the operator declared. Never read from + /// the caller's token. + pub declared: Option, } impl PaymentFailure { @@ -1161,6 +1164,20 @@ impl PaymentFailure { Self { code, check: Some(check), + declared: None, + } + } + + /// A caller that lacks the scope the connection requires. The recording + /// layer names the connection and its declared scope on the log line. + pub(crate) fn scope_refused(connection_id: &str, required_scope: &str) -> Self { + Self { + declared: Some( + DeclaredScope::new(crate::facade::SCOPE_CLAIM) + .with_required_scope(required_scope) + .with_access_profile(connection_id), + ), + ..Self::refused(Error::Forbidden, FailedCheck::Scope) } } @@ -1177,7 +1194,11 @@ impl PaymentFailure { impl From for PaymentFailure { fn from(code: Error) -> Self { - Self { code, check: None } + Self { + code, + check: None, + declared: None, + } } } diff --git a/crates/registry-adapterctl/src/compile/document.rs b/crates/registry-adapterctl/src/compile/document.rs index 9684f0ef1b..e2729292ff 100644 --- a/crates/registry-adapterctl/src/compile/document.rs +++ b/crates/registry-adapterctl/src/compile/document.rs @@ -504,23 +504,15 @@ fn openapi_method(method: HttpMethod) -> String { } /// The concrete path of one bound operation: the record type substituted -/// into the record-type parameter's whole segment, every other segment -/// kept as declared. +/// into the record-type parameter's placeholder by the rule the listener and +/// the checks share, every other part kept as declared. fn concrete_path(path: &str, parameter: Option<&str>, record_type: &str) -> String { - let Some(parameter) = parameter else { - return path.to_owned(); - }; - let template = format!("{{{parameter}}}"); - path.split('/') - .map(|segment| { - if segment == template { - record_type.to_owned() - } else { - segment.to_owned() - } - }) - .collect::>() - .join("/") + match parameter { + Some(parameter) => { + registry_adapter_core::concrete_facade_path(path, parameter, record_type) + } + None => path.to_owned(), + } } /// The operation's OpenAPI parameters: the remaining declared path @@ -1321,6 +1313,21 @@ mod tests { ); } + /// The compiled path is the one the listener serves, whether the + /// record-type placeholder fills a segment or sits inside one. + #[test] + fn the_concrete_path_follows_the_shared_substitution_rule() { + assert_eq!( + concrete_path("/v1/{type}/{id}", Some("type"), "case"), + "/v1/case/{id}" + ); + assert_eq!( + concrete_path("/v1/{type}.json", Some("type"), "case"), + "/v1/case.json" + ); + assert_eq!(concrete_path("/v1/{type}", None, "case"), "/v1/{type}"); + } + /// Two bindings whose concrete paths collide refuse the assembly with /// the collision finding. #[test] diff --git a/crates/registry-mcp-edge/src/inbound.rs b/crates/registry-mcp-edge/src/inbound.rs index 31a6b30fa4..682185d760 100644 --- a/crates/registry-mcp-edge/src/inbound.rs +++ b/crates/registry-mcp-edge/src/inbound.rs @@ -16,7 +16,8 @@ use axum::{ }; use registry_platform_audit::AuditKeyHasher; use registry_platform_authcommon::{ - parse_bearer_token, record_refusal, BearerParseError, FailedCheck, RefusalNote, RefusalRecorder, + parse_bearer_token, record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, + RefusalRecorder, }; use registry_platform_httputil::loopback::loopback_host; pub use registry_platform_oidc::AccessTokenAlgorithm; @@ -260,8 +261,17 @@ pub struct ResourceServer { scope_challenge: String, metadata: Value, refusals: Arc, - /// When the gateway last logged that it could not admit a request. - admit_fault_logged: Mutex>, + /// When the gateway last logged that it could not admit a request, and + /// how many requests failed the same way since. + admit_fault_logged: Mutex, + /// The configured claim and scopes a scope refusal line names. + declared_scope: DeclaredScope, +} + +#[derive(Default)] +struct AdmitFaultLog { + logged: Option, + suppressed: u64, } #[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] @@ -319,7 +329,9 @@ impl ResourceServer { scope_challenge, metadata, refusals, - admit_fault_logged: Mutex::new(None), + admit_fault_logged: Mutex::new(AdmitFaultLog::default()), + declared_scope: DeclaredScope::new(&options.scope_claim) + .with_required_scope(options.required_scopes.join(" ")), }) } @@ -402,31 +414,39 @@ impl ResourceServer { /// Counts and logs the refusal, then builds its answer. pub(crate) fn refuse(&self, refusal: Refusal) -> Response { match refusal.failed_check() { - Some(check) => record_refusal!(self.refusals, RefusalNote::new(check)), + Some(check) => record_refusal!( + self.refusals, + RefusalNote::new(check), + declared = Some(&self.declared_scope) + ), // The gateway could not derive a pseudonym or run its limiter. // That is a fault of this service, not a check a caller failed. None => { - if self.admit_fault_due(Instant::now()) { - tracing::error!("the gateway could not admit a request"); + if let Some(suppressed) = self.admit_fault_due(Instant::now()) { + tracing::error!(suppressed, "the gateway could not admit a request"); } } } self.refusal_response(refusal) } - /// True at most once per `ADMIT_FAULT_LOG_WINDOW`, so a limiter that has - /// reached its capacity cannot write a line for every request. - fn admit_fault_due(&self, now: Instant) -> bool { - let mut last = self + /// `Some` at most once per `ADMIT_FAULT_LOG_WINDOW`, so a limiter that has + /// reached its capacity cannot write a line for every request. The value + /// is how many requests failed the same way since the last line. + fn admit_fault_due(&self, now: Instant) -> Option { + let mut log = self .admit_fault_logged .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if last.is_some_and(|logged| now.saturating_duration_since(logged) < ADMIT_FAULT_LOG_WINDOW) + if log + .logged + .is_some_and(|logged| now.saturating_duration_since(logged) < ADMIT_FAULT_LOG_WINDOW) { - return false; + log.suppressed = log.suppressed.saturating_add(1); + return None; } - *last = Some(now); - true + log.logged = Some(now); + Some(std::mem::take(&mut log.suppressed)) } fn refusal_response(&self, refusal: Refusal) -> Response { diff --git a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs index 70b9d0ba3b..0943dc52a8 100644 --- a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs +++ b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs @@ -201,13 +201,14 @@ impl Run { (app, server): &(Router, Arc), headers: Headers, ) { - let answer = summarise( + let mut answer = summarise( app.clone() .oneshot(request(headers)) .await .expect("response"), ) .await; + settle_retry_after(&mut answer); self.record(name, server, answer); } @@ -228,6 +229,22 @@ impl Run { } } +/// The limiter holds one request per minute, so the delay it advertises is +/// the minute less however long the fixture took between its two requests, +/// rounded up. Any delay from one to sixty seconds is recorded as sixty so a +/// slow runner does not change the frozen answer. +fn settle_retry_after(answer: &mut Value) { + let Some(header) = answer["headers"].get_mut("retry-after") else { + return; + }; + let seconds: u64 = header + .as_str() + .and_then(|text| text.parse().ok()) + .expect("retry-after is whole seconds"); + assert!((1..=60).contains(&seconds), "retry-after {seconds}"); + *header = Value::from("60"); +} + /// One name per refusal the edge can answer, with the answer it gives. async fn drive() -> Run { let auth = authorization().await; @@ -475,6 +492,12 @@ async fn a_refusal_writes_one_line_with_its_check_and_no_caller_value() { .collect(); assert_eq!(lines.len(), 1, "{text}"); assert!(lines[0].contains("\"failed_check\":\"scope\""), "{text}"); + // The line names what the operator declared, never the token's scopes. + assert!(lines[0].contains("\"scope_claim\":\"scope\""), "{text}"); + assert!( + lines[0].contains(&format!("\"required_scope\":\"{SCOPE}\"")), + "{text}" + ); for canary in [token.as_str(), "citizen-canary", CLIENT, "openid"] { assert!(!text.contains(canary), "{canary} reached the log: {text}"); } @@ -485,7 +508,39 @@ async fn the_admit_fault_line_is_due_once_per_window() { let auth = authorization().await; let (_, server) = application(&auth, auth.jwks_uri(), 100); let start = std::time::Instant::now(); - assert!(server.admit_fault_due(start)); - assert!(!server.admit_fault_due(start + Duration::from_secs(59))); - assert!(server.admit_fault_due(start + Duration::from_secs(61))); + assert_eq!(server.admit_fault_due(start), Some(0)); + assert_eq!( + server.admit_fault_due(start + Duration::from_secs(30)), + None + ); + assert_eq!( + server.admit_fault_due(start + Duration::from_secs(59)), + None + ); + assert_eq!( + server.admit_fault_due(start + Duration::from_secs(61)), + Some(2) + ); + assert_eq!( + server.admit_fault_due(start + Duration::from_secs(130)), + Some(0) + ); +} + +#[test] +fn a_retry_after_from_one_to_sixty_seconds_is_frozen_as_sixty() { + for seconds in ["1", "59", "60"] { + let mut answer = json!({"headers": {"retry-after": seconds}}); + settle_retry_after(&mut answer); + assert_eq!(answer["headers"]["retry-after"], "60"); + } + let mut none = json!({"headers": {}}); + settle_retry_after(&mut none); + assert_eq!(none, json!({"headers": {}})); +} + +#[test] +#[should_panic(expected = "retry-after 61")] +fn a_retry_after_beyond_the_refill_period_is_refused() { + settle_retry_after(&mut json!({"headers": {"retry-after": "61"}})); } diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index f84f3e7718..a59ae79ec5 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -116,6 +116,9 @@ fn verifier_failure(error: OidcError) -> AuthenticationError { } } +/// The claim the verifier reads a token's scopes from. +pub(crate) const SCOPE_CLAIM: &str = "scope"; + /// The scope the render and document routes require. pub(crate) const RENDER_SCOPE: &str = "render:render"; /// The scope the seal route requires. Neither scope implies the other: a diff --git a/crates/registry-render/src/server.rs b/crates/registry-render/src/server.rs index 510062c135..9ede4a4af9 100644 --- a/crates/registry-render/src/server.rs +++ b/crates/registry-render/src/server.rs @@ -28,14 +28,14 @@ use serde::{Deserialize, Serialize}; use subtle::ConstantTimeEq; use registry_platform_authcommon::{ - parse_bearer_token, validate_api_key_entropy, BearerParseError, FailedCheck, RefusalNote, - RefusalRecorder, MIN_API_KEY_ENTROPY_BYTES, + parse_bearer_token, validate_api_key_entropy, BearerParseError, DeclaredScope, FailedCheck, + RefusalNote, RefusalRecorder, MIN_API_KEY_ENTROPY_BYTES, }; use registry_platform_canonical_json::parse_json_preserving_integers; use registry_platform_httpsec::{request_body_limit, security_headers, CspBuilder}; use crate::audit::{RenderAudit, RenderAuditEvent}; -use crate::auth::{RENDER_SCOPE, SEAL_SCOPE}; +use crate::auth::{RENDER_SCOPE, SCOPE_CLAIM, SEAL_SCOPE}; use crate::bundle::Bundle; use crate::hash::sha256_label; use crate::metrics::{Metrics, Operation, METRICS_PATH}; @@ -506,7 +506,12 @@ async fn require_bearer( problem = problem.with_public_detail(SEAL_SCOPE_GUIDANCE); } let (path, headers) = (request.uri().path(), request.headers()); - return refuse_access(&service, path, headers, &problem, &caller, check).await; + let mut response = + refuse_access(&service, path, headers, &problem, &caller, check).await; + if check == FailedCheck::Scope { + response.extensions_mut().insert(declared_scope(scope)); + } + return response; } }; // The legacy API key never seals. The runtime already refuses a signing @@ -559,11 +564,18 @@ async fn refuse_access( /// A refusal answer with the check that refused the caller in its response /// extensions, which are never serialized. fn refusal_response(problem: &RenderProblem, trace: Option<&str>, check: FailedCheck) -> Response { - let mut response = problem_response(problem, trace); + let mut response = problem_answer(problem, trace); response.extensions_mut().insert(RefusalNote::new(check)); response } +/// The values the operator declared for a scope refusal: the claim Render +/// reads scopes from and the scope the route requires. Nothing here comes +/// from the caller's token. +fn declared_scope(required_scope: &str) -> DeclaredScope { + DeclaredScope::new(SCOPE_CLAIM).with_required_scope(required_scope) +} + /// Count each refusal answer under its check and write the admitted log line. /// The trace id is the one the answer carries. async fn record_refusals( @@ -573,12 +585,18 @@ async fn record_refusals( ) -> Response { let response = next.run(request).await; if let Some(note) = response.extensions().get::() { + let declared = response.extensions().get::(); match registry_platform_httpsec::response_trace_id(response.headers()) { Ok(trace) => { - registry_platform_authcommon::record_refusal!(refusals, *note, trace_id = trace); + registry_platform_authcommon::record_refusal!( + refusals, + *note, + trace_id = trace, + declared = declared + ); } Err(_) => { - registry_platform_authcommon::record_refusal!(refusals, *note); + registry_platform_authcommon::record_refusal!(refusals, *note, declared = declared); } } } @@ -757,9 +775,24 @@ fn route_template(path: &str) -> &'static str { } } +/// An answer that is not a refusal of the caller. A 401 or 403 goes through +/// `refusal_response` so it carries the check that refused the caller: a +/// refusal status that arrives here has no check to count, which a debug +/// build refuses outright and a release build logs. +fn problem_response(problem: &RenderProblem, trace: Option<&str>) -> Response { + if matches!(problem.kind.http_status(), 401 | 403) { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + code = problem.kind.http_code(), + "a refusal was answered without its failed check" + ); + } + problem_answer(problem, trace) +} + /// HTTP callers receive fixed, value-free guidance. Operator diagnostics stay /// with the local CLI and audit boundary; the problem code identifies recovery. -fn problem_response(problem: &RenderProblem, trace: Option<&str>) -> Response { +fn problem_answer(problem: &RenderProblem, trace: Option<&str>) -> Response { let mut context = registry_platform_httpsec::TraceContext::server_created(); if let Some(trace_id) = trace.and_then(|value| registry_platform_httpsec::TraceId::parse(value).ok()) @@ -2985,7 +3018,7 @@ mod tests { Mode::Oidc, Method::GET, "/v1/documents", - token_header(serde_json::json!({"scope":"other"})), + token_header(serde_json::json!({"scope":"canary-token-scope"})), "scope", ), RefusalCase::new( @@ -3099,6 +3132,7 @@ mod tests { "canary-wrong-key-0123456789abcdef0123456789", "canary-invalid-token", "canary-principal", + "canary-token-scope", CANARY_CLIENT, ]; for RefusalCase { @@ -3160,6 +3194,22 @@ mod tests { assert_eq!(fields["decision"], "refused", "{name}"); assert_eq!(fields["failed_check"], check, "{name}"); assert_eq!(fields["trace_id"], trace.as_str(), "{name}"); + // A scope refusal names the values the operator declared. Every + // other check names none. + if check == "scope" { + assert_eq!(fields["scope_claim"], "scope", "{name}"); + let required = if uri.starts_with("/v1/seal/") { + SEAL_SCOPE + } else { + RENDER_SCOPE + }; + assert_eq!(fields["required_scope"], required, "{name}"); + assert!(fields.get("access_profile").is_none(), "{name}"); + } else { + for field in ["scope_claim", "required_scope", "access_profile"] { + assert!(fields.get(field).is_none(), "{name}: {field}"); + } + } for canary in canaries { assert!(!written.contains(canary), "{name}: {written}"); } @@ -3184,4 +3234,33 @@ mod tests { ); } } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn a_refusal_status_without_its_check_is_not_built() { + for kind in [ + ProblemKind::Unauthorized, + ProblemKind::Forbidden, + ProblemKind::SealClientNotAllowed, + ] { + let _ = problem_response(&RenderProblem::new(kind, "no check"), None); + } + } + + #[test] + fn a_refusal_with_its_check_is_built_without_the_guard() { + for kind in [ + ProblemKind::Unauthorized, + ProblemKind::Forbidden, + ProblemKind::SealClientNotAllowed, + ] { + let response = refusal_response( + &RenderProblem::new(kind, "with check"), + None, + FailedCheck::Operation, + ); + assert!(response.extensions().get::().is_some()); + } + } } diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index 14bfb9eb4b..cc8eac6cb9 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- A scope refusal on the facade and the payment routes now writes the scope + claim name, the scope the operation requires and the access profile or + payment connection it applies to on its `request refused` line. The values + come from the deployment's configuration and never from the caller's token. + No answer changes. +- A static key set that the facade refuses at startup states the rule it + broke, so the operator can correct the document without reading the source. - BREAKING: an Adapter job whose runtime document names a plain `http://` endpoint by host name must now list the address range that host resolves to in `allowedPrivateCidrs`. An omitted or empty list admits no private diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index ae63661b9c..ce2fdf969c 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -167,6 +167,9 @@ `scope`. Each value is cut to 128 bytes. Products attach it to the refusal answer's extensions, which are never written to the response. +- The MCP edge's scope refusal line names the configured scope claim and the + required scopes, never the token's own scopes. No answer changes. + - A token whose header `alg` does not fit the key its `kid` names, or whose `kid` names an encryption key such as an RSA-OAEP `use: enc` key, now fails as `OidcError::AlgorithmNotAllowed` (`token-algorithm`) instead of diff --git a/products/render/CHANGELOG.md b/products/render/CHANGELOG.md index 3d28f73d83..ea6cbd1ab5 100644 --- a/products/render/CHANGELOG.md +++ b/products/render/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- A scope refusal writes the scope claim name and the scope the route + requires on its `request refused` log line. The values are fixed by Render + and never come from the caller's token. Responses are unchanged. - Render counts every refusal of a caller in `render_request_refusals_total{check}` (served when `metricsListener` is set) and writes one `request refused` log line with `failed_check` and the trace id, at most five per check per minute. The From abf50de3301ebe31be798976899690b5c6b78cbc Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:35:13 +0100 Subject: [PATCH 054/136] fix(platform): refuse URI database names and redirecting role defaults in provision provision refuses a database name that starts with a connection URI scheme, and a name with a C1 control or a bidirectional formatting character. On a rerun it accepts role settings that do not redirect the session and refuses a role, search_path or session_authorization default as role-settings-differ. A session that cannot open in the new database is database-connect-failed with the statements that already ran, executed is true whenever a statement ran, text output lists those statements, and a product login that reaches its connection limit is an operational failure. The operate pages carry the full printed scripts from the built tools and the host, port and database rules, and the errors reference states the Messaging and Documents readiness answers. Signed-off-by: Jeremi Joslin --- .../tests/postgres_cli.rs | 52 ++++ .../tests/provision_cli.rs | 82 ++++-- crates/registry-platform-provision/README.md | 24 +- .../schema/provision-report.schema.json | 4 +- crates/registry-platform-provision/src/cli.rs | 249 +++++++++++++++++- .../src/execute.rs | 93 +++++-- .../registry-platform-provision/src/plan.rs | 81 +++++- .../tests/postgres.rs | 114 +++++++- docs/site/src/content/docs/operate/breg.mdx | 8 +- .../src/content/docs/operate/casework.mdx | 10 + .../src/content/docs/operate/coordinator.mdx | 8 + .../src/content/docs/operate/documents.mdx | 21 +- .../src/content/docs/operate/messaging.mdx | 14 +- .../src/content/docs/operate/scheduling.mdx | 6 +- .../src/content/docs/reference/errors.mdx | 10 +- products/casework/CHANGELOG.md | 4 +- .../identifiers/generated/catalog.v1.json | 4 +- products/messaging/CHANGELOG.md | 3 +- products/platform/CHANGELOG.md | 23 +- 19 files changed, 709 insertions(+), 101 deletions(-) diff --git a/crates/registry-documentsctl/tests/postgres_cli.rs b/crates/registry-documentsctl/tests/postgres_cli.rs index 19366a7bd4..02125b2805 100644 --- a/crates/registry-documentsctl/tests/postgres_cli.rs +++ b/crates/registry-documentsctl/tests/postgres_cli.rs @@ -405,6 +405,14 @@ impl ProvisionedDatabase { const PASSWORD: &'static str = "documents-test"; async fn new(admin: &tokio_postgres::Client) -> Self { + Self::with_runtime_usage(admin, true).await + } + + /// The database as an operator who provisioned by hand to a layout that + /// gives the runtime role no `USAGE` on `public` leaves it, when + /// `runtime_usage` is false: no role but the migration role can resolve + /// the `public` schema. + async fn with_runtime_usage(admin: &tokio_postgres::Client, runtime_usage: bool) -> Self { let suite = base_config() .get_dbname() .expect("DOCUMENTS_TEST_DATABASE_URL names a database") @@ -452,6 +460,14 @@ impl ProvisionedDatabase { )) .await .unwrap(); + if !runtime_usage { + database + .batch_execute(&format!( + "REVOKE USAGE ON SCHEMA public FROM PUBLIC, {runtime_role}" + )) + .await + .unwrap(); + } drop(database); connection.await.unwrap().unwrap(); provisioned @@ -594,3 +610,39 @@ async fn plan_reports_the_initial_activation_on_a_database_provisioned_as_the_op provisioned.drop(&deployment.admin).await; } + +/// A database provisioned by hand so that the runtime role has `USAGE` on no +/// schema resolves no schema before the first apply. `plan` over that +/// credential still reports the initial activation: the refusal by name is +/// for a database a package was already applied to. +#[tokio::test] +async fn plan_reports_the_initial_activation_when_the_runtime_role_resolves_no_schema() { + let deployment = Deployment::new().await; + let digest = deployment.deploy(); + let runtime = deployment.runtime(); + let provisioned = ProvisionedDatabase::with_runtime_usage(&deployment.admin, false).await; + deployment.secret( + "runtime-database-url", + &provisioned.url( + &provisioned.runtime_role, + Some(ProvisionedDatabase::PASSWORD), + ), + ); + deployment.secret( + "migration-database-url", + &provisioned.url( + &provisioned.migration_role, + Some(ProvisionedDatabase::PASSWORD), + ), + ); + + let (code, plan) = ctl(&["plan", "--runtime-config", &runtime]); + assert_eq!(code, 0, "{plan:#}"); + assert_eq!(plan["packageDigest"], digest); + assert_eq!(plan["change"], "activate"); + assert_eq!(plan["planKind"], "initial"); + assert_eq!(plan["activeDigest"], Value::Null); + assert_eq!(plan["refusals"], serde_json::json!([])); + + provisioned.drop(&deployment.admin).await; +} diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs index acc1e64853..1fb28ea3b0 100644 --- a/crates/registry-messagingctl/tests/provision_cli.rs +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -16,6 +16,12 @@ const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; /// and a runtime login on one server that does not exist, so a connection /// attempt could only fail. fn write_runtime(directory: &Path) -> String { + write_runtime_for(directory, "messaging") +} + +/// [`write_runtime`] with the database name both URLs end in, written as the +/// URL path holds it (percent-encoded where a name needs it). +fn write_runtime_for(directory: &Path, database: &str) -> String { let secrets = directory.join("secrets"); std::fs::create_dir(&secrets).unwrap(); std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); @@ -23,12 +29,12 @@ fn write_runtime(directory: &Path) -> String { ( "migration-database-url", format!( - "postgresql://messaging_migration:{MIGRATION_PASSWORD}@db.invalid:5432/messaging" + "postgresql://messaging_migration:{MIGRATION_PASSWORD}@db.invalid:5432/{database}" ), ), ( "runtime-database-url", - format!("postgresql://messaging_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/messaging"), + format!("postgresql://messaging_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/{database}"), ), ("audit-key", "0123456789abcdef0123456789abcdef".to_owned()), ( @@ -108,6 +114,24 @@ fn scratch() -> tempfile::TempDir { tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() } +#[test] +fn a_database_name_that_is_a_connection_uri_is_refused_in_print_mode() { + let directory = scratch(); + let runtime = write_runtime_for(directory.path(), "postgresql%3A%2F%2Fevil.example%2Fx"); + let (code, report) = refusal(&runtime); + assert_eq!(code, Some(2), "{report:#}"); + let diagnostic = first_diagnostic(&report); + assert_eq!( + diagnostic["code"], "platform.provision.target-invalid", + "{report:#}" + ); + assert_eq!(report["executed"], false, "{report:#}"); + assert!( + !report.to_string().contains("evil.example"), + "the refused name is not repeated: {report:#}" + ); +} + #[test] fn print_sql_writes_the_script_and_no_password() { let directory = scratch(); @@ -172,34 +196,40 @@ fn print_sql_as_json_reports_nothing_executed() { fn both_administrator_flags_are_refused() { let directory = scratch(); let runtime = write_runtime(directory.path()); - for arguments in [ - vec![ - "provision", - "--runtime-config", - &runtime, - "--admin-url-file", - "/nonexistent/admin-url", - "--admin-url-env", - "MESSAGING_ADMIN_URL", - ], - vec![ - "provision", - "--runtime-config", - &runtime, - "--print-sql", - "--admin-url-env", - "MESSAGING_ADMIN_URL", - ], - vec!["provision", "--runtime-config", &runtime], + for (arguments, message) in [ + ( + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "MESSAGING_ADMIN_URL", + ], + "conflicting use of --admin-url-file", + ), + ( + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "MESSAGING_ADMIN_URL", + ], + "conflicting use of --print-sql", + ), + ( + vec!["provision", "--runtime-config", &runtime], + "missing required argument --admin-url-file, --admin-url-env", + ), ] { let output = ctl(&arguments); let stderr = String::from_utf8_lossy(&output.stderr); assert_eq!(output.status.code(), Some(2), "{arguments:?}: {stderr}"); - // clap also answers 2 for an unknown verb, so the text names the flags. - assert!( - stderr.contains("--admin-url") || stderr.contains("--print-sql"), - "{arguments:?}: {stderr}" - ); + assert!(output.stdout.is_empty(), "{arguments:?}"); + assert!(stderr.contains(message), "{arguments:?}: {stderr}"); } } diff --git a/crates/registry-platform-provision/README.md b/crates/registry-platform-provision/README.md index a9570e53b5..cf225c38ee 100644 --- a/crates/registry-platform-provision/README.md +++ b/crates/registry-platform-provision/README.md @@ -18,10 +18,12 @@ name. `psql`. The script holds no password and no password verifier: each login role is followed by a `\password` line, a statement that needs a superuser is marked, and the script stops at the first error. A role or database name - with a control character or a backslash, a database name with `=`, the - role names `public`, `none` and `pg_*`, and the databases `postgres`, - `template0` and `template1` are refused when the plan is built, so no name - can start a `psql` meta-command or reach another database. + with a control character, a backslash or a bidirectional formatting + character, a database name with `=` or one that starts with `postgresql://` + or `postgres://`, the role names `public`, `none` and `pg_*`, and the + databases `postgres`, `template0` and `template1` are refused when the plan + is built, so no name can start a `psql` meta-command or reach another + database. - `verify_server_version` refuses a server below the shared PostgreSQL floor, `registry_platform_activation::MINIMUM_SERVER_VERSION_NUM`. - `sql` holds the statement builders and the identifier and literal quoting. @@ -33,10 +35,13 @@ name. `verify-full`). In `Mode::Converge` the server version is checked before the first statement, and an existing role, database, schema or extension in another shape is refused and never altered: a role with other attributes, - role-level settings or a membership the plan did not grant, a template - database, a PostGIS installed outside the plan's schema or without the bbox - membership. `execute_recording` keeps the outcomes of the statements that - ran before a failure. + a default for `role`, `search_path` or `session_authorization`, or a + membership the plan did not grant, a template database, a PostGIS installed + outside the plan's schema or without the bbox membership. + `execute_recording` keeps the outcomes of the statements that ran before a + failure. A session that cannot open in the new database after the + server-scope statements ran is reported as `database-connect-failed`, with + those statements listed. Passwords enter only through `RoleCredential`, whose `Debug` prints the name. The executable text of a role statement carries a SCRAM-SHA-256 verifier @@ -53,6 +58,7 @@ formats or logs a secret. - `schema` renders the report's JSON Schema from its Rust type. - `test-support` adds `test_support`, a verified-TLS superuser session and the two `PROVISION_TEST_DATABASE_*` variables, for the provision tests of the - products that use this crate. Only their dev-dependencies enable it. + products that use this crate, and `Mode::Fresh`, which skips the probes. + Only their dev-dependencies enable it. - `postgres-test` runs `tests/postgres.rs` against a disposable server. Its header names the three variables it needs. diff --git a/crates/registry-platform-provision/schema/provision-report.schema.json b/crates/registry-platform-provision/schema/provision-report.schema.json index e240b01f5e..c27832dfc8 100644 --- a/crates/registry-platform-provision/schema/provision-report.schema.json +++ b/crates/registry-platform-provision/schema/provision-report.schema.json @@ -163,7 +163,7 @@ }, "outcome": { "$ref": "#/$defs/ReportOutcome", - "description": "`not-run` for a statement the run did not reach, the one that failed\nincluded." + "description": "`not-run` for a statement the run did not reach, the one that failed\nincluded. After `platform.provision.effect-unconfirmed` the statement\nthe diagnostic names was sent and may have taken effect." }, "scope": { "$ref": "#/$defs/ReportScope" @@ -265,7 +265,7 @@ "type": "array" }, "executed": { - "description": "Whether a statement could have been sent to the server: false for a\nprint-mode run and for a run that stopped before the first statement.", + "description": "Whether a statement could have been sent to the server: false for a\nprint-mode run and for a run that stopped before the first statement.\nTrue whenever a statement is listed as run.", "type": "boolean" }, "kind": { diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs index 87ac60b5d8..9d2e4d23fd 100644 --- a/crates/registry-platform-provision/src/cli.rs +++ b/crates/registry-platform-provision/src/cli.rs @@ -136,7 +136,8 @@ pub struct ReportStatement { pub scope: ReportScope, pub needs: ReportNeeds, /// `not-run` for a statement the run did not reach, the one that failed - /// included. + /// included. After `platform.provision.effect-unconfirmed` the statement + /// the diagnostic names was sent and may have taken effect. pub outcome: ReportOutcome, pub sql: String, } @@ -158,6 +159,7 @@ pub struct PlatformCliDatabaseProvisionReport { pub product: Option, /// Whether a statement could have been sent to the server: false for a /// print-mode run and for a run that stopped before the first statement. + /// True whenever a statement is listed as run. pub executed: bool, #[serde(skip_serializing_if = "Option::is_none")] pub role_mode: Option, @@ -267,14 +269,15 @@ fn target_invalid(message: &str) -> Refusal { /// A name the plan refuses. The action names the URL member to correct and /// never quotes its value. fn plan_refusal(error: &PlanError) -> Refusal { - let rule = "A role name must not hold a control character or a backslash, and must not be \ - public, none or start with pg_."; + let rule = "A role name must not hold a control character, a backslash or a bidirectional \ + formatting character, and must not be public, none or start with pg_."; let action = match error { PlanError::InvalidName { what: "database name", } => "Change the database name, the path of database.migrationUrlRef and \ - database.runtimeUrlRef. It must not hold a control character, a backslash or =, \ - and must not be postgres, template0 or template1." + database.runtimeUrlRef. It must not hold a control character, a backslash, a \ + bidirectional formatting character or =, must not start with postgresql:// or \ + postgres://, and must not be postgres, template0 or template1." .to_owned(), PlanError::InvalidName { what: "migration role name", @@ -324,7 +327,15 @@ fn read_admin_url(args: &ProvisionArgs) -> Result, Refusal> { }; let raw = match (&args.admin_url_file, &args.admin_url_env) { (Some(path), None) => { - let read = std::fs::File::open(path).and_then(|file| { + // The check before the open keeps a named pipe from blocking it. + let read = std::fs::metadata(path).and_then(|metadata| { + if metadata.is_file() { + std::fs::File::open(path) + } else { + Err(std::io::Error::other("not a regular file")) + } + }); + let read = read.and_then(|file| { if !file.metadata()?.is_file() { return Err(std::io::Error::other("not a regular file")); } @@ -414,6 +425,14 @@ fn execution_refusal(tool: &str, error: &ProvisionError) -> Refusal { then run provision again." .to_owned(), ), + E::DatabaseConnectFailed { .. } => ( + ReportStatus::OperationalFailure, + "The administrator opened a session on the server, and the statements listed as run \ + took effect. Check that the administrator role's CONNECTION LIMIT leaves room for a \ + second session and that pg_hba.conf admits it to the new database, then run \ + provision again." + .to_owned(), + ), E::UnsupportedPostgres => ( ReportStatus::DomainRefusal, "Provision a PostgreSQL 17 or newer server, then run provision again.".to_owned(), @@ -432,6 +451,12 @@ fn execution_refusal(tool: &str, error: &ProvisionError) -> Refusal { then run provision again." .to_owned(), ), + E::RoleSettingsDiffer { .. } => ( + ReportStatus::DomainRefusal, + "Use another role name in the product URLs, or reset the role's role, search_path \ + and session_authorization defaults as an administrator, then run provision again." + .to_owned(), + ), E::RoleMembershipDiffers { .. } => ( ReportStatus::DomainRefusal, "Use another role name in the product URLs, or revoke the role's memberships as an \ @@ -480,6 +505,12 @@ fn execution_refusal(tool: &str, error: &ProvisionError) -> Refusal { again." .to_owned(), ), + Some("53300") => ( + ReportStatus::OperationalFailure, + "The role or the server has reached its connection limit. Raise the role's \ + CONNECTION LIMIT or free a connection, then run provision again." + .to_owned(), + ), Some(_) => ( ReportStatus::DomainRefusal, "Read the PostgreSQL server log for the refused login, fix the cause, then run \ @@ -612,10 +643,26 @@ impl Output<'_> { fn refusal(&mut self, report: &PlatformCliDatabaseProvisionReport) -> u8 { let written = match self.format { OutputFormat::Json => self.json(report), - OutputFormat::Human => report - .diagnostics - .iter() - .all(|diagnostic| write!(self.stderr, "{}", diagnostic.render_human()).is_ok()), + OutputFormat::Human => { + // A run that stopped part-way shows what it had already done. + let ran = report + .statements + .iter() + .filter(|statement| statement.outcome != ReportOutcome::NotRun) + .all(|statement| { + writeln!( + self.stderr, + "{} {}", + outcome_word(statement.outcome), + statement.step + ) + .is_ok() + }); + ran && report + .diagnostics + .iter() + .all(|diagnostic| write!(self.stderr, "{}", diagnostic.render_human()).is_ok()) + } }; let exit = exit_code(report.status); match self.write_failed(written) { @@ -799,7 +846,8 @@ fn run_with( output.write_failed(written) } Err(failure) => { - report.executed = failure.error.may_have_run_statements(); + report.executed = + !failure.reached.is_empty() || failure.error.may_have_run_statements(); report.statements = report_statements(&plan, &failure.reached); refused(&mut report, execution_refusal(tool, &failure.error)); output.refusal(&report) @@ -1525,6 +1573,36 @@ mod tests { 1, Some("extension.postgis"), ), + ( + E::RoleSettingsDiffer { + step: "role.runtime", + role: "app_runtime".to_owned(), + }, + "platform.provision.role-settings-differ", + "domain-refusal", + 1, + Some("role.runtime"), + ), + ( + E::DatabaseConnectFailed { + database: "app".to_owned(), + sqlstate: Some("53300".to_owned()), + }, + "platform.provision.database-connect-failed", + "operational-failure", + 3, + None, + ), + ( + E::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: Some("53300".to_owned()), + }, + "platform.provision.role-login-failed", + "operational-failure", + 3, + None, + ), ( E::EffectUnconfirmed { step: "database.create", @@ -1667,6 +1745,124 @@ mod tests { assert!(action_for(Some("28000")).contains("pg_hba.conf")); } + #[test] + fn a_connect_failure_in_the_new_database_reports_what_ran_and_names_the_database() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, plan: &Plan, _: &ProvisionTarget| { + let reached = plan + .statements() + .iter() + .take(3) + .map(|statement| (statement.step, StatementOutcome::Created)) + .collect(); + Err(Failure { + error: ProvisionError::DatabaseConnectFailed { + database: "app".to_owned(), + sqlstate: Some("53300".to_owned()), + }, + reached, + }) + }; + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.exit, 3, "{}", run.all_output()); + let report = run.json(); + assert_eq!(report["executed"], true); + let diagnostic = &report["diagnostics"][0]; + assert_eq!( + diagnostic["code"], + "platform.provision.database-connect-failed" + ); + let action = diagnostic["suggestedAction"].as_str().unwrap(); + assert!( + action.contains("CONNECTION LIMIT") && action.contains("pg_hba.conf"), + "{action}" + ); + assert!( + !action.contains("administrator URL"), + "the URL was proved right: {action}" + ); + assert_eq!(report["statements"][0]["outcome"], "created"); + } + + #[test] + fn statements_that_ran_mean_executed_whatever_the_error() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, plan: &Plan, _: &ProvisionTarget| { + Err(Failure { + error: ProvisionError::AdminConnectFailed { sqlstate: None }, + reached: vec![(plan.statements()[0].step, StatementOutcome::Created)], + }) + }; + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.json()["executed"], true); + } + + #[test] + fn a_text_refusal_lists_the_statements_that_ran_before_it() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, plan: &Plan, _: &ProvisionTarget| { + Err(Failure { + error: ProvisionError::StatementFailed { + step: "database.create", + sqlstate: "42501".to_owned(), + }, + reached: plan + .statements() + .iter() + .take(2) + .map(|statement| (statement.step, StatementOutcome::Created)) + .collect(), + }) + }; + let run = execute_run(&[], Some(&admin), Ok(split_input()), &backend); + assert_eq!(run.exit, 3); + assert_eq!(run.stdout, ""); + let ran = run + .stderr + .find("created role.migration\ncreated role.runtime\n") + .unwrap_or_else(|| panic!("{}", run.stderr)); + let refusal = run + .stderr + .find("error[platform.provision.statement-failed]") + .unwrap_or_else(|| panic!("{}", run.stderr)); + assert!(ran < refusal, "{}", run.stderr); + assert!(!run.stderr.contains("not-run"), "{}", run.stderr); + } + + #[test] + fn a_refusal_before_any_statement_lists_no_statements() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| { + Err(ProvisionError::UnsupportedPostgres.into()) + }; + let run = execute_run(&[], Some(&admin), Ok(split_input()), &backend); + assert!(!run.stderr.contains("created"), "{}", run.stderr); + assert!(run.stderr.starts_with("error["), "{}", run.stderr); + } + + #[test] + fn a_login_refusal_for_a_connection_limit_is_operational() { + let (exit, report) = refusal_json(ProvisionError::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: Some("53300".to_owned()), + }); + assert_eq!(exit, 3); + let action = report["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap(); + assert!(action.contains("CONNECTION LIMIT"), "{action}"); + } + #[test] fn a_missing_administrator_database_gets_its_own_action() { let (exit, report) = refusal_json(ProvisionError::AdminConnectFailed { @@ -1787,6 +1983,37 @@ mod tests { assert!(!String::from_utf8(stdout).unwrap().contains("nonexistent")); } + #[cfg(unix)] + #[test] + fn an_administrator_file_that_is_a_named_pipe_is_refused_without_opening_it() { + let directory = tempfile::tempdir().expect("scratch directory"); + let pipe = directory.path().join("admin.url"); + let made = std::process::Command::new("mkfifo") + .arg(&pipe) + .status() + .expect("mkfifo runs"); + assert!(made.success()); + let pipe = pipe.display().to_string(); + let args = parse(&["--runtime-config", "r", "--admin-url-file", &pipe]).unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + OutputFormat::Json, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + assert_eq!(exit, 2); + let report: Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!( + report["diagnostics"][0]["code"], + "platform.provision.admin-url-invalid" + ); + } + #[test] fn an_unset_administrator_variable_is_an_admin_url_refusal_that_names_the_variable() { let args = parse(&[ diff --git a/crates/registry-platform-provision/src/execute.rs b/crates/registry-platform-provision/src/execute.rs index ad650c1e6e..c3bd444210 100644 --- a/crates/registry-platform-provision/src/execute.rs +++ b/crates/registry-platform-provision/src/execute.rs @@ -18,7 +18,9 @@ pub enum Mode { /// Probe the catalog first, create only what is absent, and refuse what /// exists in a different shape. Every `*ctl provision` uses this. Converge, - /// The server is known to be empty: no floor check and no probes. + /// The server is known to be empty: no floor check and no probes. Only + /// the products' test helpers and the PostgreSQL suite use it. + #[cfg(any(feature = "test-support", feature = "postgres-test"))] Fresh, } @@ -46,6 +48,13 @@ pub enum ProvisionError { AdminConnectFailed { sqlstate: Option, }, + /// The administrator opened a session on the server, then could not open + /// one in the database the plan provisions, so the server-scope + /// statements before it ran. + DatabaseConnectFailed { + database: String, + sqlstate: Option, + }, UnsupportedPostgres, StatementNeedsPrivilege { step: &'static str, @@ -57,6 +66,13 @@ pub enum ProvisionError { step: &'static str, role: String, }, + /// An existing product role carries a setting that redirects its sessions: + /// a `role`, `search_path` or `session_authorization` default, for every + /// database or for the provisioned one. + RoleSettingsDiffer { + step: &'static str, + role: String, + }, /// An existing product role is a member of a role the plan did not grant it. RoleMembershipDiffers { step: &'static str, @@ -102,9 +118,11 @@ impl ProvisionError { pub fn code(&self) -> &'static str { match self { Self::AdminConnectFailed { .. } => "platform.provision.admin-connect-failed", + Self::DatabaseConnectFailed { .. } => "platform.provision.database-connect-failed", Self::UnsupportedPostgres => "platform.provision.unsupported-postgres", Self::StatementNeedsPrivilege { .. } => "platform.provision.statement-needs-privilege", Self::RoleAttributesDiffer { .. } => "platform.provision.role-attributes-differ", + Self::RoleSettingsDiffer { .. } => "platform.provision.role-settings-differ", Self::RoleMembershipDiffers { .. } => "platform.provision.role-membership-differs", Self::DatabaseOwnerDiffers { .. } => "platform.provision.database-owner-differs", Self::DatabaseIsTemplate { .. } => "platform.provision.database-is-template", @@ -130,6 +148,7 @@ impl ProvisionError { match self { Self::StatementNeedsPrivilege { step, .. } | Self::RoleAttributesDiffer { step, .. } + | Self::RoleSettingsDiffer { step, .. } | Self::RoleMembershipDiffers { step, .. } | Self::SchemaOwnerDiffers { step, .. } | Self::ExtensionTooOld { step, .. } @@ -140,6 +159,7 @@ impl ProvisionError { Some("database.create") } Self::AdminConnectFailed { .. } + | Self::DatabaseConnectFailed { .. } | Self::UnsupportedPostgres | Self::RoleLoginFailed { .. } => None, } @@ -183,6 +203,16 @@ impl fmt::Display for ProvisionError { f, "cannot open a session with the administrator URL (SQLSTATE {sqlstate})" ), + Self::DatabaseConnectFailed { database, sqlstate } => { + write!( + f, + "the administrator role cannot open a session in database \"{database}\"" + )?; + match sqlstate { + Some(sqlstate) => write!(f, " (SQLSTATE {sqlstate})"), + None => Ok(()), + } + } Self::UnsupportedPostgres => fmt::Display::fmt(&crate::plan::UnsupportedPostgres, f), Self::StatementNeedsPrivilege { step, @@ -207,6 +237,12 @@ impl fmt::Display for ProvisionError { creates it with. It is not altered: use another name or correct the role as \ an administrator" ), + Self::RoleSettingsDiffer { role, .. } => write!( + f, + "the role \"{role}\" already exists with a default for role, search_path or \ + session_authorization. It is not altered: use another name or reset the \ + setting as an administrator" + ), Self::RoleMembershipDiffers { role, .. } => write!( f, "the role \"{role}\" already exists and is a member of a role provisioning did \ @@ -358,12 +394,12 @@ async fn run_plan( Scope::Server => &server, Scope::Database => match &mut database { Some(session) => session, - empty => empty.insert( - admin - .connect(Some(plan.database())) - .await - .map_err(connect_failed)?, - ), + empty => empty.insert(admin.connect(Some(plan.database())).await.map_err( + |failure| ProvisionError::DatabaseConnectFailed { + database: plan.database().to_owned(), + sqlstate: failure.sqlstate, + }, + )?), }, }; let outcome = run_statement(session, plan, statement, mode).await?; @@ -441,13 +477,23 @@ async fn probe_is_satisfied( login, member_of, } => { - // Columns 1 to 7 are attributes that must be false: the six - // flags and role-level settings. Column 8 is membership of any - // role other than `member_of` granted as the plan grants it. + // Columns 1 to 6 are attributes that must be false: the six + // flags. Column 7 is a default for `role`, `search_path` or + // `session_authorization` set for the role in every database or + // in the provisioned one. Column 8 is membership of any role + // other than `member_of` granted as the plan grants it. let row = bounded_call(session.client.query_opt( "SELECT r.rolcanlogin, r.rolsuper, r.rolcreatedb, r.rolcreaterole, \ r.rolinherit, r.rolbypassrls, r.rolreplication, \ - r.rolconfig IS NOT NULL, \ + EXISTS (SELECT 1 FROM pg_catalog.pg_db_role_setting s, \ + unnest(s.setconfig) AS c \ + WHERE s.setrole = r.oid \ + AND (s.setdatabase = 0 \ + OR s.setdatabase = (SELECT d.oid \ + FROM pg_catalog.pg_database d \ + WHERE d.datname = $3)) \ + AND lower(split_part(c, '=', 1)) \ + IN ('role', 'search_path', 'session_authorization')), \ EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m \ JOIN pg_catalog.pg_roles g ON g.oid = m.roleid \ WHERE m.member = r.oid \ @@ -456,7 +502,7 @@ async fn probe_is_satisfied( AND m.set_option \ AND NOT m.admin_option)) \ FROM pg_catalog.pg_roles r WHERE r.rolname = $1", - &[name, member_of], + &[name, member_of, &plan.database()], )) .await .map_err(|failure| call_error(step, failure))?; @@ -465,7 +511,7 @@ async fn probe_is_satisfied( }; let can_login: bool = row.try_get(0).map_err(|_| unreadable(step))?; let mut others = false; - for column in 1..8 { + for column in 1..7 { let flag: bool = row.try_get(column).map_err(|_| unreadable(step))?; others |= flag; } @@ -475,6 +521,13 @@ async fn probe_is_satisfied( role: name.clone(), }); } + let redirected: bool = row.try_get(7).map_err(|_| unreadable(step))?; + if redirected { + return Err(ProvisionError::RoleSettingsDiffer { + step, + role: name.clone(), + }); + } let other_membership: bool = row.try_get(8).map_err(|_| unreadable(step))?; if other_membership { return Err(ProvisionError::RoleMembershipDiffers { @@ -630,11 +683,9 @@ pub async fn verify_logins( CallFailure::Unconfirmed => None, }) })?; - let current: String = row - .try_get(0) - .map_err(|_| failed(Some("XX000".to_owned())))?; + let current: String = row.try_get(0).map_err(|_| failed(None))?; if current != role.name { - return Err(failed(Some("XX000".to_owned()))); + return Err(failed(None)); } } Ok(()) @@ -669,6 +720,14 @@ mod tests { step: "role.migration", role: "r".to_owned(), }, + ProvisionError::RoleSettingsDiffer { + step: "role.runtime", + role: "r".to_owned(), + }, + ProvisionError::DatabaseConnectFailed { + database: "d".to_owned(), + sqlstate: Some("53300".to_owned()), + }, ProvisionError::RoleMembershipDiffers { step: "role.runtime", role: "r".to_owned(), diff --git a/crates/registry-platform-provision/src/plan.rs b/crates/registry-platform-provision/src/plan.rs index 9fdc63236d..6c9f030dd3 100644 --- a/crates/registry-platform-provision/src/plan.rs +++ b/crates/registry-platform-provision/src/plan.rs @@ -218,11 +218,20 @@ const MAX_NAME_BYTES: usize = 63; const RESERVED_DATABASES: [&str; 3] = ["postgres", "template0", "template1"]; /// A name reaches the printed `psql` script, where a line break would end a -/// meta-command and a backslash would start one, so no byte below 0x20, DEL -/// or backslash is allowed in any name. +/// meta-command and a backslash would start one, and a bidirectional override +/// would make a reviewed line read differently from what runs. So no control +/// character (C0, DEL or C1), backslash or bidirectional formatting character +/// is allowed in any name. fn check_name(what: &'static str, name: &str) -> Result<(), PlanError> { - let unsafe_byte = |byte: u8| byte < 0x20 || byte == 0x7f || byte == b'\\'; - if name.is_empty() || name.len() > MAX_NAME_BYTES || name.bytes().any(unsafe_byte) { + let unsafe_char = |c: char| { + c.is_control() + || c == '\\' + || matches!( + c, + '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' + ) + }; + if name.is_empty() || name.len() > MAX_NAME_BYTES || name.chars().any(unsafe_char) { return Err(PlanError::InvalidName { what }); } Ok(()) @@ -239,10 +248,16 @@ fn check_role_name(what: &'static str, name: &str) -> Result<(), PlanError> { Ok(()) } -/// `\connect` reads a database name holding `=` as a connection string. +/// `\connect` reads a database name holding `=`, or starting with a URI +/// scheme, as a connection string and so can reach another server. fn check_database_name(what: &'static str, name: &str) -> Result<(), PlanError> { check_name(what, name)?; - if name.contains('=') || RESERVED_DATABASES.contains(&name) { + let lower = name.to_ascii_lowercase(); + if name.contains('=') + || lower.starts_with("postgresql://") + || lower.starts_with("postgres://") + || RESERVED_DATABASES.contains(&name) + { return Err(PlanError::InvalidName { what }); } Ok(()) @@ -851,6 +866,60 @@ mod tests { assert!(plan_for(&role).is_ok()); } + #[test] + fn a_database_name_that_starts_with_a_connection_uri_scheme_is_refused() { + for bad in [ + "postgresql://evil.example/x", + "postgres://evil.example/x", + "PostgreSQL://evil.example/x", + "POSTGRES://evil.example/x", + ] { + let mut database = target(); + database.database = bad.to_owned(); + assert_eq!( + plan_for(&database).unwrap_err(), + invalid("database name"), + "{bad}" + ); + } + // Only a leading scheme is read as a URI, and a role name may hold one. + let mut inner = target(); + inner.database = "app-postgres://x".to_owned(); + assert!(plan_for(&inner).is_ok()); + let mut role = target(); + role.runtime = RoleCredential::new("postgres://runtime", PASSWORD_R); + assert!(plan_for(&role).is_ok()); + } + + #[test] + fn names_with_c1_controls_or_bidirectional_overrides_are_refused() { + for bad in [ + "a\u{85}b", + "a\u{9f}b", + "a\u{202e}b", + "a\u{2066}b", + "a\u{200f}b", + ] { + let mut database = target(); + database.database = bad.to_owned(); + assert_eq!( + plan_for(&database).unwrap_err(), + invalid("database name"), + "{bad:?}" + ); + let mut runtime = target(); + runtime.runtime = RoleCredential::new(bad, PASSWORD_R); + assert_eq!( + plan_for(&runtime).unwrap_err(), + invalid("runtime role name"), + "{bad:?}" + ); + } + let mut accented = target(); + accented.database = "cafe\u{301}".to_owned(); + assert!(plan_for(&accented).is_ok()); + } + #[test] fn reserved_role_names_are_refused() { for reserved in [ diff --git a/crates/registry-platform-provision/tests/postgres.rs b/crates/registry-platform-provision/tests/postgres.rs index 52ceea54cd..9b38ae7fc4 100644 --- a/crates/registry-platform-provision/tests/postgres.rs +++ b/crates/registry-platform-provision/tests/postgres.rs @@ -1064,7 +1064,7 @@ async fn an_existing_role_with_members_or_the_plans_own_grants_is_accepted() { } #[tokio::test] -async fn an_existing_role_with_role_level_settings_is_refused() { +async fn an_existing_role_with_a_role_level_search_path_is_refused() { let _serial = lock().await; let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; let role = fixture.runtime_name(); @@ -1072,7 +1072,8 @@ async fn an_existing_role_with_role_level_settings_is_refused() { .server .superuser .exec(&format!( - "CREATE ROLE {} LOGIN; ALTER ROLE {} SET search_path = pg_catalog", + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \ + ALTER ROLE {} SET search_path = pg_catalog", quote(&role), quote(&role) )) @@ -1081,8 +1082,78 @@ async fn an_existing_role_with_role_level_settings_is_refused() { .provision(&Fixture::public_product()) .await .unwrap_err(); - assert_eq!(error.code(), "platform.provision.role-attributes-differ"); + assert_eq!(error.code(), "platform.provision.role-settings-differ"); assert_eq!(error.step(), Some("role.runtime")); + assert!(error.to_string().contains(&role)); + assert!( + !fixture.database_exists().await, + "nothing runs after a refusal" + ); + fixture + .server + .superuser + .exec(&format!("DROP ROLE IF EXISTS {}", quote(&role))) + .await; + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_search_path_set_for_the_role_in_the_product_database_is_refused_on_a_rerun() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = Fixture::public_product(); + fixture.provision(&product).await.unwrap(); + let role = quote(&fixture.runtime_name()); + // A setting for another database does not touch this one. + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {role} IN DATABASE postgres SET search_path = pg_catalog" + )) + .await; + let again = fixture.provision(&product).await.unwrap(); + assert_eq!(created(&again), Vec::<&str>::new()); + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {role} IN DATABASE {} SET search_path = pg_catalog", + quote(&fixture.database()) + )) + .await; + let error = fixture.provision(&product).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.role-settings-differ"); + assert_eq!(error.step(), Some("role.runtime")); + fixture + .server + .superuser + .exec(&format!("ALTER ROLE {role} IN DATABASE postgres RESET ALL")) + .await; + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_rerun_converges_over_role_settings_that_do_not_redirect_the_session() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = Fixture::public_product(); + fixture.provision(&product).await.unwrap(); + let role = quote(&fixture.runtime_name()); + // The settings an operator puts on the runtime role behind a pooler that + // drops startup options. + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {role} SET idle_in_transaction_session_timeout = '120s'; \ + ALTER ROLE {role} SET jit = off; \ + ALTER ROLE {role} IN DATABASE {} SET statement_timeout = '30s'", + quote(&fixture.database()) + )) + .await; + let again = fixture.provision(&product).await.unwrap(); + assert_eq!(created(&again), Vec::<&str>::new()); fixture.cleanup().await; } @@ -1450,6 +1521,43 @@ async fn a_login_refused_for_another_reason_carries_that_sqlstate() { fixture.cleanup().await; } +#[tokio::test] +async fn a_database_session_that_cannot_open_reports_the_statements_that_already_ran() { + let _serial = lock().await; + // One connection is the server session the run keeps open, so the session + // in the new database cannot open. + let fixture = Fixture::new("CREATEROLE CREATEDB CONNECTION LIMIT 1").await; + let plan = plan(&Fixture::public_product(), &fixture.target()).unwrap(); + let failure = execute_recording(&fixture.admin(), &plan, Mode::Converge) + .await + .unwrap_err(); + assert_eq!( + failure.error.code(), + "platform.provision.database-connect-failed" + ); + assert!(failure.error.may_have_run_statements()); + let message = failure.error.to_string(); + assert!(message.contains(&fixture.database()), "{message}"); + assert!(message.contains("53300"), "{message}"); + let steps: Vec<&str> = failure.reached.iter().map(|(step, _)| *step).collect(); + assert_eq!( + steps, + [ + "role.migration", + "role.runtime", + "database.create", + "database.revoke-public", + "database.grant-connect", + "database.allow-connections" + ] + ); + assert!( + fixture.database_exists().await, + "the statements listed as run took effect" + ); + fixture.cleanup().await; +} + // ---- A.13 test 9 ---------------------------------------------------------- fn unquote(identifier: &str) -> String { diff --git a/docs/site/src/content/docs/operate/breg.mdx b/docs/site/src/content/docs/operate/breg.mdx index 2ce0546077..0578f64753 100644 --- a/docs/site/src/content/docs/operate/breg.mdx +++ b/docs/site/src/content/docs/operate/breg.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-10-17" +last_reviewed: "2026-11-27" doc_type: how-to persona: - operator @@ -279,6 +279,12 @@ instead, use `--admin-url-env NAME`. The connection requires TLS and verifies th certificate. Set `database.caBundleRef` in the runtime file to trust a private CA. The command never prints the administrator URL or a password. +The administrator URL must name the same host and port as the two product URLs, or `provision` +refuses it as `platform.provision.target-mismatch`. It must also name a database other than the +product database, such as `postgres`, or `provision` refuses it as `platform.provision.target-invalid`. +Where the administrator may connect only to the product database, `provision` cannot run: add +`--print-sql` and give the script to the person who administers the server. + The command: - Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index 9e1a3fe182..a5650e7638 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -207,6 +207,12 @@ use `--admin-url-env NAME`. The connection requires TLS and verifies the server `database.caBundleRef` in the runtime file to trust a private CA. The command never prints the administrator URL or a password. +The administrator URL must name the same host and port as the two product URLs, or `provision` +refuses it as `platform.provision.target-mismatch`. It must also name a database other than the +product database, such as `postgres`, or `provision` refuses it as `platform.provision.target-invalid`. +Where the administrator may connect only to the product database, `provision` cannot run: add +`--print-sql` and give the script to the person who administers the server. + The command: - Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. @@ -224,6 +230,10 @@ flags. The command connects to nothing and prints the script. Each `CREATE ROLE` `\password` line that prompts for the password in `psql`, so the script holds no password: ```sql +-- provision script, product casework. Nothing was run. +-- For a server where these objects do not exist yet. Review, then run with psql as an +-- administrator that has CREATEROLE and CREATEDB. It stops at the first error. +\set ON_ERROR_STOP on SET createrole_self_grant = 'set,inherit'; CREATE ROLE "casework_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \password "casework_migration" diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index f71dfb8825..c3f0e56c1f 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -261,12 +261,16 @@ Secret values never appear in a diagnostic or a log. Use PostgreSQL 17 or newer; `apply` and startup refuse an older server. `provision` creates what the two database URLs in your runtime file name: the migration role, the runtime role, and the database, and it lets only those two roles connect. It takes the role names, the database name, and the passwords from `database.migrationUrlRef` and `database.runtimeUrlRef`, so you write each of them once, except that when the runtime file has a `deployment` block, the user of the runtime URL must be `deployment.runtimeRole`: `provision` refuses a different user before it connects, with `coordinator.runtime-config.runtime-role-mismatch`. +Without a `deployment` block, `provision` creates the role the runtime URL names, and `apply` then refuses the missing block. Run it as a PostgreSQL administrator that can create roles and databases (`CREATEROLE` and `CREATEDB`). It needs no superuser. Put the administrator URL in a file or an environment variable, never on the command line. The connection always uses verified TLS: it trusts the certificate authority behind `database.caBundleRef` when the runtime file names one, and the system roots otherwise. The URL's `sslmode` must be `require`, `verify-ca`, or `verify-full`. +The administrator URL must name the same host and port as the two product URLs, or `provision` refuses it as `platform.provision.target-mismatch`. +It must also name a database other than the product database, such as `postgres`, or `provision` refuses it as `platform.provision.target-invalid`. +Where the administrator may connect only to the product database, `provision` cannot run: add `--print-sql` and give the script to the person who administers the server. ```sh coordinatorctl provision --runtime-config /etc/registry-coordinator/runtime.yaml \ @@ -282,6 +286,10 @@ To review the statements first, or to run them yourself with `psql`, add `--prin It connects to nothing and prints a script with a `\password` line after each role instead of a password: ```sql +-- provision script, product coordinator. Nothing was run. +-- For a server where these objects do not exist yet. Review, then run with psql as an +-- administrator that has CREATEROLE and CREATEDB. It stops at the first error. +\set ON_ERROR_STOP on SET createrole_self_grant = 'set,inherit'; CREATE ROLE "coordinator_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \password "coordinator_migration" diff --git a/docs/site/src/content/docs/operate/documents.mdx b/docs/site/src/content/docs/operate/documents.mdx index 2870b6c454..272ead5f50 100644 --- a/docs/site/src/content/docs/operate/documents.mdx +++ b/docs/site/src/content/docs/operate/documents.mdx @@ -56,16 +56,18 @@ The `admin-url` file holds one PostgreSQL URL for that administrator, for exampl use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set `database.caBundleRef` in the runtime file to trust a private CA. The administrator URL must name the same host and port as the two product URLs, and a database other than the product database, such -as `postgres`. The command refuses it otherwise. It never prints the administrator URL or a -password. +as `postgres`. The command refuses it otherwise, as `platform.provision.target-mismatch` for the host +and port and as `platform.provision.target-invalid` for the database. Where the administrator may +connect only to the product database, `provision` cannot run: add `--print-sql` and give the script +to the person who administers the server. It never prints the administrator URL or a password. The command: - Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. - Creates the database and closes it to `PUBLIC`. - Grants both roles `CONNECT` on the database. -- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it - from `PUBLIC`. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema and the runtime role `USAGE` + on it, and takes `CREATE` on it from `PUBLIC`. Run it again at any time. It creates only what is missing. It refuses a role that exists with a different password than its URL holds, and tells you which role. @@ -75,6 +77,10 @@ flags. The command connects to nothing and prints the script. Each `CREATE ROLE` `\password` line that prompts for the password in `psql`, so the script holds no password: ```sql +-- provision script, product documents. Nothing was run. +-- For a server where these objects do not exist yet. Review, then run with psql as an +-- administrator that has CREATEROLE and CREATEDB. It stops at the first error. +\set ON_ERROR_STOP on SET createrole_self_grant = 'set,inherit'; CREATE ROLE "documents_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \password "documents_migration" @@ -294,9 +300,10 @@ address. `DOCUMENTS_LOG` sets the level to `error`, `warn`, or `info`, the defau stops `documents serve` with exit status 2. A request that succeeds writes no log line. A refused request writes one `request refused` line that names `failed_check`, at most five per check per minute, with `suppressed` counting the rest, and `documents_request_refusals_total` counts every one (see -[Metrics](#watch-the-metrics)). A token verifier that cannot reach its key source answers 503 and is logged -the same way, as `request refused` with `failed_check` `key-source-unavailable`, not as a warning, so -`DOCUMENTS_LOG=warn` shows no line for it and the counter is the signal to alert on. A failure behind +[Metrics](#watch-the-metrics)). A token verifier that cannot fetch, read or use its key set answers 503. +A key endpoint it refuses to contact answers the refusal a bad credential gets. Both are logged as +`request refused` with `failed_check` `key-source-unavailable`, not as a warning, so +`DOCUMENTS_LOG=warn` shows no line for them and the counter is the signal to alert on. A failure behind a request, such as the database, is logged where it happens. Every audited operation, such as an upload, a download, or a grant, is in the audit journal. diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index c45530c3f7..d36e8ab6d4 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -246,13 +246,19 @@ use `--admin-url-env NAME`. The connection requires TLS and verifies the server `database.caBundleRef` in the runtime file to trust a private CA. The command never prints the administrator URL or a password. +The administrator URL must name the same host and port as the two product URLs, or `provision` +refuses it as `platform.provision.target-mismatch`. It must also name a database other than the +product database, such as `postgres`, or `provision` refuses it as `platform.provision.target-invalid`. +Where the administrator may connect only to the product database, `provision` cannot run: add +`--print-sql` and give the script to the person who administers the server. + The command: - Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. - Creates the database and closes it to `PUBLIC`. - Grants both roles `CONNECT` on the database. -- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it - from `PUBLIC`. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema and the runtime role `USAGE` + on it, and takes `CREATE` on it from `PUBLIC`. Run it again at any time. It creates only what is missing. It refuses a role that exists with a different password than its URL holds, and tells you which role. @@ -262,6 +268,10 @@ flags. The command connects to nothing and prints the script. Each `CREATE ROLE` `\password` line that prompts for the password in `psql`, so the script holds no password: ```sql +-- provision script, product messaging. Nothing was run. +-- For a server where these objects do not exist yet. Review, then run with psql as an +-- administrator that has CREATEROLE and CREATEDB. It stops at the first error. +\set ON_ERROR_STOP on SET createrole_self_grant = 'set,inherit'; CREATE ROLE "messaging_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \password "messaging_migration" diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index d18b4fa145..a8b4ac1612 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -146,7 +146,11 @@ schedulingctl provision --runtime-config /etc/registry-scheduling/runtime.yaml - The `admin-url` file holds one PostgreSQL URL for that administrator, for example `postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and `CREATEDB` and does not need to be a superuser. The URL must name the same host and port as the two -product URLs, or `provision` refuses it as `platform.provision.target-mismatch`. To pass the URL in +product URLs, or `provision` refuses it as `platform.provision.target-mismatch`. It must also name a +database other than the product database, such as `postgres`, or `provision` refuses it as +`platform.provision.target-invalid`. Where the administrator may connect only to the product +database, `provision` cannot run: add `--print-sql` and give the script to the person who +administers the server. To pass the URL in an environment variable instead, use `--admin-url-env NAME`. The connection requires TLS and verifies the server certificate. Set `database.caBundleRef` in the runtime file to trust a private CA. The command never prints the diff --git a/docs/site/src/content/docs/reference/errors.mdx b/docs/site/src/content/docs/reference/errors.mdx index de8b7d1182..3bb4818a3a 100644 --- a/docs/site/src/content/docs/reference/errors.mdx +++ b/docs/site/src/content/docs/reference/errors.mdx @@ -6,7 +6,7 @@ owner: registry-docs source_repos: - registry-evidence - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: reference locale: en standards_referenced: [] @@ -113,15 +113,17 @@ These products differ: - Casework and Scheduling answer 200 with the shared body `{"status":"ready"}`, and `/health` with `{"status":"ok"}`. - Coordinator answers 200 with `{"ready":true,"status":"ready"}` and 503 with `{"ready":false}`. - Scheduling also serves `/readyz`, a bodyless probe on the same readiness test, under its deployment health contract. -- Messaging and Documents answer without a body. +- Messaging and Documents answer 200 without a body, and 503 with a `service.unavailable` problem body and a `Retry-After` header. {/* Evidence: crates/registry-breg/src/problem.rs RuntimeNotReady; crates/registry-evidence-oid4vci/src/service.rs not_ready; crates/registry-platform-httputil/src/probe.rs READY_BODY; crates/registry-casework/src/http.rs ready; crates/registry-coordinator/src/http.rs ready; - crates/registry-scheduling/src/http.rs ready, readyz. */} -{/* TODO[evidence]: the generic `{"status":"not-ready"}` body and the bodyless Messaging and Documents readiness answers have no single code anchor. */} + crates/registry-scheduling/src/http.rs ready, readyz; + crates/registry-messaging/src/http.rs ready; + crates/registry-documents/src/http.rs ready. */} +{/* TODO[evidence]: the generic `{"status":"not-ready"}` body has no single code anchor. */} ## Idempotency and retries diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index 54c613a1fa..c9b59a4907 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -28,7 +28,9 @@ `--admin-url-file` or `--admin-url-env` over verified TLS, or prints the SQL with `--print-sql` and connects to nothing. Run it again at any time: it creates only what is missing and refuses a role that exists with different - attributes. It loads the whole runtime file and verifies the package first. + attributes. It also grants the runtime role USAGE on the `public` schema, + and running it again restores that grant. It loads the whole runtime file + and verifies the package first. - `GET /health` answers `{"status":"ok"}` and `GET /ready` answers `{"status":"ready"}` as `application/json`, in place of an empty 200. Both diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index f3541c440c..6f82cce568 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -6098,11 +6098,11 @@ "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions.", "source": { "path": "crates/registry-platform-provision/src/cli.rs", - "sha256": "bce58d08771dc21d7d4ceeda472f4709105066979298ab3bfd188d484c53c503" + "sha256": "43ad277b6695e1ceff8bdf6b917f19e19531a2fa954d4a8283367615bf3f17b7" }, "artifact": { "path": "crates/registry-platform-provision/schema/provision-report.schema.json", - "sha256": "e0e39e826b35c83161ea544805d6b33a18bd1365033fd497022cefe05f30b0bb", + "sha256": "9be2b180528a351d3e18b336f062da0e48c57aba3311ed048703ca56822e83de", "mediaType": "application/schema+json" } }, diff --git a/products/messaging/CHANGELOG.md b/products/messaging/CHANGELOG.md index a351fc1fb3..05e5f78e41 100644 --- a/products/messaging/CHANGELOG.md +++ b/products/messaging/CHANGELOG.md @@ -20,8 +20,7 @@ runtime roles and the database from the runtime file's two database URLs, as a non-superuser administrator over verified TLS, or prints the script with `--print-sql`. It also grants the runtime role USAGE on the `public` schema, - and running it again restores that grant. The operate page no longer gives - hand SQL. + and running it again restores that grant. - A plain `http` provider base URL and an SMTP relay in development use the same loopback rule: `127.0.0.0/8`, `::1`, or an IPv4-mapped form of `127.0.0.0/8`. The name `localhost` is accepted for a provider base URL as diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index ce2fdf969c..47235331c8 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -80,14 +80,23 @@ product's schema layout and the optional `btree_gist` and PostGIS extensions. It can run as an administrator over verified TLS, converging by object, or print a `psql` script that holds no password and stops at the - first error. It refuses an existing role with other attributes, role-level - settings or a membership it did not grant, a template database, a PostGIS - installed outside its schema or without the bbox membership, a role name - that is `public`, `none` or starts with `pg_`, a name with a control - character or backslash, and the `postgres`, `template0` and `template1` - databases. It grants the runtime role `USAGE` on `public` directly, so + first error. It refuses an existing role with other attributes or a + membership it did not grant, a `role`, `search_path` or + `session_authorization` default for a product role, in every database or + the product's (`platform.provision.role-settings-differ`), a template + database, a PostGIS installed outside its schema or without the bbox + membership, a role name that is `public`, `none` or starts with `pg_`, a + name with a control character, a backslash or a bidirectional formatting + character, a database name that starts with `postgresql://` or + `postgres://`, and the `postgres`, `template0` and `template1` databases. + Other role settings, such as `statement_timeout` or `jit`, are accepted on + a rerun. It grants the runtime role `USAGE` on `public` directly, so running `provision` again restores it. A run that stops part-way reports - the statements that ran. `registry-platform-activation` exports + the statements that ran, in text output as well, and the report's + `executed` is true whenever a statement ran. A session that cannot open in + the new database is `platform.provision.database-connect-failed`, and a + connection limit reached by a product login is an operational failure + (exit 3). `registry-platform-activation` exports `MINIMUM_SERVER_VERSION_NUM`, the PostgreSQL 17 floor the plan and the activation ledger share. `rstack dev` provisions its databases from the same plan. From 991d91c30d5b520cdc21e3f3203d9ba8655cef35 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:35:38 +0100 Subject: [PATCH 055/136] test(platform): key the journey and token tables on change names The token corpus and the journey failure table name the change that alters a result by a public change name, such as caller-contract, in place of an opaque milestone number, and the failure rows no longer carry finding ids. The token fixture check accepts none or a lowercase kebab-case change name. Signed-off-by: Jeremi Joslin --- .../src/token_fixtures.rs | 28 +- .../tests/token_fixtures.rs | 38 +- .../platform/conformance/tokens/README.md | 6 +- .../platform/conformance/tokens/expected.yaml | 378 +++++++++--------- products/platform/journeys/README.md | 6 +- .../platform/journeys/expected-failures.yaml | 83 ++-- products/platform/journeys/own-provider.sh | 4 +- products/platform/journeys/products.yaml | 2 +- .../platform/journeys/test_journey_tables.py | 8 +- products/platform/journeys/test_lib.sh | 8 +- 10 files changed, 298 insertions(+), 263 deletions(-) diff --git a/crates/registry-platform-testing/src/token_fixtures.rs b/crates/registry-platform-testing/src/token_fixtures.rs index 6619ecd04d..518b6fb886 100644 --- a/crates/registry-platform-testing/src/token_fixtures.rs +++ b/crates/registry-platform-testing/src/token_fixtures.rs @@ -565,7 +565,7 @@ pub enum Basis { pub struct ExpectedCell { pub main: Outcome, pub target: Outcome, - #[serde(deserialize_with = "milestone_or_none")] + #[serde(deserialize_with = "change_or_none")] pub changed_by: Option, pub landed: Option, pub basis: Basis, @@ -574,7 +574,7 @@ pub struct ExpectedCell { } impl ExpectedCell { - /// What a test asserts: `target` where the milestone has landed, `main` + /// What a test asserts: `target` where the change has landed, `main` /// everywhere else. #[must_use] pub fn expected(&self) -> &Outcome { @@ -586,19 +586,33 @@ impl ExpectedCell { } } -fn milestone_or_none<'de, D: serde::Deserializer<'de>>( +/// A change name is lowercase kebab-case: `caller-contract`. +fn is_change_name(text: &str) -> bool { + let mut words = text.split('-'); + let word_ok = |word: &str| { + !word.is_empty() + && word + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + }; + words + .next() + .is_some_and(|first| word_ok(first) && first.starts_with(|c: char| c.is_ascii_lowercase())) + && words.all(word_ok) +} + +fn change_or_none<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { let text = String::deserialize(deserializer)?; if text == "none" { return Ok(None); } - let digits = text.strip_prefix('M').unwrap_or(""); - if !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) { + if is_change_name(&text) { Ok(Some(text)) } else { Err(serde::de::Error::custom(format!( - "changedBy `{text}` is neither `none` nor a milestone like `M7`" + "changedBy `{text}` is neither `none` nor a lowercase kebab-case change name like `caller-contract`" ))) } } @@ -1095,7 +1109,7 @@ impl TokenCorpus { for (product, cell) in &row.products { if cell.landed.is_some() != cell.changed_by.is_some() { return fail(format!( - "`{}` / `{product}`: landed appears exactly when changedBy is a milestone", + "`{}` / `{product}`: landed appears exactly when changedBy is a change name", row.fixture )); } diff --git a/crates/registry-platform-testing/tests/token_fixtures.rs b/crates/registry-platform-testing/tests/token_fixtures.rs index 43e840dc79..48863b0e3c 100644 --- a/crates/registry-platform-testing/tests/token_fixtures.rs +++ b/crates/registry-platform-testing/tests/token_fixtures.rs @@ -8,8 +8,8 @@ use std::collections::BTreeSet; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use registry_platform_testing::{ - Against, Binding, Comparison, Configuration, FixtureClass, Outcome, Stage, TokenCorpus, - TokenFixture, TokenSigner, + Against, Binding, Comparison, Configuration, ExpectedCell, FixtureClass, Outcome, Stage, + TokenCorpus, TokenFixture, TokenSigner, }; use serde_json::{json, Value}; @@ -322,8 +322,40 @@ fn no_negative_fixture_is_expected_to_be_admitted() { } } +fn cell_with_changed_by(changed_by: &str) -> Result { + serde_json::from_value(json!({ + "main": "refused/scope", + "target": "admitted", + "basis": "observed", + "changedBy": changed_by, + "landed": false, + })) +} + +#[test] +fn changed_by_is_a_change_name_or_none() { + for accepted in ["caller-contract", "posture", "none"] { + cell_with_changed_by(accepted) + .unwrap_or_else(|error| panic!("`{accepted}` is refused: {error}")); + } + for refused in [ + "M7", + "Caller-Contract", + "caller_contract", + "-caller", + "caller-", + "7th", + "", + ] { + let error = cell_with_changed_by(refused) + .expect_err(&format!("`{refused}` is accepted")) + .to_string(); + assert!(error.contains("changedBy"), "unhelpful error: {error}"); + } +} + #[test] -fn landed_appears_exactly_when_a_milestone_changes_the_cell() { +fn landed_appears_exactly_when_a_change_alters_the_cell() { let corpus = corpus(); for row in &corpus.expectations().rows { for (product, cell) in &row.products { diff --git a/products/platform/conformance/tokens/README.md b/products/platform/conformance/tokens/README.md index 93f25febf0..e7269c3238 100644 --- a/products/platform/conformance/tokens/README.md +++ b/products/platform/conformance/tokens/README.md @@ -94,14 +94,14 @@ A cell holds: - `main`: the result today. - `target`: the result the caller contract work aims for. -- `changedBy`: the milestone that changes the result, such as `M7`, or `none`. -- `landed`: present when `changedBy` is a milestone. It is `false` until that milestone makes `target` true. +- `changedBy`: the change that alters the result, a name such as `caller-contract`, or `none`. +- `landed`: present when `changedBy` is a change name. It is `false` until that change makes `target` true. - `basis`: `inferred` while `main` is a reading of the code, `observed` once a test has run the fixture through the product. - `reason` and `targetReason`: why a `main` or a `target` is `unknown`, `n-a` or `none`, or why a product cannot follow one of the driver's choices listed at the head of `expected.yaml`. A result is `admitted`, `admitted/`, `admitted/unspecified`, `refused/`, `none`, `n-a` or `unknown`. A stage is one of the verifier's labels (`header`, `algorithm`, `token-type`, `key`, `signature`, `issuer`, `audience`, `time`, `client`, `scope`, `profile`, `unavailable`) or `claims`, which a product uses for its own claim checks. -The test asserts `target` where `landed` is `true` and `main` everywhere else. Work on a milestone goes row by row. Set `landed: true`, watch the test fail, make the change, watch it pass. +The test asserts `target` where `landed` is `true` and `main` everywhere else. Work on a change goes row by row. Set `landed: true`, watch the test fail, make the change, watch it pass. The head of `expected.yaml` lists the choices the driver makes for every row, such as which client list and which read scope a product is given. diff --git a/products/platform/conformance/tokens/expected.yaml b/products/platform/conformance/tokens/expected.yaml index 35c558275b..3fb5525ebd 100644 --- a/products/platform/conformance/tokens/expected.yaml +++ b/products/platform/conformance/tokens/expected.yaml @@ -10,8 +10,8 @@ # when a characterisation test observes a different result, and then the # cell's `basis` becomes `observed` # target the result the caller-contract work is meant to give -# changedBy the milestone that changes the result, or `none` -# landed false until that milestone makes `target` true. A test asserts `target` +# changedBy the change that alters the result, or `none` +# landed false until that change makes `target` true. A test asserts `target` # where `landed` is true and `main` otherwise # basis inferred or observed # reason why `main` is `unknown` or `n-a` @@ -52,14 +52,14 @@ rows: configuration: default products: breg: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } - casework: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + casework: { main: refused/scope, basis: observed, target: admitted, changedBy: caller-contract, landed: false } messaging: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } scheduling: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } documents: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } - coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: caller-contract, landed: false } adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } - evidence: { main: refused/claims, basis: observed, target: admitted/human, changedBy: M7, landed: false } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + evidence: { main: refused/claims, basis: observed, target: admitted/human, changedBy: caller-contract, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } - fixture: thunderid-user-access @@ -73,8 +73,8 @@ rows: documents: { main: admitted/human, basis: observed, target: admitted/human, changedBy: none } coordinator: { main: admitted, basis: observed, target: admitted, changedBy: none } adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } - evidence: { main: refused/claims, basis: observed, target: admitted/human, changedBy: M7, landed: false } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + evidence: { main: refused/claims, basis: observed, target: admitted/human, changedBy: caller-contract, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } - fixture: thunderid-client-credentials @@ -82,14 +82,14 @@ rows: configuration: default products: breg: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } - casework: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + casework: { main: refused/scope, basis: observed, target: admitted, changedBy: caller-contract, landed: false } messaging: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } scheduling: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } documents: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } - coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: caller-contract, landed: false } adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } - evidence: { main: refused/claims, basis: observed, target: admitted/service, changedBy: M7, landed: false } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + evidence: { main: refused/claims, basis: observed, target: admitted/service, changedBy: caller-contract, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } - fixture: thunderid-client-credentials @@ -103,8 +103,8 @@ rows: documents: { main: admitted/service, basis: observed, target: admitted/service, changedBy: none } coordinator: { main: admitted, basis: observed, target: admitted, changedBy: none } adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } - evidence: { main: refused/claims, basis: observed, target: admitted/service, changedBy: M7, landed: false } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + evidence: { main: refused/claims, basis: observed, target: admitted/service, changedBy: caller-contract, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } - fixture: thunderid-client-credentials @@ -118,7 +118,7 @@ rows: documents: { main: refused/profile, basis: observed, target: refused/profile, changedBy: none } coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - evidence: { main: refused/claims, basis: observed, target: refused/profile, changedBy: M7, landed: false } + evidence: { main: refused/claims, basis: observed, target: refused/profile, changedBy: caller-contract, landed: false } render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } @@ -141,17 +141,17 @@ rows: against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - coordinator: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - adapter: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - render: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + coordinator: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + adapter: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + render: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } - fixture: keycloak-client-credentials against: plain-read configuration: default @@ -171,17 +171,17 @@ rows: against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - coordinator: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - adapter: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - render: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + coordinator: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + adapter: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + render: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } - fixture: keycloak-client-credentials-stock against: plain-read configuration: default @@ -216,17 +216,17 @@ rows: against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } messaging: { main: none, basis: inferred, target: none, changedBy: none } - scheduling: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + scheduling: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } documents: { main: none, basis: inferred, target: none, changedBy: none } - coordinator: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - adapter: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - evidence: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - render: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + coordinator: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + adapter: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } mcp-edge: { main: none, basis: inferred, target: refused/client, changedBy: none } - evidence-oid4vci: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence-oid4vci: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - fixture: supabase-oauth-server-user-access against: plain-read configuration: default @@ -246,17 +246,17 @@ rows: against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - messaging: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - scheduling: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - documents: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - coordinator: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - adapter: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - evidence: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - render: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - mcp-edge: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - evidence-oid4vci: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + messaging: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + scheduling: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + documents: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + coordinator: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + adapter: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + mcp-edge: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence-oid4vci: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - fixture: entra-v2-user-access against: plain-read configuration: default @@ -276,17 +276,17 @@ rows: against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - coordinator: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - adapter: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - render: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + coordinator: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + adapter: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + render: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } - fixture: entra-v2-app-access against: plain-read configuration: default @@ -306,17 +306,17 @@ rows: against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - coordinator: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - adapter: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: M7, landed: false } - render: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } - evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: M7, landed: false } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + scheduling: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + documents: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + coordinator: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + adapter: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + evidence: { main: none, basis: inferred, target: admitted/unspecified, changedBy: caller-contract, landed: false } + render: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + mcp-edge: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: admitted, changedBy: caller-contract, landed: false } - fixture: identity-only against: plain-read configuration: default @@ -336,44 +336,44 @@ rows: against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } messaging: { main: none, basis: inferred, target: none, changedBy: none } - scheduling: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + scheduling: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } documents: { main: none, basis: inferred, target: none, changedBy: none } - coordinator: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - adapter: { main: none, basis: inferred, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + coordinator: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + adapter: { main: none, basis: inferred, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } mcp-edge: { main: refused/client, basis: observed, target: refused/client, changedBy: none } - evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - fixture: rstack-dev-run-user against: plain-read configuration: default products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: refused/scope, basis: observed, target: admitted, changedBy: caller-contract, landed: false } messaging: { main: admitted/unspecified, basis: observed, target: admitted/unspecified, changedBy: none } - scheduling: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - documents: { main: refused/profile, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided in M7" } - coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: M7, landed: false } + scheduling: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + documents: { main: refused/profile, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided by the caller-contract change" } + coordinator: { main: refused/scope, basis: observed, target: admitted, changedBy: caller-contract, landed: false } adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } - evidence: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + evidence: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } mcp-edge: { main: admitted, basis: observed, target: admitted, changedBy: none } evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } - fixture: keycloak-client-credentials against: human-only-profile configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: refused/profile, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + breg: { main: refused/claims, basis: observed, target: refused/profile, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: refused/profile, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: refused/profile, changedBy: caller-contract, landed: false } scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } - documents: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: refused/profile, changedBy: caller-contract, landed: false } coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - evidence: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + evidence: { main: none, basis: inferred, target: refused/profile, changedBy: caller-contract, landed: false } render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } @@ -381,14 +381,14 @@ rows: against: human-only-profile configuration: recipe products: - breg: { main: none, basis: observed, target: refused/profile, changedBy: M7, landed: false, reason: "BReg does not start: a profile that names requester clients cannot be combined with allowedClients unrestricted" } - casework: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + breg: { main: none, basis: observed, target: refused/profile, changedBy: caller-contract, landed: false, reason: "BReg does not start: a profile that names requester clients cannot be combined with allowedClients unrestricted" } + casework: { main: none, basis: inferred, target: refused/profile, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: refused/profile, changedBy: caller-contract, landed: false } scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } - documents: { main: none, basis: inferred, target: refused/profile, changedBy: M7, landed: false } + documents: { main: none, basis: inferred, target: refused/profile, changedBy: caller-contract, landed: false } coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - evidence: { main: refused/scope, basis: observed, target: refused/profile, changedBy: M7, landed: false } + evidence: { main: refused/scope, basis: observed, target: refused/profile, changedBy: caller-contract, landed: false } render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } @@ -412,16 +412,16 @@ rows: configuration: jwt-accepted products: breg: { main: refused/audience, basis: observed, target: refused/audience, changedBy: none } - casework: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - documents: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - adapter: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - evidence: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - render: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + documents: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + adapter: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + evidence: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + render: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } - fixture: keycloak-id-token against: plain-read configuration: default @@ -442,16 +442,16 @@ rows: configuration: jwt-accepted products: breg: { main: refused/audience, basis: observed, target: refused/audience, changedBy: none } - casework: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - documents: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - adapter: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - evidence: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - render: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + documents: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + adapter: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + evidence: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + render: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } - fixture: supabase-id-token against: plain-read configuration: default @@ -472,16 +472,16 @@ rows: configuration: jwt-accepted products: breg: { main: refused/audience, basis: observed, target: refused/audience, changedBy: none } - casework: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - documents: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - adapter: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - evidence: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - render: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } - evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: M7, landed: false } + casework: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + scheduling: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + documents: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + coordinator: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + adapter: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + evidence: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + render: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + mcp-edge: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: refused/audience, changedBy: caller-contract, landed: false } - fixture: entra-id-token against: plain-read configuration: default @@ -501,17 +501,17 @@ rows: against: plain-read configuration: jwt-accepted products: - breg: { main: refused/client, basis: observed, target: refused/token-type, changedBy: M7, landed: false } - casework: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - messaging: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - scheduling: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - documents: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - coordinator: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - adapter: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - evidence: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - render: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - mcp-edge: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } - evidence-oid4vci: { main: none, basis: inferred, target: refused/token-type, changedBy: M7, landed: false } + breg: { main: refused/client, basis: observed, target: refused/token-type, changedBy: caller-contract, landed: false } + casework: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + messaging: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + scheduling: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + documents: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + coordinator: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + adapter: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + evidence: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + render: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + mcp-edge: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } + evidence-oid4vci: { main: none, basis: inferred, target: refused/token-type, changedBy: caller-contract, landed: false } - fixture: keycloak-refresh-token against: plain-read configuration: default @@ -606,62 +606,62 @@ rows: against: plain-read configuration: default products: - breg: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "a token with no actor kind passes authentication as unspecified. The audience, scope claim and client rule are issuer-block lines. The holder profile limits rows by holder_ref, and no national claim is passed through" } - casework: { main: refused/audience, basis: observed, target: admitted, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } + breg: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "a token with no actor kind passes authentication as unspecified. The audience, scope claim and client rule are issuer-block lines. The holder profile limits rows by holder_ref, and no national claim is passed through" } + casework: { main: refused/audience, basis: observed, target: admitted, changedBy: caller-contract, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } messaging: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: none, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product"} - scheduling: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } - documents: { main: refused/audience, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided in M7" } - coordinator: { main: refused/audience, basis: observed, target: admitted, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } + scheduling: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } + documents: { main: refused/audience, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided by the caller-contract change" } + coordinator: { main: refused/audience, basis: observed, target: admitted, changedBy: caller-contract, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } adapter: { main: refused/audience, basis: observed, target: admitted, changedBy: none, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product"} - evidence: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } - render: { main: refused/audience, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + evidence: { main: refused/audience, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product" } + render: { main: refused/audience, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } mcp-edge: { main: refused/audience, basis: observed, target: admitted, changedBy: none, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product"} evidence-oid4vci: { main: refused/audience, basis: observed, target: admitted, changedBy: none, reason: "observed: the token's literal aud (https://resource.example.test) is not the audience the driver configures for the product"} - fixture: thunderid-exchanged-holder against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "a token with no actor kind passes authentication as unspecified. The audience, scope claim and client rule are issuer-block lines. The holder profile limits rows by holder_ref, and no national claim is passed through" } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "a token with no actor kind passes authentication as unspecified. The audience, scope claim and client rule are issuer-block lines. The holder profile limits rows by holder_ref, and no national claim is passed through" } casework: { main: admitted, basis: observed, target: admitted, changedBy: none } messaging: { main: admitted/unspecified, basis: observed, target: admitted/unspecified, changedBy: none } - scheduling: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - documents: { main: refused/profile, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided in M7" } + scheduling: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + documents: { main: refused/profile, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "every Documents profile requires an actor kind and this token declares none; the declared actor kind is decided by the caller-contract change" } coordinator: { main: admitted, basis: observed, target: admitted, changedBy: none } adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } - evidence: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } + evidence: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries records:get", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } mcp-edge: { main: none, basis: observed, target: admitted, changedBy: none, reason: "observed: the edge serves one MCP path, so the token's literal audience, which is not an /mcp URL, cannot be configured"} evidence-oid4vci: { main: admitted, basis: observed, target: admitted, changedBy: none } - fixture: thunderid-exchanged-holder-no-scope against: plain-read configuration: default products: - breg: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - casework: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - documents: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + breg: { main: refused/claims, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + casework: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + documents: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } - evidence: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "no result is defined yet for a token that carries no scope claim" } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries no scope claim", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } - mcp-edge: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - evidence-oid4vci: { main: admitted, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence: { main: refused/claims, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries no scope claim", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } + mcp-edge: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence-oid4vci: { main: admitted, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed in the characterisation run: the cause was not traced", targetReason: "no result is defined yet for a token that carries no scope claim" } - fixture: thunderid-exchanged-holder-no-scope against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - casework: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - documents: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + breg: { main: refused/claims, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + casework: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + documents: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } adapter: { main: admitted, basis: observed, target: admitted, changedBy: none } - evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries no scope claim", targetReason: "whether the caller contract gives Render a configurable scope is decided in M7" } - mcp-edge: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "Render requires the fixed scope render:render and has no scope setting; the fixture carries no scope claim", targetReason: "whether the caller contract gives Render a configurable scope is decided by the caller-contract change" } + mcp-edge: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } + evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no scope claim" } - fixture: esignet-standin-id-token against: plain-read configuration: default @@ -787,29 +787,29 @@ rows: against: plain-read configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: M7, landed: false } - casework: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } + breg: { main: refused/claims, basis: observed, target: admitted/unspecified, changedBy: caller-contract, landed: false } + casework: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } messaging: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } - scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } + scheduling: { main: refused/claims, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } documents: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } - coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } - adapter: { main: admitted, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } - evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } - render: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } + coordinator: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } + adapter: { main: admitted, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } + evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } + render: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "no result is defined yet for a token that carries no registry scope" } mcp-edge: { main: refused/scope, basis: observed, target: refused/scope, changedBy: none, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "the token proves identity only" } - evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } + evidence-oid4vci: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "no result is defined yet for a token that carries no registry scope" } - fixture: thunderid-user-access-identity-only against: human-only-profile configuration: recipe products: - breg: { main: refused/claims, basis: observed, target: unknown, changedBy: M7, landed: false, targetReason: "decided with the actor kind an operator declares for the client (M7)" } - casework: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client (M7)" } - messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client (M7)" } + breg: { main: refused/claims, basis: observed, target: unknown, changedBy: caller-contract, landed: false, targetReason: "decided with the actor kind an operator declares for the client, by the caller-contract change" } + casework: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client, by the caller-contract change" } + messaging: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client, by the caller-contract change" } scheduling: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "Scheduling records the actor kind and no access profile pins it" } - documents: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client (M7)" } + documents: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client, by the caller-contract change" } coordinator: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } adapter: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } - evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: M7, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client (M7)" } + evidence: { main: refused/scope, basis: observed, target: unknown, changedBy: caller-contract, landed: false, reason: "observed: the token carries no registry scope, so the scope the profile requires is not met", targetReason: "decided with the actor kind an operator declares for the client, by the caller-contract change" } render: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } mcp-edge: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } evidence-oid4vci: { main: n-a, basis: inferred, target: n-a, changedBy: none, reason: "no access profile in this product pins an actor kind" } diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index 7c56084f3d..2b7303d7e3 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -4,7 +4,7 @@ This folder holds the tables behind three acceptance journeys and a static check of those tables. A journey walks one product from nothing to a first authenticated call, or from a development run to a production start, using only what a reader of the documentation has. The tables say where each journey stops -for each product today and which milestone removes the stop. +for each product today and which change removes the stop. ## The three journeys @@ -61,7 +61,7 @@ journey run replaces it with the code the run saw and sets `observed`. A harness failure, such as a container that did not start, is never a row. A journey run in ratchet mode succeeds when every cell matches the table. A -milestone that fixes a cell deletes the row in the same commit and adds the +change that fixes a cell deletes the row in the same commit and adds the cell to `passes`. A fix that is not recorded fails the run, and so does a new failure that the table does not list. @@ -84,7 +84,7 @@ It checks that: thresholds, and the full reader-time model - the concept list has unique, well-formed entries - every journey and product cell appears exactly once, every step belongs to its - journey, every code is valid, every failure row names a listed milestone, + journey, every code is valid, every failure row names a listed change, and every row records its basis and a reason - journey scripts, when they exist, call none of `openssl`, `mkcert`, `keytool`, `psql`, `docker build` or `docker exec`, outside `lib-assists.sh`, and the diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index a09611761f..aa414f7d58 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -1,12 +1,12 @@ # The ratchet table of the acceptance journeys: where each journey stops for -# each product on `main`, and which milestone removes the stop. +# each product on `main`, and which change removes the stop. # # A cell is one journey and one product. Every cell of the journeys and products # in this folder appears exactly once, as an expected failure or as unreached, # or in `passes` once a cell passes. A cell fails at its first failing step with # one code. In ratchet mode a journey exits 0 when every cell equals this table. # A cell that fails differently, or no longer fails while still listed, fails -# the run. A milestone that fixes a cell deletes its row in the same commit and +# the run. A change that fixes a cell deletes its row in the same commit and # adds the cell to `passes`. # # basis: predicted inferred from reading code. The first journey run on @@ -47,16 +47,15 @@ journeyCodeSuffixes: attach: [issuer-refused] authenticationStages: [header, algorithm, token-type, key, signature, issuer, audience, time, client, scope, profile, unavailable] -# Milestones of the plan that can remove a row. -milestones: [M1, M2, M3, M4, M5, M6, M7, M8, M9, M10, M11, M12, M13, M14, M15, M16] +# Changes that can remove a row. +changes: [posture, rstack-dev-products, caller-contract] expectedFailures: - journey: own-provider product: breg step: database.provision code: journey.needs.hand-written-sql - finding: X13 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" reason: "prepare and issuer pass (bregctl check accepts the Keycloak issuer with RS256). bregctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." @@ -64,8 +63,7 @@ expectedFailures: product: casework step: database.provision code: journey.needs.hand-written-sql - finding: X13 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" reason: "prepare and issuer pass (caseworkctl check). caseworkctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." @@ -73,8 +71,7 @@ expectedFailures: product: messaging step: database.provision code: journey.needs.hand-written-sql - finding: X13 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" reason: "prepare and issuer pass (messagingctl check). messagingctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." @@ -82,8 +79,7 @@ expectedFailures: product: scheduling step: database.provision code: journey.needs.hand-written-sql - finding: X13 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" reason: "prepare and issuer pass (schedulingctl check). schedulingctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." @@ -91,8 +87,7 @@ expectedFailures: product: documents step: database.provision code: journey.needs.hand-written-sql - finding: X13 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" reason: "prepare and issuer pass (documentsctl check). documentsctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." @@ -100,8 +95,7 @@ expectedFailures: product: coordinator step: database.provision code: journey.needs.hand-written-sql - finding: X13 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" reason: "prepare and issuer pass (coordinatorctl check, with the deployment block written by hand). coordinatorctl provision is refused with coordinator.cli.usage (unrecognized command), so roles, the database and grants are made by hand." @@ -109,8 +103,7 @@ expectedFailures: product: adapter step: database.provision code: journey.needs.hand-written-sql - finding: X13 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" reason: "prepare and issuer pass (adapterctl check of the facade-recovery example with the breg-records profile). adapterctl provision --runtime-config R --admin-url-file A is refused as an unrecognized subcommand, so roles, the database and grants are made by hand." @@ -118,17 +111,15 @@ expectedFailures: product: evidence step: issuer code: product.evidence.bundle.invalid-authentication - finding: X1 - removedBy: M1 + removedBy: posture basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" - reason: "evidencectl check refuses the local target (outer code evidence.target.publication-invalid): the local profile takes only a canonical 127.0.0.1 HTTP origin with a port, and a Keycloak issuer carries the /realms/ path, so any such issuer needs allowInsecureHttp: true. The loopback transport class of M1 (A2) removes the URL-shape rule. Behind it the call is predicted to stop at token-type, because Keycloak sends typ JWT." + reason: "evidencectl check refuses the local target (outer code evidence.target.publication-invalid): the local profile takes only a canonical 127.0.0.1 HTTP origin with a port, and a Keycloak issuer carries the /realms/ path, so any such issuer needs allowInsecureHttp: true. The loopback transport class of the posture change removes the URL-shape rule. Behind it the call is predicted to stop at token-type, because Keycloak sends typ JWT." - journey: own-provider product: render step: call code: product.render.unauthorized - finding: G3 - removedBy: M7 + removedBy: caller-contract basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127021546-ddef" reason: "No database. Start, ready and the client-credentials token pass (RS256, audience urn:example:render, scope render:render, client portal). POST /v1/render/letter answers 401 with problem render.unauthorized. Render logs no authentication stage, so the code is the problem code. Inferred cause: the token type fixed at at+jwt (registry-render/src/auth.rs:71 on main) against Keycloak's typ JWT." @@ -137,8 +128,7 @@ expectedFailures: product: breg step: plan code: journey.needs.hand-written-plan - finding: FH-4 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "bregctl init writes a project with no dev.yaml. rstack dev check refuses it with rstack.dev.check-unavailable (cannot read dev.yaml), so the only way forward is a plan the reader writes." @@ -146,7 +136,7 @@ expectedFailures: product: casework step: plan code: journey.needs.hand-written-plan - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "caseworkctl init writes casework.yaml with no dev.yaml. rstack dev check refuses it with rstack.dev.check-unavailable. Its own next step tells the reader to write a dev.yaml plan." @@ -154,8 +144,7 @@ expectedFailures: product: messaging step: keep code: journey.keep.state-lost - finding: FH-3 - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "init ships a dev.yaml and the run reaches call (HTTP 202). After rstack dev stop and a second rstack dev start of the same project, the message the first run accepted answers HTTP 404, because every start draws fresh databases." @@ -163,7 +152,7 @@ expectedFailures: product: evidence step: plan code: journey.needs.hand-written-plan - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "evidencectl init --profile local --transport sqlite-extract writes a project with no dev.yaml, so rstack dev check refuses it with rstack.dev.check-unavailable. The attach step is not reached." @@ -171,7 +160,7 @@ expectedFailures: product: scheduling step: plan code: product.config.unknown-variant - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "init succeeds and writes no dev.yaml. A hand-written dev.yaml naming scheduling is refused with config.unknown-variant at /products/0/product: expected one of breg, casework, evidence, messaging." @@ -179,7 +168,7 @@ expectedFailures: product: documents step: plan code: product.config.unknown-variant - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "init succeeds and writes no dev.yaml. A hand-written dev.yaml naming documents is refused with config.unknown-variant at /products/0/product: expected one of breg, casework, evidence, messaging." @@ -187,7 +176,7 @@ expectedFailures: product: coordinator step: plan code: product.config.unknown-variant - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "init succeeds and writes no dev.yaml. A hand-written dev.yaml naming coordinator is refused with config.unknown-variant at /products/0/product: expected one of breg, casework, evidence, messaging." @@ -195,7 +184,7 @@ expectedFailures: product: render step: plan code: product.config.unknown-variant - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "init succeeds and writes no dev.yaml. A hand-written dev.yaml naming render is refused with config.unknown-variant at /products/0/product: expected one of breg, casework, evidence, messaging." @@ -203,7 +192,7 @@ expectedFailures: product: adapter step: init code: product.adapterctl.usage-invalid - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "adapterctl has no init command. adapterctl --format json init DIR is refused with adapterctl.usage-invalid (unrecognized subcommand), so there is no starter project to plan from." @@ -211,7 +200,7 @@ expectedFailures: product: discovery step: init code: product.discovery.usage.invalid-arguments - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127014337-dc92" reason: "discoveryctl has no init command. discoveryctl init DIR is refused with discovery.usage.invalid-arguments (unrecognized subcommand), so there is no starter project to plan from." @@ -220,7 +209,7 @@ expectedFailures: product: breg step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -228,7 +217,7 @@ expectedFailures: product: casework step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -236,7 +225,7 @@ expectedFailures: product: messaging step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -244,7 +233,7 @@ expectedFailures: product: evidence step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -252,7 +241,7 @@ expectedFailures: product: scheduling step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -260,7 +249,7 @@ expectedFailures: product: documents step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -268,7 +257,7 @@ expectedFailures: product: coordinator step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -276,7 +265,7 @@ expectedFailures: product: adapter step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -284,7 +273,7 @@ expectedFailures: product: render step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." @@ -292,7 +281,7 @@ expectedFailures: product: discovery step: input code: journey.promote.no-input - removedBy: M4 + removedBy: rstack-dev-products basis: observed observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The own-provider cell of discovery is unreached (it verifies no token and keeps no database), so there are no files to promote." @@ -422,8 +411,8 @@ unreached: # product: scheduling # step: refusals # code: journey.promote.nothing-refused -# removedBy: M6 +# removedBy: posture # basis: observed # observedOn: "bin-4eb643d6 (runtime code equals origin/main cd83550e), promote run 20261127025000-816f on own-provider run 20261127024425-265d (assisted: sql, certificate, token-type, mapper)" -# reason: "The assisted Scheduling cell reached T1. Started with no development declaration, schedulingctl check (which has no --production flag) lists no refusal and the server starts and answers /readyz, so zero refusals are listed. No shared posture exists on main, so nothing can refuse. The count becomes meaningful at M1 with M6." +# reason: "The assisted Scheduling cell reached T1. Started with no development declaration, schedulingctl check (which has no --production flag) lists no refusal and the server starts and answers /readyz, so zero refusals are listed. No shared posture exists on main, so nothing can refuse. The count becomes meaningful once the posture change lands." passes: [] diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 9c77207775..9faf1ccf6f 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -1109,12 +1109,12 @@ step_call() { } # hook: the products whose runtime format has hook destinations need the -# receiver container the hook milestone adds; the others deliver nothing, so +# receiver container the private-network-destinations change adds; the others deliver nothing, so # the step has no command for them. step_hook() { case "$CELL" in breg | scheduling | documents) - journey_unreached hook "The product delivers hooks, and the journey has no receiver for them until the hook milestone (M8) adds one." + journey_unreached hook "The product delivers hooks, and the journey has no receiver for them until the private-network-destinations change adds one." CELL_OVER=1 ;; *) journey_pass hook ;; diff --git a/products/platform/journeys/products.yaml b/products/platform/journeys/products.yaml index eeb4f36aad..8e0ecf7a77 100644 --- a/products/platform/journeys/products.yaml +++ b/products/platform/journeys/products.yaml @@ -10,7 +10,7 @@ # ctl names the crate of the matching tool. It is null where the tool is a # binary of the runtime's own crate (coordinatorctl) or where none exists. # -# usesPostgres, verifiesTokens and rstackDevPlan describe `main`. A milestone +# usesPostgres, verifiesTokens and rstackDevPlan describe `main`. A change # that changes one edits the row in the same commit. schema: registry.journey-products/v1 diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 6491fd6e41..37bb8aabc9 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -223,15 +223,15 @@ def test_every_row_says_why(self): for kind, row in self.rows: self.assertTrue(row["reason"].strip(), f"{kind} {cell(row)}") - def test_failure_rows_name_a_code_and_the_milestone_that_removes_them(self): - milestones = set(self.data["milestones"]) + def test_failure_rows_name_a_code_and_the_change_that_removes_them(self): + changes = set(self.data["changes"]) for row in self.data["expectedFailures"]: self.assertEqual( - set(row) - {"finding", "observedOn"}, + set(row) - {"observedOn"}, {"journey", "product", "step", "code", "removedBy", "basis", "reason"}, cell(row), ) - self.assertIn(row["removedBy"], milestones, cell(row)) + self.assertIn(row["removedBy"], changes, cell(row)) self.assertTrue(self.code_is_valid(row["code"]), f"{cell(row)}: {row['code']}") def test_unreached_rows_have_no_code(self): diff --git a/products/platform/journeys/test_lib.sh b/products/platform/journeys/test_lib.sh index 1756d95cc8..34958a529c 100644 --- a/products/platform/journeys/test_lib.sh +++ b/products/platform/journeys/test_lib.sh @@ -1173,13 +1173,13 @@ journeyCodeSuffixes: needs: [certificate, hand-written-sql] promote: [no-input] authenticationStages: [issuer, audience] -milestones: [M1, M2] +changes: [posture, shared-trust-rules] expectedFailures: - journey: sample product: beta step: call code: http.401.issuer - removedBy: M1 + removedBy: posture basis: predicted reason: The issuer is refused. YAML @@ -1189,7 +1189,7 @@ YAML product: delta step: start code: product.config.unknown-field - removedBy: M2 + removedBy: shared-trust-rules basis: predicted reason: The runtime file names a field the product does not know. YAML @@ -1200,7 +1200,7 @@ YAML product: alpha step: call code: http.401.audience - removedBy: M2 + removedBy: shared-trust-rules basis: predicted reason: Listed twice on purpose. YAML From d77c5667eefc846b460fdb50b85a023297c1fbcd Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:36:15 +0100 Subject: [PATCH 056/136] feat(release): add a held Adapter image and an opt-in arm64 image build The release tooling carries a Registry Adapter image, runtime plus adapterctl on the distroless non-root base, held out of every roster until ADAPTER_IMAGE_FIRST_RELEASE names a release. With the constant unset the release image set and the amd64 build command line are unchanged, and tests pin both. build-release-image.sh takes RELEASE_IMAGE_PLATFORM, linux/amd64 by default or linux/arm64, and refuses any other value before calling docker. The nightly workflow gains an arm64_images dispatch input that builds native arm64 image layouts and retains them for inspection, outside the publish path. Published images stay linux/amd64. Signed-off-by: Jeremi Joslin --- .github/workflows/nightly-release.yml | 70 ++++++++ release/VERIFY.md | 3 +- release/docker/Dockerfile.adapter | 51 ++++++ release/scripts/build-release-binaries.sh | 14 +- release/scripts/build-release-image.sh | 16 +- release/scripts/check-debian13-images.py | 7 + .../scripts/merge-release-binary-shards.py | 3 + release/scripts/release_candidate.py | 7 + release/scripts/release_roster.py | 26 ++- .../scripts/smoke-release-image-oci-labels.sh | 4 +- release/scripts/test_build_release_image.py | 153 ++++++++++++++++++ release/scripts/test_check_debian13_images.py | 3 + .../test_check_release_image_oci_labels.py | 9 +- .../test_merge_release_binary_shards.py | 31 +++- .../scripts/test_nightly_release_workflow.py | 46 +++++- release/scripts/test_release_candidate.py | 129 +++++++++++++++ release/scripts/test_release_roster.py | 32 ++++ 17 files changed, 591 insertions(+), 13 deletions(-) create mode 100644 release/docker/Dockerfile.adapter create mode 100644 release/scripts/test_build_release_image.py diff --git a/.github/workflows/nightly-release.yml b/.github/workflows/nightly-release.yml index f1b5a0b6f7..fa4b4eee17 100644 --- a/.github/workflows/nightly-release.yml +++ b/.github/workflows/nightly-release.yml @@ -5,6 +5,12 @@ on: schedule: - cron: "19 0 * * *" workflow_dispatch: + inputs: + arm64_images: + description: Also build native Linux arm64 image layouts, retained for inspection and not published + type: boolean + required: false + default: false permissions: contents: read @@ -217,6 +223,70 @@ jobs: retention-days: 7 if-no-files-found: error + arm64-images: + name: Build native Linux arm64 nightly image layouts + needs: [select, arm64] + if: needs.select.outputs.skip != 'true' && inputs.arm64_images + runs-on: ubuntu-24.04-arm + timeout-minutes: 90 + steps: + - name: Checkout selected source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ needs.select.outputs.source_sha }} + persist-credentials: false + submodules: false + - name: Download exact arm64 binaries + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 + with: + name: nightly-arm64-${{ github.run_id }}-${{ github.run_attempt }} + path: arm64 + - name: Stage the arm64 image binaries + env: + IMAGE_NAMES: ${{ needs.select.outputs.image_names }} + BASE_VERSION: ${{ needs.select.outputs.base_version }} + NIGHTLY_TAG: ${{ needs.select.outputs.tag }} + run: | + mkdir -p dist/image-bin + operator_tools="$(python3 release/scripts/release_candidate.py image-operator-tools --version "${BASE_VERSION}")" + for name in ${IMAGE_NAMES}; do + install -m 0755 "arm64/${name}-${NIGHTLY_TAG}-linux-arm64" "dist/image-bin/${name}" + for pair in ${operator_tools}; do + if [[ "${pair%%=*}" == "${name}" ]]; then + tool="${pair#*=}" + install -m 0755 "arm64/${tool}-${NIGHTLY_TAG}-linux-arm64" "dist/image-bin/${tool}" + fi + done + done + - name: Set up pinned Docker Buildx + id: buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 + with: + version: ${{ env.RELEASE_BUILDX_VERSION }} + driver-opts: image=${{ env.RELEASE_BUILDKIT_IMAGE }} + - name: Build arm64 image layouts without publication credentials + env: + IMAGE_NAMES: ${{ needs.select.outputs.image_names }} + NIGHTLY_VERSION: ${{ needs.select.outputs.version }} + SOURCE_SHA: ${{ needs.select.outputs.source_sha }} + RELEASE_BUILDX_BUILDER: ${{ steps.buildx.outputs.name }} + RELEASE_IMAGE_PLATFORM: linux/arm64 + run: | + mkdir -p dist/images-arm64 + for name in ${IMAGE_NAMES}; do + reference="ghcr.io/registrystack/${name}-candidate:candidate-arm64-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + RELEASE_IMAGE_OCI_LAYOUT="${GITHUB_WORKSPACE}/dist/images-arm64/${name}.oci" \ + release/scripts/build-release-image.sh "${name}" "${reference}" \ + "https://github.com/${GITHUB_REPOSITORY}" "${SOURCE_SHA}" "${NIGHTLY_VERSION}" "dist/images-arm64/${name}.metadata.json" + done + - name: Retain arm64 image layouts + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: arm64-image-layouts-${{ github.run_id }}-${{ github.run_attempt }} + path: dist/images-arm64 + retention-days: 7 + if-no-files-found: error + images: name: Merge Linux shards and build exact nightly image layouts needs: [select, linux] diff --git a/release/VERIFY.md b/release/VERIFY.md index 595fa6d03a..1c88719d63 100644 --- a/release/VERIFY.md +++ b/release/VERIFY.md @@ -280,7 +280,8 @@ and Python client namespace also joins in `v0.44.0`, under `COORDINATOR_CLIENT_FIRST_RELEASE`. Its image remains held while `COORDINATOR_FIRST_RELEASE` is unset. Registry Adapter binaries join in `v0.46.0`, as set by -`ADAPTER_FIRST_RELEASE`; the Adapter has no image. +`ADAPTER_FIRST_RELEASE`. Its image is authored and remains held while +`ADAPTER_IMAGE_FIRST_RELEASE` is unset. The Registry Document Store is held out of every release while `DOCUMENTS_FIRST_RELEASE` is `None`, and no release roster names it. `BREG_SERVICES_FIRST_RELEASE`, `MESSAGING_FIRST_RELEASE`, diff --git a/release/docker/Dockerfile.adapter b/release/docker/Dockerfile.adapter new file mode 100644 index 0000000000..43a7271edc --- /dev/null +++ b/release/docker/Dockerfile.adapter @@ -0,0 +1,51 @@ +# syntax=docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e + +ARG SOURCE_DATE_EPOCH=0 + +FROM docker.io/library/debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2 AS runtime-root +ARG SOURCE_DATE_EPOCH + +ADD --checksum=sha256:b59b0625cd1a791375d40dab23a4d5d3d0641e3d0a773501becdc3725b7f99cf https://snapshot.debian.org/archive/debian/20261114T144101Z/pool/main/g/glibc/libc6_2.41-12+deb13u5_amd64.deb /workspace/runtime-packages/libc6_2.41-12+deb13u5_amd64.deb +ADD --checksum=sha256:0966fc3da1a26cc57647c68b5736f791b6e7eb498173a7993f63b6c89b4ed4f5 https://snapshot.debian.org/archive/debian/20261114T144101Z/pool/main/g/glibc/libc6_2.41-12+deb13u5_arm64.deb /workspace/runtime-packages/libc6_2.41-12+deb13u5_arm64.deb +ADD --checksum=sha256:ff16bc048bcd7d1b256094450b79c77947d8e76fe2a24bd99b91021d591fa074 https://snapshot.debian.org/archive/debian-security/20260930T060347Z/pool/updates/main/o/openssl/libssl3t64_3.5.7-1~deb13u3_amd64.deb /workspace/runtime-packages/libssl3t64_3.5.7-1~deb13u3_amd64.deb +ADD --checksum=sha256:d0681293a160392186c6ef85a165e40603d1628a099936137d24d391bd591f97 https://snapshot.debian.org/archive/debian-security/20260930T060347Z/pool/updates/main/o/openssl/libssl3t64_3.5.7-1~deb13u3_arm64.deb /workspace/runtime-packages/libssl3t64_3.5.7-1~deb13u3_arm64.deb +ADD --checksum=sha256:8c27c342230503b73dfde629642c3b352e87b554e06d60cf58772f236a305ceb https://snapshot.debian.org/archive/debian-security/20261107T075304Z/pool/updates/main/z/zlib/zlib1g_1.3.dfsg+really1.3.1-1+deb13u1_amd64.deb /workspace/runtime-packages/zlib1g_1.3.dfsg+really1.3.1-1+deb13u1_amd64.deb +ADD --checksum=sha256:0e41b3d7ad8ad7fcd36dd4d61ca91a70018478fc4af652e044f4be770784ddff https://snapshot.debian.org/archive/debian-security/20261107T075304Z/pool/updates/main/z/zlib/zlib1g_1.3.dfsg+really1.3.1-1+deb13u1_arm64.deb /workspace/runtime-packages/zlib1g_1.3.dfsg+really1.3.1-1+deb13u1_arm64.deb + +# The project directory, the runtime configuration, and secrets are deployment +# inputs. The image carries the runtime binary, the adapterctl author and +# operator tool, and their licenses. The runtime stays the entrypoint. An +# operator runs adapterctl by overriding it. +# Adapter keeps its journal and idempotency state in PostgreSQL, so the image +# needs no writable persistent directory. +# Every release that carries the Adapter image stages adapterctl beside the +# runtime, and the candidate refuses a build whose staged copy is missing. +RUN --mount=type=bind,source=dist/image-bin,target=/workspace/image-bin \ + --mount=type=bind,source=LICENSE,target=/workspace/LICENSE \ + --mount=type=bind,source=THIRD_PARTY_NOTICES,target=/workspace/THIRD_PARTY_NOTICES,readonly \ + --mount=type=bind,source=release/scripts/install-runtime-packages.sh,target=/workspace/install-runtime-packages.sh,readonly \ + /workspace/install-runtime-packages.sh /workspace/runtime-root /workspace/runtime-packages \ + && mkdir -p \ + /workspace/runtime-root/etc/registry-adapter \ + /workspace/runtime-root/licenses/adapter \ + /workspace/runtime-root/usr/local/bin \ + && install -m 0755 /workspace/image-bin/adapter /workspace/runtime-root/usr/local/bin/adapter \ + && install -m 0755 /workspace/image-bin/adapterctl /workspace/runtime-root/usr/local/bin/adapterctl \ + && install -m 0644 /workspace/LICENSE /workspace/runtime-root/licenses/adapter/LICENSE \ + && install -m 0644 /workspace/THIRD_PARTY_NOTICES /workspace/runtime-root/licenses/adapter/THIRD_PARTY_NOTICES \ + && find /workspace/runtime-root -exec touch -h --date="@${SOURCE_DATE_EPOCH}" {} + + +FROM gcr.io/distroless/cc-debian13:nonroot@sha256:cb87acc574abe719b6e5c547384defa2f7b1f24af9605d3f618cf852495d8be2 AS runtime + +LABEL org.registrystack.runtime.uid="65532" \ + org.registrystack.runtime.gid="65532" + +COPY --from=runtime-root /workspace/runtime-root/ / + +EXPOSE 8080 + +# Adapter serves GET /health and GET /ready on the listener its runtime +# configuration binds, and the examples bind port 8080. Distroless has no shell +# or HTTP client, so the deployment platform owns the probe. +ENTRYPOINT ["/usr/local/bin/adapter"] +CMD ["serve", "--runtime-config", "/etc/registry-adapter/runtime.yaml", "--project", "/etc/registry-adapter/project"] diff --git a/release/scripts/build-release-binaries.sh b/release/scripts/build-release-binaries.sh index a20dd7f0c3..38c0a931ed 100755 --- a/release/scripts/build-release-binaries.sh +++ b/release/scripts/build-release-binaries.sh @@ -165,13 +165,17 @@ include_coordinator_image=0 if [[ "$(python3 "${script_dir}/release_roster.py" coordinator-in-release "${version}")" == true ]]; then include_coordinator_image=1 fi -# The Adapter ships as binaries only; the facade has no image yet. +# Adapter binaries have an independent boundary from image publication. include_adapter=0 adapter_in_release="$(python3 "${script_dir}/release_roster.py" \ adapter-in-release "${version}")" if [[ "${adapter_in_release}" == true ]]; then include_adapter=1 fi +include_adapter_image=0 +if [[ "$(python3 "${script_dir}/release_roster.py" adapter-image-in-release "${version}")" == true ]]; then + include_adapter_image=1 +fi if [[ "${group}" == discovery ]]; then include_discovery=1 @@ -362,6 +366,10 @@ build_payload() { cargo build --release --locked \ -p registry-adapterctl --bin adapterctl cp target/release/adapterctl "dist/bin/adapterctl-${RELEASE_TAG}-linux-amd64" + if [[ "${include_adapter_image}" -eq 1 ]]; then + cp target/release/adapter dist/image-bin/adapter + cp target/release/adapterctl dist/image-bin/adapterctl + fi fi fi @@ -598,6 +606,7 @@ docker run --rm \ --env RELEASE_INCLUDE_COORDINATOR="${include_coordinator}" \ --env RELEASE_INCLUDE_COORDINATOR_IMAGE="${include_coordinator_image}" \ --env RELEASE_INCLUDE_ADAPTER="${include_adapter}" \ + --env RELEASE_INCLUDE_ADAPTER_IMAGE="${include_adapter_image}" \ --env RELEASE_INCLUDE_LANGUAGE_SERVER="${include_language_server}" \ --env RELEASE_INCLUDE_EVIDENCE_OID4VCI_IMAGE="${include_evidence_oid4vci_image}" \ --env RELEASE_TAG="${tag}" \ @@ -725,6 +734,9 @@ if [[ "${group}" == all || "${group}" == core ]]; then "adapter-${tag}-linux-amd64" "adapterctl-${tag}-linux-amd64" ) + if [[ "${include_adapter_image}" -eq 1 ]]; then + image_bin_binaries+=(adapter adapterctl) + fi fi fi diff --git a/release/scripts/build-release-image.sh b/release/scripts/build-release-image.sh index 469546c8da..b984a4915b 100755 --- a/release/scripts/build-release-image.sh +++ b/release/scripts/build-release-image.sh @@ -24,7 +24,7 @@ release_image_context="${RELEASE_IMAGE_CONTEXT:-${repo_root}}" created_builder=false case "${name}" in - discovery|evidence|evidence-oid4vci|registry-render|breg|breg-mcp|breg-review|casework|scheduling|messaging|coordinator) + discovery|evidence|evidence-oid4vci|registry-render|breg|breg-mcp|breg-review|casework|scheduling|messaging|coordinator|adapter) dockerfile="${repo_root}/release/docker/Dockerfile.${name}" ;; *) @@ -33,6 +33,18 @@ case "${name}" in ;; esac +# Images build natively for one platform per invocation. amd64 is the release +# default. An arm64 image is built on an arm64 host from arm64 binaries staged +# in dist/image-bin, never through emulation. +release_image_platform="${RELEASE_IMAGE_PLATFORM-linux/amd64}" +case "${release_image_platform}" in + linux/amd64 | linux/arm64) ;; + *) + echo "RELEASE_IMAGE_PLATFORM must be linux/amd64 or linux/arm64, got: ${release_image_platform}" >&2 + exit 2 + ;; +esac + cache_args=() if [[ -n "${RELEASE_IMAGE_CACHE_FROM:-}" ]]; then cache_args+=(--cache-from "${RELEASE_IMAGE_CACHE_FROM}") @@ -164,7 +176,7 @@ mkdir -p "$(dirname -- "${metadata_file}")" cd -- "${release_image_context}" docker buildx build \ --builder "${release_buildx_builder}" \ - --platform linux/amd64 \ + --platform "${release_image_platform}" \ --file "${dockerfile}" \ --tag "${image}" \ "${provenance_args[@]}" \ diff --git a/release/scripts/check-debian13-images.py b/release/scripts/check-debian13-images.py index 02ce5e164d..dc58d1e0d2 100755 --- a/release/scripts/check-debian13-images.py +++ b/release/scripts/check-debian13-images.py @@ -132,6 +132,7 @@ def archive_version(version: str) -> str: Path("release/docker/Dockerfile.scheduling"), Path("release/docker/Dockerfile.messaging"), Path("release/docker/Dockerfile.coordinator"), + Path("release/docker/Dockerfile.adapter"), ) # Adopter and development images. They build from source like the per-product @@ -226,6 +227,12 @@ def archive_version(version: str) -> str: "entrypoint": 'ENTRYPOINT ["/usr/local/bin/coordinator"]', "command": 'CMD ["--runtime-config", "/etc/registry-coordinator/runtime.yaml"]', }, + Path("release/docker/Dockerfile.adapter"): { + "binary": "adapter", + "tool": "adapterctl", + "entrypoint": 'ENTRYPOINT ["/usr/local/bin/adapter"]', + "command": 'CMD ["serve", "--runtime-config", "/etc/registry-adapter/runtime.yaml", "--project", "/etc/registry-adapter/project"]', + }, } FROM_RE = re.compile(r"^FROM\s+(?:--platform=\S+\s+)?(\S+)", re.MULTILINE) diff --git a/release/scripts/merge-release-binary-shards.py b/release/scripts/merge-release-binary-shards.py index f5a559bf9d..f0bd56741d 100755 --- a/release/scripts/merge-release-binary-shards.py +++ b/release/scripts/merge-release-binary-shards.py @@ -166,6 +166,9 @@ def rosters( if release_roster.coordinator_in_release(parsed): for binary in ("coordinator", "coordinatorctl"): image_bins.append((binary, f"{binary}-{tag}-linux-amd64")) + if release_roster.adapter_image_in_release(parsed): + for binary in ("adapter", "adapterctl"): + image_bins.append((binary, f"{binary}-{tag}-linux-amd64")) return { "core": core, "breg": breg, diff --git a/release/scripts/release_candidate.py b/release/scripts/release_candidate.py index 156b42983e..490c64c6da 100644 --- a/release/scripts/release_candidate.py +++ b/release/scripts/release_candidate.py @@ -80,6 +80,7 @@ "scheduling": "schedulingctl", "messaging": "messagingctl", "coordinator": "coordinatorctl", + "adapter": "adapterctl", } # Registry Messaging joins the release set from the release that # release_roster.MESSAGING_FIRST_RELEASE names. @@ -95,6 +96,9 @@ # Registry Coordinator joins the release set from the release that # release_roster.COORDINATOR_FIRST_RELEASE names. COORDINATOR_RUNTIME_IMAGE_NAMES = {"coordinator"} +# The Registry Adapter facade image joins the release set from the release that +# release_roster.ADAPTER_IMAGE_FIRST_RELEASE names. +ADAPTER_RUNTIME_IMAGE_NAMES = {"adapter"} V2_TOP_LEVEL_FIELDS = { "schema_version", "repository", @@ -142,6 +146,7 @@ | RENDER_RUNTIME_IMAGE_NAMES | EVIDENCE_OID4VCI_RUNTIME_IMAGE_NAMES | COORDINATOR_RUNTIME_IMAGE_NAMES + | ADAPTER_RUNTIME_IMAGE_NAMES ) for directory, suffix in ( ("image-sbom", "spdx"), @@ -185,6 +190,8 @@ def _candidate_image_names(version: str) -> set[str]: image_names = image_names | EVIDENCE_OID4VCI_RUNTIME_IMAGE_NAMES if release_roster.coordinator_in_release(parsed): image_names = image_names | COORDINATOR_RUNTIME_IMAGE_NAMES + if release_roster.adapter_image_in_release(parsed): + image_names = image_names | ADAPTER_RUNTIME_IMAGE_NAMES if not release_roster.relay_in_release(parsed): image_names = image_names - {"relay"} return image_names diff --git a/release/scripts/release_roster.py b/release/scripts/release_roster.py index 14c58c6778..a40b502b6f 100644 --- a/release/scripts/release_roster.py +++ b/release/scripts/release_roster.py @@ -50,9 +50,11 @@ ``ADAPTER_FIRST_RELEASE`` decides when the Registry Adapter binaries join the Stack train: the ``adapter`` facade, the ``adapterctl`` author tool and their -installer, on every supported platform, from v0.46.0. The facade has no image -yet. The ``adapter-job`` host stays source-build only until its release build -enables a destination. +installer, on every supported platform, from v0.46.0. +``ADAPTER_IMAGE_FIRST_RELEASE`` independently decides when the facade image and +its image-specific security evidence join. The image stays held until that +evidence is ready. The ``adapter-job`` host stays source-build only until its +release build enables a destination. ``LANGUAGE_SERVER_FIRST_RELEASE`` decides when the standalone Registry Stack language server joins the Stack train for the editor hosts that consume it: @@ -105,6 +107,8 @@ ADAPTER_FIRST_RELEASE: tuple[int, int, int] | None = (0, 46, 0) +ADAPTER_IMAGE_FIRST_RELEASE: tuple[int, int, int] | None = None + LANGUAGE_SERVER_FIRST_RELEASE: tuple[int, int, int] | None = (0, 46, 1) ALL_PLATFORMS_FIRST_RELEASE = (0, 44, 0) @@ -285,6 +289,16 @@ def adapter_in_release(version: tuple[int, int, int]) -> bool: return first_release is not None and tuple(version) >= first_release +def adapter_image_in_release(version: tuple[int, int, int]) -> bool: + """Return whether the release at ``version`` ships the Registry Adapter image. + + Binary distribution does not waive the independent image evidence gate. + The constant is read at call time so tests can patch it. + """ + first_release = ADAPTER_IMAGE_FIRST_RELEASE + return first_release is not None and tuple(version) >= first_release + + def language_server_in_release(version: tuple[int, int, int]) -> bool: """Return whether the release ships the standalone language server.""" @@ -345,6 +359,12 @@ def main(argv: list[str] | None = None) -> int: ) adapter.add_argument("version", type=version_argument, help="release version as X.Y.Z") adapter.set_defaults(in_release=adapter_in_release) + adapter_image = commands.add_parser( + "adapter-image-in-release", + help="print true when the release version ships the Adapter image, else false", + ) + adapter_image.add_argument("version", type=version_argument, help="release version as X.Y.Z") + adapter_image.set_defaults(in_release=adapter_image_in_release) language_server = commands.add_parser( "language-server-in-release", help="print true when the release ships the standalone language server", diff --git a/release/scripts/smoke-release-image-oci-labels.sh b/release/scripts/smoke-release-image-oci-labels.sh index 8ef21ca621..238cafaca4 100755 --- a/release/scripts/smoke-release-image-oci-labels.sh +++ b/release/scripts/smoke-release-image-oci-labels.sh @@ -6,9 +6,9 @@ repo_root="$(cd -- "${script_dir}/../.." && pwd)" checker="${script_dir}/check-release-image-oci-labels.py" image_builder="${script_dir}/build-release-image.sh" layout_comparator="${script_dir}/compare-release-image-layouts.py" -images=(evidence evidence-oid4vci discovery registry-render breg breg-mcp breg-review casework scheduling messaging coordinator) +images=(evidence evidence-oid4vci discovery registry-render breg breg-mcp breg-review casework scheduling messaging coordinator adapter) # The stateful product images carry their operator tool beside the runtime. -operator_tools=(bregctl caseworkctl schedulingctl messagingctl coordinatorctl) +operator_tools=(bregctl caseworkctl schedulingctl messagingctl coordinatorctl adapterctl) sample_dockerfile="${repo_root}/release/docker/Dockerfile.evidence" source_label="https://github.com/registrystack/registry-stack" diff --git a/release/scripts/test_build_release_image.py b/release/scripts/test_build_release_image.py new file mode 100644 index 0000000000..6c1aec6676 --- /dev/null +++ b/release/scripts/test_build_release_image.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Hold the build-release-image.sh command line and its platform selection. + +The script drives `docker buildx` through a stand-in `docker` on PATH that +records its arguments, so no daemon, registry or base image is needed. +""" + +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "release/scripts/build-release-image.sh" +BUILDKIT_IMAGE = ( + "ghcr.io/registrystack/buildkit:v0.31.2@sha256:" + "2f5adac4ecd194d9f8c10b7b5d7bceb5186853db1b26e5abd3a657af0b7e26ec" +) +BUILDKIT_REPO_DIGEST = ( + "ghcr.io/registrystack/buildkit@sha256:" + "2f5adac4ecd194d9f8c10b7b5d7bceb5186853db1b26e5abd3a657af0b7e26ec" +) + +FAKE_DOCKER = f"""#!/usr/bin/env bash +set -euo pipefail +printf '%s\\n' "$*" >> "${{FAKE_DOCKER_LOG}}" +case "$1 ${{2:-}}" in + "buildx version") echo "github.com/docker/buildx v0.33.0 fixture" ;; + "buildx inspect") printf 'Driver: docker-container\\nBuildKit version: v0.31.2\\n' ;; + "ps --all") echo "buildx_buildkit_fixture0" ;; + "inspect --format") echo "{BUILDKIT_IMAGE}" ;; + "image inspect") echo "{BUILDKIT_REPO_DIGEST}" ;; + "buildx build") : ;; + *) echo "unexpected docker call: $*" >&2; exit 99 ;; +esac +""" + + +class BuildReleaseImageTest(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.tmp = Path(self.temp.name) + fake_bin = self.tmp / "bin" + fake_bin.mkdir() + docker = fake_bin / "docker" + docker.write_text(FAKE_DOCKER, encoding="utf-8") + docker.chmod(0o755) + self.fake_bin = fake_bin + self.log = self.tmp / "docker.log" + self.log.write_text("", encoding="utf-8") + + def run_script(self, name: str = "breg", **overrides: str) -> subprocess.CompletedProcess: + environment = { + key: value + for key, value in os.environ.items() + if not key.startswith("RELEASE_IMAGE_") + } + environment.update( + { + "PATH": f"{self.fake_bin}{os.pathsep}{environment['PATH']}", + "FAKE_DOCKER_LOG": str(self.log), + "RELEASE_BUILDX_BUILDER": "fixture", + "RELEASE_IMAGE_OCI_LAYOUT": str(self.tmp / "layout.oci"), + } + ) + environment.update(overrides) + return subprocess.run( + [ + str(SCRIPT), + name, + "ghcr.io/registrystack/breg-candidate:fixture", + "https://example.invalid/source", + "0123456789abcdef0123456789abcdef01234567", + "1.2.3", + str(self.tmp / "meta/metadata.json"), + ], + text=True, + capture_output=True, + check=False, + env=environment, + ) + + def build_calls(self) -> list[str]: + return [ + line + for line in self.log.read_text(encoding="utf-8").splitlines() + if line.startswith("buildx build ") + ] + + def expected_build_call(self, name: str, platform: str) -> str: + return " ".join( + [ + "buildx build --builder fixture", + f"--platform {platform}", + f"--file {ROOT}/release/docker/Dockerfile.{name}", + "--tag ghcr.io/registrystack/breg-candidate:fixture", + "--provenance=false", + "--label org.opencontainers.image.source=https://example.invalid/source", + "--label org.opencontainers.image.revision=0123456789abcdef0123456789abcdef01234567", + "--label org.opencontainers.image.version=1.2.3", + "--build-arg SOURCE_DATE_EPOCH=0", + f"--metadata-file {self.tmp}/meta/metadata.json", + f"--output type=oci,dest={self.tmp}/layout.oci,tar=false," + "rewrite-timestamp=true,compatibility-version=20", + ".", + ] + ) + + def test_default_command_line_is_the_amd64_release_command_line(self) -> None: + result = self.run_script() + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual( + [self.expected_build_call("breg", "linux/amd64")], self.build_calls() + ) + + def test_explicit_amd64_matches_the_default(self) -> None: + result = self.run_script(RELEASE_IMAGE_PLATFORM="linux/amd64") + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual( + [self.expected_build_call("breg", "linux/amd64")], self.build_calls() + ) + + def test_arm64_changes_only_the_platform(self) -> None: + result = self.run_script(RELEASE_IMAGE_PLATFORM="linux/arm64") + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual( + [self.expected_build_call("breg", "linux/arm64")], self.build_calls() + ) + + def test_unsupported_platforms_are_refused_before_any_docker_call(self) -> None: + for platform in ("linux/arm", "linux/amd64,linux/arm64", "darwin/arm64", "arm64", ""): + with self.subTest(platform=platform): + self.log.write_text("", encoding="utf-8") + result = self.run_script(RELEASE_IMAGE_PLATFORM=platform) + self.assertEqual(2, result.returncode) + self.assertIn("RELEASE_IMAGE_PLATFORM must be", result.stderr) + self.assertEqual("", self.log.read_text(encoding="utf-8")) + + def test_adapter_is_a_recognised_image(self) -> None: + result = self.run_script("adapter") + self.assertEqual(0, result.returncode, result.stderr) + calls = self.build_calls() + self.assertEqual(1, len(calls)) + self.assertIn(f"--file {ROOT}/release/docker/Dockerfile.adapter ", calls[0]) + self.assertIn("--platform linux/amd64 ", calls[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/release/scripts/test_check_debian13_images.py b/release/scripts/test_check_debian13_images.py index 57121936e8..88eeac190c 100644 --- a/release/scripts/test_check_debian13_images.py +++ b/release/scripts/test_check_debian13_images.py @@ -40,6 +40,7 @@ def test_official_runtime_images_are_required_maintained_surfaces(self) -> None: Path("release/docker/Dockerfile.scheduling"), Path("release/docker/Dockerfile.messaging"), Path("release/docker/Dockerfile.coordinator"), + Path("release/docker/Dockerfile.adapter"), }, set(POLICY.DOCKERFILES), ) @@ -56,6 +57,7 @@ def test_official_runtime_images_are_required_maintained_surfaces(self) -> None: Path("release/docker/Dockerfile.scheduling"), Path("release/docker/Dockerfile.messaging"), Path("release/docker/Dockerfile.coordinator"), + Path("release/docker/Dockerfile.adapter"), }, set(POLICY.HTTP_PROBE_DOCKERFILES), ) @@ -611,6 +613,7 @@ def test_stateful_images_carry_their_operator_tool_beside_the_runtime( Path("release/docker/Dockerfile.scheduling"): "schedulingctl", Path("release/docker/Dockerfile.messaging"): "messagingctl", Path("release/docker/Dockerfile.coordinator"): "coordinatorctl", + Path("release/docker/Dockerfile.adapter"): "adapterctl", }, { relative: contract["tool"] diff --git a/release/scripts/test_check_release_image_oci_labels.py b/release/scripts/test_check_release_image_oci_labels.py index cb0b52cd8a..ba12d1ab38 100644 --- a/release/scripts/test_check_release_image_oci_labels.py +++ b/release/scripts/test_check_release_image_oci_labels.py @@ -649,7 +649,7 @@ def read_calls(path: Path) -> list[list[str]]: build_calls = [ call for call in read_calls(docker_log) if call[:2] == ["buildx", "build"] ] - self.assertEqual(24, len(build_calls)) + self.assertEqual(26, len(build_calls)) dockerfiles = [] for call in build_calls: self.assertEqual(["buildx", "build"], call[:2]) @@ -685,6 +685,7 @@ def read_calls(path: Path) -> list[list[str]]: str(ROOT / "release/docker/Dockerfile.scheduling"), str(ROOT / "release/docker/Dockerfile.messaging"), str(ROOT / "release/docker/Dockerfile.coordinator"), + str(ROOT / "release/docker/Dockerfile.adapter"), }, set(dockerfiles), ) @@ -705,6 +706,7 @@ def read_calls(path: Path) -> list[list[str]]: "scheduling", "messaging", "coordinator", + "adapter", ): self.assertEqual( 2, @@ -740,6 +742,8 @@ def read_calls(path: Path) -> list[list[str]]: "messagingctl", "coordinator", "coordinatorctl", + "adapter", + "adapterctl", ) ) ) @@ -767,6 +771,7 @@ def read_calls(path: Path) -> list[list[str]]: "correct-scheduling-first", "correct-messaging-first", "correct-coordinator-first", + "correct-adapter-first", }, { Path(layout.removeprefix("oci-layout://")).name @@ -789,7 +794,7 @@ def read_calls(path: Path) -> list[list[str]]: for call in python_calls if call and call[0].endswith("compare-release-image-layouts.py") ] - self.assertEqual(12, len(comparisons)) + self.assertEqual(13, len(comparisons)) self.assertEqual(1, sum("--rootfs-only" in call for call in comparisons)) diff --git a/release/scripts/test_merge_release_binary_shards.py b/release/scripts/test_merge_release_binary_shards.py index 6d3b725a99..e964fde16f 100644 --- a/release/scripts/test_merge_release_binary_shards.py +++ b/release/scripts/test_merge_release_binary_shards.py @@ -494,6 +494,31 @@ def test_adapter_joins_the_core_shard_from_v0_46_0_without_an_image(self) -> Non ) self.assertFalse(any(name.startswith("adapter") for name, _ in images)) + def test_adapter_image_bins_join_only_from_the_image_first_release(self) -> None: + with mock.patch.object( + MODULE.release_roster, "ADAPTER_IMAGE_FIRST_RELEASE", (0, 49, 0) + ): + rosters_048, images_048 = MODULE.rosters("0.48.0") + rosters_049, images_049 = MODULE.rosters("0.49.0") + self.assertFalse(any(name.startswith("adapter") for name, _ in images_048)) + self.assertEqual( + [ + ("adapter", "adapter-v0.49.0-linux-amd64"), + ("adapterctl", "adapterctl-v0.49.0-linux-amd64"), + ], + [entry for entry in images_049 if entry[0].startswith("adapter")], + ) + # The binaries ship on their own gate, so the shard rosters match. + self.assertEqual( + {key: [n.replace("0.48.0", "0.49.0") for n in names] for key, names in rosters_048.items()}, + rosters_049, + ) + _, images_held = MODULE.rosters("0.49.0") + self.assertEqual( + [entry for entry in images_049 if not entry[0].startswith("adapter")], + images_held, + ) + def test_core_recipe_builds_each_adapter_binary_in_its_own_invocation(self) -> None: # Cargo unifies features within one invocation, so each binary keeps # its own build to retain its product's feature boundary. @@ -516,7 +541,11 @@ def test_core_recipe_builds_each_adapter_binary_in_its_own_invocation(self) -> N ) ) self.assertNotIn("adapter-job", block) - self.assertNotIn("dist/image-bin", block) + # Image staging sits behind its own gate, inside the same block. + self.assertIn('if [[ "${include_adapter_image}" -eq 1 ]]; then', block) + staging = block.split('if [[ "${include_adapter_image}" -eq 1 ]]; then', 1)[1] + self.assertIn("cp target/release/adapter dist/image-bin/adapter", staging) + self.assertIn("cp target/release/adapterctl dist/image-bin/adapterctl", staging) def test_no_shard_carries_the_document_store_while_it_is_held_out(self) -> None: # The Document Store is held out by DOCUMENTS_FIRST_RELEASE and has no diff --git a/release/scripts/test_nightly_release_workflow.py b/release/scripts/test_nightly_release_workflow.py index d15345ba64..a6a1170bb8 100644 --- a/release/scripts/test_nightly_release_workflow.py +++ b/release/scripts/test_nightly_release_workflow.py @@ -19,7 +19,7 @@ def setUp(self): def test_only_main_scheduler_or_manual_selection(self): trigger = self.workflow.get("on", self.workflow.get(True)) self.assertEqual(set(trigger), {"schedule", "workflow_dispatch"}) - self.assertIsNone(trigger["workflow_dispatch"]) + self.assertEqual(set(trigger["workflow_dispatch"]), {"inputs"}) self.assertEqual(self.workflow["concurrency"]["cancel-in-progress"], False) self.assertIn("nightly_release.py plan", self.text) self.assertIn("wait-for-ci", self.text) @@ -175,6 +175,50 @@ def test_arm64_build_compiles_the_nightly_launcher(self): recipe, ) + def test_arm64_images_are_opt_in_and_amd64_stays_the_default(self): + trigger = self.workflow.get("on", self.workflow.get(True)) + inputs = trigger["workflow_dispatch"]["inputs"] + self.assertEqual({"arm64_images"}, set(inputs)) + self.assertEqual("boolean", inputs["arm64_images"]["type"]) + self.assertIs(False, inputs["arm64_images"]["default"]) + self.assertIs(False, inputs["arm64_images"]["required"]) + # Only the opt-in job selects a non-default image platform. The image + # job the scheduled run uses keeps the amd64 default. + selecting = { + name + for name, job in self.jobs.items() + if "RELEASE_IMAGE_PLATFORM" in str(job) + } + self.assertEqual({"arm64-images"}, selecting) + self.assertNotIn("RELEASE_IMAGE_PLATFORM", str(self.jobs["images"])) + # Images build natively per architecture, never through emulation. + self.assertNotIn("qemu", self.text.lower()) + self.assertNotIn("binfmt", self.text.lower()) + + def test_arm64_image_job_builds_native_layouts_outside_the_publication_path(self): + job = self.jobs["arm64-images"] + self.assertEqual("ubuntu-24.04-arm", job["runs-on"]) + self.assertIn("inputs.arm64_images", job["if"]) + self.assertIn("needs.select.outputs.skip != 'true'", job["if"]) + self.assertEqual({"select", "arm64"}, set(job["needs"])) + self.assertNotIn("permissions", job) + for later in ("prepare", "attest", "publish"): + self.assertNotIn("arm64-images", self.jobs[later]["needs"]) + text = str(job) + self.assertIn("release/scripts/build-release-image.sh", text) + self.assertIn("linux/arm64", text) + self.assertIn("nightly-arm64-${{ github.run_id }}", text) + # The layouts stay out of the artifacts the payload assembly downloads. + uploads = [ + step["with"]["name"] + for step in job["steps"] + if step.get("uses", "").startswith("actions/upload-artifact@") + ] + self.assertEqual( + ["arm64-image-layouts-${{ github.run_id }}-${{ github.run_attempt }}"], + uploads, + ) + def test_no_numbered_release_promotion_or_mutable_image_alias(self): self.assertNotIn("REGISTRY_RELEASE_TAG:", self.text) self.assertNotIn(":nightly", self.text) diff --git a/release/scripts/test_release_candidate.py b/release/scripts/test_release_candidate.py index 5fe1434b42..b5cdb7e3a9 100644 --- a/release/scripts/test_release_candidate.py +++ b/release/scripts/test_release_candidate.py @@ -1357,6 +1357,135 @@ def test_coordinator_image_hold_is_independent_of_binary_distribution( self.assertEqual(0, result) self.assertNotIn("coordinator", stdout.getvalue().split()) + def test_adapter_image_is_absent_from_every_roster_while_held(self) -> None: + self.assertIsNone(self.module.release_roster.ADAPTER_IMAGE_FIRST_RELEASE) + held_images = { + "breg", "breg-mcp", "breg-review", "casework", "discovery", "evidence", + "evidence-oid4vci", "messaging", "registry-render", "scheduling", + } + held_tools = { + "breg": "bregctl", + "casework": "caseworkctl", + "scheduling": "schedulingctl", + "messaging": "messagingctl", + } + with mock.patch.object( + self.module.release_roster, "COORDINATOR_FIRST_RELEASE", None + ): + for version in ("0.48.0", "1.0.0"): + with self.subTest(version=version): + self.assertEqual( + held_images, self.module._candidate_image_names(version) + ) + self.assertEqual( + held_tools, self.module.image_operator_tools(version) + ) + stdout = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(io.StringIO()): + result = self.module.main( + ["image-names", "--version", version, "--unit", "stack"] + ) + self.assertEqual(0, result) + self.assertEqual(held_images, set(stdout.getvalue().split())) + required = self.module._security_evidence_required_files( + self.module._candidate_image_names(version) + ) + self.assertFalse(any("adapter" in name for name in required)) + + @roster_patch("release_roster.ADAPTER_IMAGE_FIRST_RELEASE", (0, 49, 0)) + def test_adapter_image_joins_the_rosters_from_its_first_release(self) -> None: + self.hold_out("COORDINATOR_FIRST_RELEASE") + before = self.module._candidate_image_names("0.48.0") + self.assertNotIn("adapter", before) + self.assertEqual( + before | {"adapter"}, self.module._candidate_image_names("0.49.0") + ) + self.assertNotIn("adapter", self.module.image_operator_tools("0.48.0")) + self.assertEqual( + "adapterctl", self.module.image_operator_tools("0.49.0")["adapter"] + ) + stdout = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(io.StringIO()): + result = self.module.main( + ["image-names", "--version", "0.49.0", "--unit", "stack"] + ) + self.assertEqual(0, result) + self.assertIn("adapter", stdout.getvalue().split()) + evidence = { + "image-sbom/adapter.spdx.json", + "syft/adapter.syft.json", + "grype/adapter.grype.json", + } + self.assertTrue( + evidence.issubset( + self.module._security_evidence_required_files( + self.module._candidate_image_names("0.49.0") + ) + ) + ) + self.assertTrue(evidence.issubset(self.module.SECURITY_EVIDENCE_REQUIRED_FILES)) + # The binaries already ship on their own gate, so the payload inventory + # does not change when the image joins. + self.assertEqual( + { + name.replace("0.48.0", "0.49.0"): kind + for name, kind in self.module._release_payload_inventory("0.48.0").items() + }, + self.module._release_payload_inventory("0.49.0"), + ) + + @roster_patch("release_roster.ADAPTER_IMAGE_FIRST_RELEASE", (0, 49, 0)) + def test_adapter_onboarding_stays_closed_until_external_setup(self) -> None: + self.hold_out("COORDINATOR_FIRST_RELEASE") + root = self.onboarding_repository() + shutil.copy2( + ROOT / "release/docker/Dockerfile.adapter", + root / "release/docker/Dockerfile.adapter", + ) + with self.assertRaisesRegex( + self.module.CandidateError, "adapter advisory baseline is missing" + ): + self.module.check_image_onboarding(root, "0.49.0") + with self.assertRaisesRegex( + self.module.CandidateError, + "CANDIDATE_PACKAGES must contain adapter-candidate", + ): + self.module.check_image_onboarding( + root, "0.49.0", allow_missing_baseline=True + ) + cleanup = root / "release/scripts/cleanup-release-candidates.py" + cleanup.write_text( + cleanup.read_text(encoding="utf-8").replace( + ' "messaging-candidate",\n', + ' "messaging-candidate",\n "adapter-candidate",\n', + ), + encoding="utf-8", + ) + with self.assertRaisesRegex( + self.module.CandidateError, "PUBLIC_PACKAGES must contain adapter" + ): + self.module.check_image_onboarding( + root, "0.49.0", allow_missing_baseline=True + ) + # The canonical recipe stages the runtime and its operator tool. + for staged in ("adapter", "adapterctl"): + recipe = root / "release/scripts/build-release-binaries.sh" + original = recipe.read_text(encoding="utf-8") + line = f"cp target/release/{staged} dist/image-bin/{staged}" + self.assertIn(line, original) + recipe.write_text( + original.replace(line, f"cp target/release/{staged} dist/image-bin/wrong-{staged}"), + encoding="utf-8", + ) + with self.assertRaisesRegex( + self.module.CandidateError, + f"canonical binary recipe must stage dist/image-bin/{staged}", + ): + self.module.check_image_onboarding( + root, "0.49.0", allow_missing_baseline=True + ) + recipe.write_text(original, encoding="utf-8") + def test_no_version_ships_the_document_store_while_it_is_held_out( self, ) -> None: diff --git a/release/scripts/test_release_roster.py b/release/scripts/test_release_roster.py index fff1eeeaf1..c5fbbaf3bc 100644 --- a/release/scripts/test_release_roster.py +++ b/release/scripts/test_release_roster.py @@ -120,6 +120,38 @@ def test_coordinator_binary_release_does_not_release_its_image(self): self.assertTrue(release_roster.coordinator_binaries_in_release((0, 44, 0))) self.assertFalse(release_roster.coordinator_in_release((0, 44, 0))) + def test_adapter_image_is_held_until_its_release_prerequisites_are_ready(self) -> None: + self.assertIsNone(release_roster.ADAPTER_IMAGE_FIRST_RELEASE) + for version in ((0, 46, 0), (0, 48, 0), (1, 0, 0)): + self.assertFalse(release_roster.adapter_image_in_release(version)) + with mock.patch.object(release_roster, "ADAPTER_IMAGE_FIRST_RELEASE", (0, 49, 0)): + self.assertFalse(release_roster.adapter_image_in_release((0, 48, 99))) + self.assertTrue(release_roster.adapter_image_in_release((0, 49, 0))) + # The image gate is independent of the binary gate. + with mock.patch.object(release_roster, "ADAPTER_FIRST_RELEASE", (0, 50, 0)): + self.assertTrue(release_roster.adapter_in_release((0, 50, 0))) + self.assertFalse(release_roster.adapter_image_in_release((0, 50, 0))) + + def test_verify_guide_names_the_held_adapter_image_gate(self) -> None: + verify = (SCRIPT_DIR.parent / "VERIFY.md").read_text(encoding="utf-8") + self.assertIn("`ADAPTER_IMAGE_FIRST_RELEASE`", verify) + self.assertIn("Its image is authored and remains held", verify) + + def test_adapter_image_command_prints_the_held_answer(self) -> None: + for version, expected in (("0.48.0", "false\n"), ("v1.0.0", "false\n")): + with self.subTest(version=version): + stdout = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(io.StringIO()): + result = release_roster.main(["adapter-image-in-release", version]) + self.assertEqual(0, result) + self.assertEqual(expected, stdout.getvalue()) + with mock.patch.object(release_roster, "ADAPTER_IMAGE_FIRST_RELEASE", (0, 49, 0)): + stdout = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(io.StringIO()): + result = release_roster.main(["adapter-image-in-release", "0.49.0"]) + self.assertEqual(0, result) + self.assertEqual("true\n", stdout.getvalue()) + def test_adapter_binaries_join_the_stack_train_from_v0_46_0(self) -> None: self.assertEqual((0, 46, 0), release_roster.ADAPTER_FIRST_RELEASE) self.assertFalse(release_roster.adapter_in_release((0, 45, 0))) From 244fe8ed0cb8bd7005daf69a5ed2af2190d6c4f5 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:41:19 +0100 Subject: [PATCH 057/136] fix: name declared scope on Documents and Coordinator refusals and accept the global runtime file for provision A scope refusal line in the Document Store names the configured scope claim, the scope the access profile requires and the profile id, and in the Coordinator the scope claim and the required scope. Nothing from the token is written, and answers are unchanged. coordinatorctl accepts --runtime-config before provision as for its other commands, and a runtime URL that names no user gets its own message. The Coordinator /health test runs through the router and the readiness test checks the body. New tests pin how the Document Store counts a custodian without grant authority and how it treats a key source its verifier refuses. The security and operate pages state what the Document Store logs and answers when its key source cannot be used. Signed-off-by: Jeremi Joslin --- crates/registry-cli-docs/catalog.json | 116 ++---------------- crates/registry-coordinator/src/access.rs | 15 ++- crates/registry-coordinator/src/authoring.rs | 5 +- crates/registry-coordinator/src/cli.rs | 8 ++ crates/registry-coordinator/src/error.rs | 21 +++- crates/registry-coordinator/src/http.rs | 67 ++++++++-- crates/registry-coordinator/src/provision.rs | 29 +++-- crates/registry-coordinator/src/scenarios.rs | 11 +- .../tests/deployment_postgres.rs | 10 +- .../tests/deployment_surface.rs | 13 +- .../tests/provision_cli.rs | 80 ++++++++++++ crates/registry-documents/src/auth.rs | 110 ++++++++++++++++- crates/registry-documents/src/http.rs | 43 ++++++- crates/registry-documents/src/metrics.rs | 10 +- .../tests/refusal_golden.rs | 88 ++++++++++++- .../src/content/docs/security/coordinator.mdx | 6 +- .../src/content/docs/security/documents.mdx | 15 ++- products/coordinator/CHANGELOG.md | 16 ++- products/documents/CHANGELOG.md | 17 +-- .../identifiers/generated/catalog.v1.json | 4 +- 20 files changed, 500 insertions(+), 184 deletions(-) diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index cb56984049..d8b70967a7 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -1744,102 +1744,6 @@ } ] }, - { - "name": "provision", - "invocation": "adapterctl provision", - "about": "Create the roles and the database the runtime file names, or print the SQL", - "long_about": null, - "usage": "adapterctl provision [OPTIONS] --runtime-config ", - "arguments": [], - "options": [ - { - "display": "--runtime-config ", - "description": "Runtime configuration file, the one `apply` reads", - "always_required": true, - "repeatable": false, - "default_values": [], - "possible_values": [], - "environment": null - }, - { - "display": "--admin-url-file ", - "description": "File holding the administrator PostgreSQL URL", - "always_required": false, - "repeatable": false, - "default_values": [], - "possible_values": [], - "environment": null - }, - { - "display": "--admin-url-env ", - "description": "Name of the environment variable holding the administrator PostgreSQL URL", - "always_required": false, - "repeatable": false, - "default_values": [], - "possible_values": [], - "environment": null - }, - { - "display": "--print-sql", - "description": "Print the SQL script and connect to nothing", - "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": [ - { - "kind": "mutually-exclusive", - "when": null, - "arguments": [ - "--admin-url-env ", - "--admin-url-file " - ] - }, - { - "kind": "mutually-exclusive", - "when": null, - "arguments": [ - "--admin-url-env ", - "--print-sql" - ] - }, - { - "kind": "mutually-exclusive", - "when": null, - "arguments": [ - "--admin-url-file ", - "--print-sql" - ] - } - ], - "subcommands": [] - }, { "name": "schemas", "invocation": "adapterctl schemas", @@ -12612,18 +12516,9 @@ "invocation": "coordinatorctl provision", "about": "Create the database, the migration and runtime roles, and the grants `apply` expects, as a PostgreSQL administrator", "long_about": null, - "usage": "coordinatorctl provision [OPTIONS] --runtime-config ", + "usage": "coordinatorctl provision [OPTIONS]", "arguments": [], "options": [ - { - "display": "--runtime-config ", - "description": "Runtime configuration file, the one `apply` reads", - "always_required": true, - "repeatable": false, - "default_values": [], - "possible_values": [], - "environment": null - }, { "display": "--admin-url-file ", "description": "File holding the administrator PostgreSQL URL", @@ -12651,6 +12546,15 @@ "possible_values": [], "environment": null }, + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one `apply` reads", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--format ", "description": "Output format for local reports and authenticated API responses: readable text, or one JSON report", diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index c4fb06d8e9..bce7905514 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Verified access-token ownership and exact deployment policy matching. use crate::{store::Actor, CoordinatorError, Result}; -use registry_platform_authcommon::FailedCheck; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_config::{ JwksSource, OidcClientsConfig, OidcIssuerConfig, SecretProvidersConfig, }; @@ -317,7 +317,8 @@ impl AccessConfig { .map_err(|_| refused())?; Arc::new(JwksFetcher::new_static( parse_static_jwks(value.expose_secret()).map_err(|error| match error { - // The text names the key position and member, never key material. + // The text names the rule broken, and the key's position for a rule about + // one key, never key material. OidcError::StaticKeySet(_) => CoordinatorError::new( "access.configuration", error.to_string(), @@ -394,6 +395,8 @@ pub struct Authenticator { verifier: TokenVerifier, policies: BTreeMap, assertion_issuers: bool, + /// The claim the deployment reads scopes from, as configured. + scope_claim: String, } pub struct Caller { pub actor: Actor, @@ -468,6 +471,7 @@ impl Authenticator { assertion_issuers: bool, ) -> Self { Self { + scope_claim: profile.scope_claim.clone(), verifier: TokenVerifier::new(profile, keys), policies, assertion_issuers, @@ -527,12 +531,13 @@ impl Authenticator { .get(client) .filter(|p| p.subjects.iter().any(|s| s == subject)) .ok_or_else(|| denied(FailedCheck::AccessProfile))?; - if !p + if let Some(missing) = p .required_scopes .iter() - .all(|s| verified.scopes.contains(s)) + .find(|s| !verified.scopes.contains(s)) { - return Err(denied(FailedCheck::Scope)); + return Err(denied(FailedCheck::Scope) + .declaring(DeclaredScope::new(&self.scope_claim).with_required_scope(missing))); } Ok(Caller { actor: Actor { diff --git a/crates/registry-coordinator/src/authoring.rs b/crates/registry-coordinator/src/authoring.rs index 5ecc377b5f..1a7c20660c 100644 --- a/crates/registry-coordinator/src/authoring.rs +++ b/crates/registry-coordinator/src/authoring.rs @@ -2390,12 +2390,13 @@ pub(crate) fn positioned(document: &Document, error: CoordinatorError) -> Coordi error.code.as_str(), "function.value_limit" | "function.json" ) - && error.file.as_deref() != Some(Path::new("workflow.yaml")) + && error.file.as_deref().map(std::path::PathBuf::as_path) + != Some(Path::new("workflow.yaml")) { let mut error = error; error .file - .get_or_insert_with(|| Path::new("functions.rhai").into()); + .get_or_insert_with(|| Box::new(std::path::PathBuf::from("functions.rhai"))); return CoordinatorError::from_report(error.report()); } let exit = error.exit_code; diff --git a/crates/registry-coordinator/src/cli.rs b/crates/registry-coordinator/src/cli.rs index 55aec2e155..b9d7db37f3 100644 --- a/crates/registry-coordinator/src/cli.rs +++ b/crates/registry-coordinator/src/cli.rs @@ -193,6 +193,7 @@ enum Command { remove_workflow: Vec, }, /// Create the database, the migration and runtime roles, and the grants `apply` expects, as a PostgreSQL administrator. + #[command(mut_arg("runtime_config", |argument| argument.required(false)))] Provision(registry_platform_provision::cli::ProvisionArgs), /// Apply every listed workflow's package and least-privileged runtime grants using migration credentials. Apply { @@ -1079,6 +1080,13 @@ fn usage(error: &clap::Error, arguments: &[String]) -> CoordinatorError { format!("missing required argument {all}"), format!("Add {all}; {help} describes it."), ), + // A required argument the command's own definition relaxes, so that a + // global flag given before the command satisfies it, is checked when + // its value is read and names no argument. + (ErrorKind::MissingRequiredArgument, None) => ( + "missing required argument".to_owned(), + format!("Add the missing argument; {help} describes it."), + ), (ErrorKind::InvalidValue | ErrorKind::ValueValidation, Some(name)) => ( format!("invalid value for {name}"), match error.get(ContextKind::ValidValue) { diff --git a/crates/registry-coordinator/src/error.rs b/crates/registry-coordinator/src/error.rs index acd1255c2a..249bb05c59 100644 --- a/crates/registry-coordinator/src/error.rs +++ b/crates/registry-coordinator/src/error.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -use registry_platform_authcommon::FailedCheck; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_yaml::{Diagnostic, Report, Severity}; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; /// A category, authored location and repair action, without run payload /// values. A restore refusal's operator message names the run id or package @@ -11,7 +11,7 @@ use std::path::{Path, PathBuf}; pub struct CoordinatorError { pub code: String, pub message: String, - pub file: Option>, + pub file: Option>, pub field: Option>, pub suggested_action: Option>, pub diagnostics: Box<[Diagnostic]>, @@ -20,6 +20,9 @@ pub struct CoordinatorError { /// authentication, authorization and event-delivery refusals and read /// where the refusal is answered. A fixed member, never a caller value. pub check: Option, + /// What the deployment declared about a scope refusal, for the operator's + /// log line only: never a caller value, never written to an answer. + pub declared: Option>, } impl CoordinatorError { @@ -36,6 +39,7 @@ impl CoordinatorError { _ => 1, }, check: None, + declared: None, } } /// Preserve all shared-reader findings and their authored positions. @@ -56,7 +60,7 @@ impl CoordinatorError { file: deciding .source .as_ref() - .map(|source| PathBuf::from(&source.file).into_boxed_path()), + .map(|source| Box::new(PathBuf::from(&source.file))), field: Some(deciding.path.clone().into_boxed_str()), suggested_action: Some(deciding.suggested_action.clone().into_boxed_str()), diagnostics: diagnostics.into(), @@ -69,6 +73,7 @@ impl CoordinatorError { 1 }, check: None, + declared: None, } } /// Name the check that refused the caller. @@ -77,6 +82,12 @@ impl CoordinatorError { self.check = Some(check); self } + /// Attach the declared values of a scope refusal. + #[must_use] + pub(crate) fn declaring(mut self, declared: DeclaredScope) -> Self { + self.declared = Some(Box::new(declared)); + self + } pub(crate) fn with_exit(mut self, exit_code: u8) -> Self { self.exit_code = exit_code; self @@ -129,7 +140,7 @@ impl CoordinatorError { Report::new(vec![diagnostic]) } pub fn at(mut self, file: impl Into, field: impl Into) -> Self { - self.file = Some(file.into().into_boxed_path()); + self.file = Some(Box::new(file.into())); self.field = Some(field.into().into_boxed_str()); self } diff --git a/crates/registry-coordinator/src/http.rs b/crates/registry-coordinator/src/http.rs index 45340ff341..27bcc9301a 100644 --- a/crates/registry-coordinator/src/http.rs +++ b/crates/registry-coordinator/src/http.rs @@ -26,7 +26,7 @@ use axum::{ Json, Router, }; use registry_platform_authcommon::{ - record_refusal, BearerParseError, FailedCheck, RefusalNote, RefusalRecorder, + record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, RefusalRecorder, }; use registry_platform_httpsec::{ normalize_framework_rejection, FrameworkRejection, ProblemBody, TraceContext, @@ -126,7 +126,7 @@ pub fn router(state: HttpState) -> Router { let ready_state = state.clone(); let ready_bindings = Arc::new(BindingReadiness::default()); let routes = Router::new() - .route(HEALTH_PATH, get(|| async { Json(live_body()) })) + .route(HEALTH_PATH, get(live)) .route( READY_PATH, get(move || ready(ready_state.clone(), ready_bindings.clone())), @@ -204,7 +204,13 @@ async fn record_refusals( let response = next.run(request).await; if let Some(note) = response.extensions().get::() { let trace = current_trace(); - record_refusal!(refusals, *note, trace_id = trace.trace_id); + let declared = response.extensions().get::(); + record_refusal!( + refusals, + *note, + trace_id = trace.trace_id, + declared = declared + ); } response } @@ -251,6 +257,9 @@ pub(crate) fn problem(error: CoordinatorError) -> Response { let mut response = problem_response(problem); if let Some(check) = check { response.extensions_mut().insert(RefusalNote::new(check)); + if let Some(declared) = error.declared { + response.extensions_mut().insert(*declared); + } } response } @@ -406,6 +415,9 @@ fn live_body() -> Value { fn ready_body() -> Value { probe_body(READY_BODY, "ready") } +async fn live() -> Json { + Json(live_body()) +} async fn ready(s: HttpState, bindings: Arc) -> Response { if !s.recovery_only && deployment::check(&s.store, &s.runtime, s.workflows.digest()) @@ -432,13 +444,24 @@ mod readiness_tests { use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::Notify; - #[test] - fn the_probe_bodies_keep_the_shared_status_member_and_name_their_own() { - assert_eq!(live_body().to_string(), r#"{"live":true,"status":"ok"}"#); - assert_eq!( - ready_body().to_string(), - r#"{"ready":true,"status":"ready"}"# - ); + #[tokio::test] + async fn the_health_route_answers_the_shared_status_member_and_its_own() { + use tower::ServiceExt as _; + let response = Router::new() + .route(HEALTH_PATH, get(live)) + .oneshot( + axum::http::Request::builder() + .uri(HEALTH_PATH) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + assert_eq!(&body[..], br#"{"live":true,"status":"ok"}"#); } #[tokio::test(start_paused = true)] @@ -2106,6 +2129,30 @@ mod refusal_recording_tests { } } + #[tokio::test] + async fn a_scope_refusal_line_names_the_declared_values_and_nothing_else() { + let (answered, body, _, log) = refused( + CoordinatorError::new("access.denied", CANARY) + .failing(FailedCheck::Scope) + .declaring(DeclaredScope::new("scp").with_required_scope("coordinator:run")), + ) + .await; + assert_eq!(answered.as_u16(), 403); + for field in ["scope_claim=\"scp\"", "required_scope=\"coordinator:run\""] { + assert!(log.contains(field), "{field} in {log}"); + } + assert!(!log.contains("access_profile"), "{log}"); + assert!(!body.to_string().contains("coordinator:run"), "{body}"); + // A refusal that is not a scope refusal names no declared value. + let (_, _, _, other) = refused( + CoordinatorError::new("access.denied", CANARY) + .failing(FailedCheck::Operation) + .declaring(DeclaredScope::new("scp")), + ) + .await; + assert!(!other.contains("scope_claim"), "{other}"); + } + #[tokio::test] async fn an_answer_that_is_not_a_caller_refusal_is_not_counted() { for error in [ diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs index f39098962b..f34de9a891 100644 --- a/crates/registry-coordinator/src/provision.rs +++ b/crates/registry-coordinator/src/provision.rs @@ -96,7 +96,8 @@ fn load(path: &Path) -> Result> { /// `apply` grants to `deployment.runtimeRole` and the service requires its /// connection to log in as that role, so a runtime URL naming another user -/// would provision a role neither of them uses. The diagnostic names the +/// would provision a role neither of them uses. A URL with no user, or one +/// that does not parse, gets its own message. The diagnostic names the /// configured role, never the URL. fn require_runtime_role(runtime_url: &str, expected: &str) -> Result<(), Box> { let user = runtime_url @@ -104,15 +105,25 @@ fn require_runtime_role(runtime_url: &str, expected: &str) -> Result<(), Box() .ok() .and_then(|config| config.get_user().map(str::to_owned)); - if user.as_deref() == Some(expected) { - return Ok(()); + match user.as_deref() { + Some(user) if user == expected => Ok(()), + Some(_) => Err(Box::new(Diagnostic::error( + RUNTIME_ROLE_MISMATCH, + "/database/runtimeUrlRef", + format!( + "the runtime database URL does not log in as deployment.runtimeRole ({expected})" + ), + "Use the runtimeRole as the user of the URL database.runtimeUrlRef names, or change deployment.runtimeRole to the URL's user.", + ))), + None => Err(Box::new(Diagnostic::error( + RUNTIME_ROLE_MISMATCH, + "/database/runtimeUrlRef", + format!( + "the runtime database URL names no user, or is not a PostgreSQL URL, so it cannot log in as deployment.runtimeRole ({expected})" + ), + "Put the runtimeRole in the URL database.runtimeUrlRef names, as a PostgreSQL URL with a user.", + ))), } - Err(Box::new(Diagnostic::error( - RUNTIME_ROLE_MISMATCH, - "/database/runtimeUrlRef", - format!("the runtime database URL does not log in as deployment.runtimeRole ({expected})"), - "Use the runtimeRole as the user of the URL database.runtimeUrlRef names, or change deployment.runtimeRole to the URL's user.", - ))) } fn secret_text( diff --git a/crates/registry-coordinator/src/scenarios.rs b/crates/registry-coordinator/src/scenarios.rs index f3facadddb..1242e34e17 100644 --- a/crates/registry-coordinator/src/scenarios.rs +++ b/crates/registry-coordinator/src/scenarios.rs @@ -1864,7 +1864,9 @@ pub fn check(definition: &Definition, document: &ScenarioDocument) -> Result Vec { - if refused.file.as_deref() == Some(Path::new("workflow.yaml")) { + if refused.file.as_deref().map(std::path::PathBuf::as_path) == Some(Path::new("workflow.yaml")) + { return authoring::positioned(workflow, refused) .report() .into_diagnostics(); @@ -2065,7 +2068,9 @@ pub(crate) fn case_pointer(error: &CoordinatorError, index: usize) -> String { .field .as_deref() .filter(|field| { - field.starts_with('/') && error.file.as_deref() == Some(Path::new(SCENARIOS_FILE)) + field.starts_with('/') + && error.file.as_deref().map(std::path::PathBuf::as_path) + == Some(Path::new(SCENARIOS_FILE)) }) .unwrap_or_default(); format!("/cases/{index}{within}") diff --git a/crates/registry-coordinator/tests/deployment_postgres.rs b/crates/registry-coordinator/tests/deployment_postgres.rs index fe1f05279d..93882e4e92 100644 --- a/crates/registry-coordinator/tests/deployment_postgres.rs +++ b/crates/registry-coordinator/tests/deployment_postgres.rs @@ -412,13 +412,11 @@ async fn assert_bounded_readiness( database: &str, namespace: &str, ) { + let ready = http.get(format!("{origin}/ready")).send().await.unwrap(); + assert_eq!(ready.status(), 200); assert_eq!( - http.get(format!("{origin}/ready")) - .send() - .await - .unwrap() - .status(), - 200 + ready.json::().await.unwrap(), + serde_json::json!({"ready": true, "status": "ready"}) ); let (mut locker, connection) = tokio_postgres::connect(database, tokio_postgres::NoTls) .await diff --git a/crates/registry-coordinator/tests/deployment_surface.rs b/crates/registry-coordinator/tests/deployment_surface.rs index 033e601677..a419dcbc59 100644 --- a/crates/registry-coordinator/tests/deployment_surface.rs +++ b/crates/registry-coordinator/tests/deployment_surface.rs @@ -183,7 +183,18 @@ async fn verified_subject_owns_runs_and_exact_policy_restricts_flow_action() { scope, Utc::now().timestamp() + 300, ); - assert!(auth.authenticate(&token).await.is_err()); + let refusal = auth.authenticate(&token).await.err().unwrap(); + // Only a scope refusal declares values, and they come from the + // configuration, never from the token. + match refusal.declared { + Some(declared) => { + assert_eq!(scope, "wrong-scope"); + assert_eq!(declared.scope_claim(), "scope"); + assert_eq!(declared.required_scope(), Some("coordinator:start")); + assert_eq!(declared.access_profile(), None); + } + None => assert_ne!(scope, "wrong-scope"), + } } issuer.stop().await; } diff --git a/crates/registry-coordinator/tests/provision_cli.rs b/crates/registry-coordinator/tests/provision_cli.rs index b5a5e41692..58ff9383a5 100644 --- a/crates/registry-coordinator/tests/provision_cli.rs +++ b/crates/registry-coordinator/tests/provision_cli.rs @@ -196,6 +196,86 @@ fn a_runtime_url_user_that_is_not_the_deployment_runtime_role_is_refused_before_ ); } +#[test] +fn a_runtime_url_that_names_no_user_is_refused_as_missing_its_user() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + for url in [ + "postgres://db.example.org:5432/coordinator", + "not a postgresql url", + ] { + let output = provision_with( + &runtime, + &["--print-sql"], + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + Some(url.to_owned()), + ); + assert_refused( + &output, + "coordinator.runtime-config.runtime-role-mismatch", + "/database/runtimeUrlRef", + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("names no user"), + "the refusal says the URL has no user: {stderr}" + ); + assert!( + !stderr.contains("does not log in as"), + "a missing user is not reported as another user: {stderr}" + ); + } +} + +/// Every other verb takes `--runtime-config` before or after its name, and +/// `provision` does too. +#[test] +fn the_runtime_file_may_be_given_before_the_verb() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let run = |arguments: &[&std::ffi::OsStr]| { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .args(arguments) + .env( + "COORDINATOR_MIGRATION_URL", + database_url("coordinator_migration", MIGRATION_PASSWORD), + ) + .env( + "COORDINATOR_DATABASE_URL", + database_url("coordinator_runtime", RUNTIME_PASSWORD), + ) + .output() + .unwrap() + }; + let before = run(&[ + "--runtime-config".as_ref(), + runtime.as_os_str(), + "provision".as_ref(), + "--print-sql".as_ref(), + ]); + let after = run(&[ + "provision".as_ref(), + "--runtime-config".as_ref(), + runtime.as_os_str(), + "--print-sql".as_ref(), + ]); + assert_eq!( + before.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&before.stderr) + ); + assert_eq!(before.stdout, after.stdout, "the same plan either way"); + + let missing = run(&["provision".as_ref(), "--print-sql".as_ref()]); + assert_eq!(missing.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&missing.stderr); + assert!( + stderr.contains("missing required argument") && stderr.contains("provision --help"), + "the usage error says an argument is missing and where to read: {stderr}" + ); +} + #[test] fn an_unreadable_runtime_url_secret_is_refused_without_a_password() { let directory = tempfile::tempdir().unwrap(); diff --git a/crates/registry-documents/src/auth.rs b/crates/registry-documents/src/auth.rs index 661cededf5..f758102552 100644 --- a/crates/registry-documents/src/auth.rs +++ b/crates/registry-documents/src/auth.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use registry_documents_core::{ AccessProfiles, AccessRefusal, ActorKind, ActorKindClaim, Caller, VerifiedTokenFacts, }; -use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; +use registry_platform_authcommon::{validate_compact_access_token, DeclaredScope, FailedCheck}; use registry_platform_oidc::{ actor_kind, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, @@ -31,6 +31,8 @@ pub struct DocumentsAuthenticator { verifier: TokenVerifier, claim_names: ClaimNames, profiles: AccessProfiles, + /// The claim the deployment reads scopes from, as configured. + scope_claim: String, /// Whether the deployment declared any assertion authority at all. binds_assertion_issuers: bool, } @@ -48,6 +50,7 @@ impl DocumentsAuthenticator { .validate() .expect("the default contextual claim names are valid"); Self { + scope_claim: verifier.scope_claim.clone(), verifier: TokenVerifier::new(verifier, keys), claim_names, profiles, @@ -59,6 +62,16 @@ impl DocumentsAuthenticator { /// A refusal names the check it failed, for the operator's counter and /// log line. The answer to the caller does not carry it. pub async fn authenticate(&self, token: &str) -> Result { + self.authenticate_declaring(token) + .await + .map_err(|refusal| refusal.error) + } + + /// As [`Self::authenticate`], and a scope refusal also carries what the + /// deployment declared about it: the scope claim name, the scope the + /// profile requires, and the profile's id. None of it comes from the + /// token. + pub async fn authenticate_declaring(&self, token: &str) -> Result { validate_compact_access_token(token) .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; let verified = self @@ -76,9 +89,7 @@ impl DocumentsAuthenticator { tracing::debug!( "an exchanged credential arrived at a deployment that declared no assertion authority" ); - return Err(AuthenticationError::Profile( - FailedCheck::TokenAssertionIssuer, - )); + return Err(AuthenticationError::Profile(FailedCheck::TokenAssertionIssuer).into()); } let client_id = verified .matched_client_id() @@ -94,11 +105,31 @@ impl DocumentsAuthenticator { self.profiles .resolve(&facts) .map_err(|refusal| match refusal { - AccessRefusal::Profile => AuthenticationError::Profile(self.profile_check(&facts)), - AccessRefusal::Claims => AuthenticationError::Claims(claims_check(&facts)), + AccessRefusal::Profile => { + let check = self.profile_check(&facts); + let declared = (check == FailedCheck::Scope) + .then(|| self.declared_scope(&facts)) + .flatten(); + DeclaredRefusal { + error: AuthenticationError::Profile(check), + declared, + } + } + AccessRefusal::Claims => AuthenticationError::Claims(claims_check(&facts)).into(), }) } + /// The scope claim, the scope and the access profile a scope refusal is + /// about, all from configuration. + fn declared_scope(&self, facts: &VerifiedTokenFacts<'_>) -> Option { + let missing = self.profiles.missing_scope(facts)?; + Some( + DeclaredScope::new(&self.scope_claim) + .with_required_scope(missing.scope) + .with_access_profile(missing.profile), + ) + } + /// Which check a profile refusal failed. The access profiles answer only /// that no profile admits the token. A missing scope is the one the /// profiles name themselves. Resolving the same facts under each kind a @@ -147,6 +178,23 @@ impl std::fmt::Debug for DocumentsAuthenticator { } } +/// A refusal of authentication with the values the deployment declared about +/// it, when it is a scope refusal. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DeclaredRefusal { + pub error: AuthenticationError, + pub declared: Option, +} + +impl From for DeclaredRefusal { + fn from(error: AuthenticationError) -> Self { + Self { + error, + declared: None, + } + } +} + /// Why authentication did not admit a caller. Each refusal carries the check /// it failed, which is operator-side only and never written to a response. #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] @@ -352,6 +400,33 @@ pub(crate) mod tests { ); } + #[tokio::test] + async fn a_scope_refusal_declares_the_configured_values_and_none_of_the_tokens() { + let mut unscoped = citizen_claims(); + unscoped["scope"] = json!("canary-scope-from-the-token"); + let refusal = authenticator() + .authenticate_declaring(&token(unscoped)) + .await + .unwrap_err(); + assert_eq!( + refusal.error, + AuthenticationError::Profile(FailedCheck::Scope) + ); + let declared = refusal.declared.expect("a scope refusal declares values"); + assert_eq!(declared.scope_claim(), "scope"); + assert_eq!(declared.required_scope(), Some("documents:own")); + assert_eq!(declared.access_profile(), Some("citizen")); + assert!(!format!("{declared:?}").contains("canary-scope-from-the-token")); + // Another refusal declares nothing. + let mut unprofiled = citizen_claims(); + unprofiled["azp"] = json!("unprofiled-client"); + let other = authenticator() + .authenticate_declaring(&token(unprofiled)) + .await + .unwrap_err(); + assert_eq!(other.declared, None); + } + #[tokio::test] async fn a_token_outside_every_profile_is_a_profile_refusal() { let mut unscoped = citizen_claims(); @@ -466,6 +541,29 @@ pub(crate) mod tests { ); } + /// A key endpoint the verifier refuses to contact, or a static key set it + /// cannot use, is counted under `key-source-unavailable` and answers the + /// refusal a credential gets (401), not the 503 of a key set that could + /// not be fetched or read. The operator pages say so. + #[test] + fn a_key_source_the_verifier_refuses_is_counted_unavailable_and_answers_a_refusal() { + use registry_platform_oidc::{OidcEndpoint, StaticJwksError}; + for error in [ + OidcError::EndpointRefused { + endpoint: OidcEndpoint::DiscoveredCrossOriginJwks, + remedy: "declare the endpoint", + }, + OidcError::InsecureHttpRequiresOptIn, + OidcError::StaticKeySet(StaticJwksError::Empty), + ] { + assert_eq!( + verifier_failure(&error), + AuthenticationError::Refused(FailedCheck::KeySourceUnavailable), + "{error:?}" + ); + } + } + #[test] fn a_refused_credential_carries_the_check_the_verifier_names() { assert_eq!( diff --git a/crates/registry-documents/src/http.rs b/crates/registry-documents/src/http.rs index e2527d7fc5..be23fc788a 100644 --- a/crates/registry-documents/src/http.rs +++ b/crates/registry-documents/src/http.rs @@ -27,7 +27,7 @@ use registry_documents_core::{ READY_PATH, }; use registry_platform_authcommon::{ - parse_bearer_token, BearerParseError, FailedCheck, RefusalNote, + parse_bearer_token, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, }; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, @@ -253,13 +253,16 @@ impl DocumentRoutes { /// The verified caller, before anything else of the request is read. /// A missing or refused credential is `authentication.refused`; a token /// that resolves to no access profile is `profile.not-authorized`. - async fn caller(&self, headers: &HeaderMap) -> Result { + async fn caller(&self, headers: &HeaderMap) -> Result { let token = bearer_token(headers)?; let caller = self .authenticator - .authenticate(token) + .authenticate_declaring(token) .await - .map_err(authentication_refusal)?; + .map_err(|refusal| Refusal { + error: authentication_refusal(refusal.error), + declared: refusal.declared, + })?; self.service.admit().await?; Ok(caller) } @@ -322,8 +325,36 @@ fn identifier(text: &str) -> Result { Uuid::parse_str(text).map_err(|_| ServiceError::concealed(FailedCheck::Visibility)) } -fn answer(result: Result) -> Response { - result.unwrap_or_else(refusal_response) +/// A failed operation, and the values the deployment declared about it when +/// it is a scope refusal. The values go to the operator's log line only. +pub(crate) struct Refusal { + error: ServiceError, + declared: Option, +} + +impl From for Refusal { + fn from(error: ServiceError) -> Self { + Self { + error, + declared: None, + } + } +} + +impl From for Refusal { + fn from(problem: ProblemCode) -> Self { + ServiceError::from(problem).into() + } +} + +fn answer(result: Result) -> Response { + result.unwrap_or_else(|refusal| { + let mut response = refusal_response(refusal.error); + if let Some(declared) = refusal.declared { + response.extensions_mut().insert(declared); + } + response + }) } /// The remedy the log line of a scope refusal carries. diff --git a/crates/registry-documents/src/metrics.rs b/crates/registry-documents/src/metrics.rs index e011eff2d9..63a7f92c94 100644 --- a/crates/registry-documents/src/metrics.rs +++ b/crates/registry-documents/src/metrics.rs @@ -39,7 +39,7 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{Method, Request, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; -use registry_platform_authcommon::{record_refusal, RefusalNote, RefusalRecorder}; +use registry_platform_authcommon::{record_refusal, DeclaredScope, RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ sample_error_class, CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CLASS_NO_TIME_LEFT, CLASS_POOL, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -217,6 +217,12 @@ impl Metrics { record_refusal!(self.refusals, note); } + /// As [`Self::record_refusal`], and a scope refusal's line also names the + /// values the deployment declared for it. + pub fn record_refusal_declaring(&self, note: RefusalNote, declared: Option<&DeclaredScope>) { + record_refusal!(self.refusals, note, declared = declared); + } + /// Record that `worker` just completed a pass. pub fn record_worker_success(&self, worker: Worker) { self.record_worker_success_at(worker, self.started.elapsed().as_secs()); @@ -376,7 +382,7 @@ pub async fn count_requests( let response = next.run(request).await; metrics.record_request(&route, &method, response.status()); if let Some(note) = response.extensions().get::() { - metrics.record_refusal(*note); + metrics.record_refusal_declaring(*note, response.extensions().get::()); } response } diff --git a/crates/registry-documents/tests/refusal_golden.rs b/crates/registry-documents/tests/refusal_golden.rs index 9820e50435..74bbc76f63 100644 --- a/crates/registry-documents/tests/refusal_golden.rs +++ b/crates/registry-documents/tests/refusal_golden.rs @@ -139,7 +139,12 @@ struct World { } async fn world() -> World { - let mut deployment = Deployment::new(DATABASE_STORAGE, DISABLED_VERIFIER).await; + world_with_project(support::STARTER_PROJECT).await +} + +async fn world_with_project(project: &str) -> World { + let mut deployment = + Deployment::with_project(DATABASE_STORAGE, DISABLED_VERIFIER, project).await; let port = std::net::TcpListener::bind("127.0.0.1:0") .unwrap() .local_addr() @@ -641,3 +646,84 @@ async fn a_request_that_is_not_refused_is_not_counted() { assert_eq!(counted_in_total(&world.prepared).await, before); drop(world.deployment); } + +/// A custodian whose profile has no grant authority is refused under +/// `operation`, not `ownership`, with the answer the reserving system gets. +/// Under `citizen-delivery` with represented-principal grants refused, the +/// citizen holds the document and may not issue a grant on it. +#[tokio::test] +async fn a_custodian_without_grant_authority_is_counted_under_operation() { + let project = support::STARTER_PROJECT.replacen( + "representedPrincipalGrants: permitted", + "representedPrincipalGrants: refused", + 1, + ); + assert_ne!( + project, + support::STARTER_PROJECT, + "the starter changed shape" + ); + let world = world_with_project(&project).await; + let fixture = Fixture::as_principal( + "grant-issued-by-a-custodian-without-grant-authority", + FailedCheck::Operation, + Method::POST, + &format!("/v1/documents/{}/grants", world.document), + CITIZEN, + ) + .with_body( + json!({"versionId": world.version, "grantee": {"subject": "reader-1", "kind": "human"}}), + ); + let operation_before = counted(&world.prepared, FailedCheck::Operation).await; + let ownership_before = counted(&world.prepared, FailedCheck::Ownership).await; + let (_, answer) = observe(&world.api, &fixture).await; + assert_eq!( + counted(&world.prepared, FailedCheck::Operation).await, + operation_before + 1 + ); + assert_eq!( + counted(&world.prepared, FailedCheck::Ownership).await, + ownership_before + ); + let golden: Value = serde_json::from_slice(&std::fs::read(golden_path()).unwrap()).unwrap(); + assert_eq!(answer, golden["grant-issued-by-the-reserving-system"]); + drop(world.deployment); +} + +/// A scope refusal's line names what the deployment declared, the scope +/// claim, the scope the profile requires and the profile, and nothing the +/// token carried in its own scope. +#[tokio::test] +async fn a_scope_refusal_line_names_the_declared_values_and_none_of_the_tokens() { + let world = world().await; + let logs = registry_platform_testing::CapturedDiagnosticLogs::default(); + let canary = "canary-scope-from-the-token"; + let fixture = Fixture::get( + "listing-with-another-scope", + FailedCheck::Scope, + "/v1/documents", + Credential::Token(token_with(CITIZEN, claims("scope", json!(canary)))), + ); + let (answer, _) = observe(&world.api, &fixture) + .with_subscriber(logs.subscriber()) + .await; + assert_eq!(answer.status, 403); + let text = logs.text(); + assert!( + !text.contains(canary), + "the token's scope reached the log\n{text}" + ); + let line: Value = text + .lines() + .filter(|line| line.contains("request refused")) + .map(|line| serde_json::from_str(line).unwrap()) + .next() + .unwrap_or_else(|| panic!("no refusal line\n{text}")); + let fields = &line["fields"]; + assert_eq!(fields["failed_check"], "scope"); + assert_eq!(fields["scope_claim"], "scope"); + assert_eq!(fields["required_scope"], "documents:own"); + assert_eq!(fields["access_profile"], "citizen"); + assert!(fields["remedy"].as_str().unwrap().contains("scopeClaim")); + drop(world.deployment); +} diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index 1cabc6388c..fb4b72ec10 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -48,8 +48,10 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. - Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and - recording a refusal changes nothing the caller receives. + A scope refusal's line also names the scope claim the deployment configured and the scope the + caller's policy requires, as `scope_claim` and `required_scope`. + Apart from those two configured values, neither the counter nor the line holds a token, claim, + client, subject, scope or identifier, and recording a refusal changes nothing the caller receives. The older `coordinator_authentication_refusals_total{reason}` counter is unchanged. - Host users run `coordinatorctl`, which is local operator tooling for a trusted single-user machine. diff --git a/docs/site/src/content/docs/security/documents.mdx b/docs/site/src/content/docs/security/documents.mdx index a60537dceb..1c8faeb356 100644 --- a/docs/site/src/content/docs/security/documents.mdx +++ b/docs/site/src/content/docs/security/documents.mdx @@ -50,12 +50,15 @@ and the restore drill is in published at zero, and no caller value becomes a label. The counter covers a missing or refused credential, a token that resolves to no access profile, a refused custody placement, a caller that sees a document but may not act on it, a document or - upload the caller may not see, and a verifier that cannot reach its key source - (`key-source-unavailable`). - Each refusal also writes one `request refused` log line with `failed_check` and the request's - trace id when it has one, at most five lines per check per minute, with `suppressed` counting what - a window held back. - A scope refusal carries a fixed remedy that names `authentication.oidc.scopeClaim`. + upload the caller may not see, and a verifier that cannot reach or use its key source + (`key-source-unavailable`). A key set the verifier cannot fetch, read or use answers 503. A key + endpoint the verifier refuses to contact answers the refusal a bad credential gets, and is counted + the same way. + Each refusal also writes one `request refused` log line with `failed_check`, at most five lines per + check per minute, with `suppressed` counting what a window held back. + A scope refusal's line also carries `scope_claim`, `required_scope` and `access_profile`, the + values the deployment configured, never the token's own scope, and a fixed remedy that names + `authentication.oidc.scopeClaim`. Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and recording a refusal changes nothing the caller receives. - The custodian alone removes a document and issues, lists and revokes its grants. diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index 254dd74175..42fd757488 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -7,7 +7,10 @@ writes one `request refused` line with `failed_check` and the request's trace id, at most five lines per check per minute. A policy denial after authentication and a refused signed event delivery are now counted and - logged too. Refusal statuses and bodies are unchanged, and + logged too. A scope refusal's line also names the scope claim the + deployment configured and the scope the caller's policy requires, as + `scope_claim` and `required_scope`, and nothing from the token. Refusal + statuses and bodies are unchanged, and `coordinator_authentication_refusals_total{reason}` stays. - Wherever Coordinator and `coordinatorctl` allow plaintext to a loopback host, an IPv4-mapped loopback literal such as `[::ffff:127.0.0.1]` counts as @@ -17,15 +20,18 @@ signing key is unreadable, missing or too short counts under `key-source-unavailable` in `coordinator_request_refusals_total`. The 401 and 503 answers are unchanged. -- A static key set that startup refuses now names the key position and member - in the `access.configuration` message instead of pointing at the issuer and - policy configuration. +- A static key set that startup refuses now names the rule it broke, and the + key's position for a rule about one key, in the `access.configuration` + message instead of pointing at the issuer and policy configuration. - `coordinatorctl provision` creates the database, the migration and runtime roles and the grants `apply` expects, from the two database URLs in the runtime file, as a PostgreSQL administrator. `--print-sql` prints the plan and connects to nothing. When the runtime file has a `deployment` block, a runtime URL whose user is not `deployment.runtimeRole` is refused before any - connection with `coordinator.runtime-config.runtime-role-mismatch`. + connection with `coordinator.runtime-config.runtime-role-mismatch`, and a + runtime URL that names no user gets its own message under the same code. + `coordinatorctl --runtime-config FILE provision` is accepted, as for every + other `coordinatorctl` command. - `GET /health` and `GET /ready` carry the `status` member the other services answer: `{"live":true,"status":"ok"}` and diff --git a/products/documents/CHANGELOG.md b/products/documents/CHANGELOG.md index 0524cee508..8fbb4e295e 100644 --- a/products/documents/CHANGELOG.md +++ b/products/documents/CHANGELOG.md @@ -15,16 +15,19 @@ - The Document Store counts every refused request by the check that refused it, in `documents_request_refusals_total{check}` on the metrics listener, published at zero for every check. Each refusal writes one `request refused` - line with `failed_check`, at most five lines per check per minute. That line - replaces the scope refusal line, which named the claim, the scope and the - access profile; a scope refusal now carries a fixed remedy that names - `authentication.oidc.scopeClaim`. Refusal statuses, headers and bodies are - unchanged. + line with `failed_check`, at most five lines per check per minute. A scope + refusal's line also names the scope claim the deployment configured, the + scope the access profile requires and the profile's id, as `scope_claim`, + `required_scope` and `access_profile`, and carries a fixed remedy that names + `authentication.oidc.scopeClaim`. No value from the token is written. + Refusal statuses, headers and bodies are unchanged. - A static key set with a private key member or a repeated member name is refused at startup, and the error names the rule it broke, and the key's position for a rule about one key, never a key value. -- A token verifier that cannot reach its key source still answers 503, and the - operator's record of it is the `request refused` line with `failed_check` +- A token verifier that cannot fetch, read or use its key set still answers + 503. A key endpoint the verifier refuses to contact answers the refusal a bad + credential gets, with its `WWW-Authenticate` header. The operator's record of + either is the `request refused` line with `failed_check` `key-source-unavailable` and the counter, not a warning per request, so `DOCUMENTS_LOG=warn` writes no line for it. - A caller that sees a document and does not hold custody of it is counted diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 6f82cce568..a4aa7010e6 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5414,7 +5414,7 @@ "description": "Registry Coordinator portable project authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/authoring.rs", - "sha256": "1bb41563fd58ad1544df962d17d94172fe76c027128020095da08b5ba63ae733" + "sha256": "9b527f0a859daded79ed7fc6f23e764f8c644b277550fb3a2fa030be127d416b" }, "artifact": { "path": "products/coordinator/generated/project/project.schema.json", @@ -5450,7 +5450,7 @@ "description": "Registry Coordinator deterministic scenario authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/scenarios.rs", - "sha256": "d15a452b05c77a398cf957e0f955fb0d7faa2b478df6ee1780f10606d21366b3" + "sha256": "74658bd513eea12df551c2eb2f0edb1255695b5830022a6c414a095340358d9b" }, "artifact": { "path": "products/coordinator/generated/scenarios/scenarios.schema.json", From ae72bd4ec88f26485f277d1e65f3d5a16609f984 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:45:55 +0100 Subject: [PATCH 058/136] fix: name declared scope on BReg and Casework refusals and build each refusal with its check A scope refusal line in BReg and Casework names the configured scope claim, the scope the operation needs and the access profile when one applies, as the configuration or package declares them. Nothing the token held is written, and answers are unchanged. BReg builds every 401, 403 and concealing 404 through one function that takes the failed check, Casework builds every refusal the same way, and a debug build catches one built without. A grant whose verified client is missing or invalid counts under token-client, concealed batch items are counted once the batch answers, and the Python hook verifier stub accepts None for caller_enforced_freshness. The BReg monitoring and security pages state which 412 answers and routes are not counted and which key set rules name their rule and position. Signed-off-by: Jeremi Joslin --- .../python/registry_breg_client/__init__.pyi | 2 +- .../tests/python/test_webhook_verification.py | 11 ++ crates/registry-breg/src/api/actions.rs | 1 + crates/registry-breg/src/api/context.rs | 52 ++++++++ .../registry-breg/src/api/external_views.rs | 1 + crates/registry-breg/src/api/ingestion.rs | 4 +- crates/registry-breg/src/api/mod.rs | 96 +++++++++++++-- crates/registry-breg/src/api/proposals.rs | 12 +- crates/registry-breg/src/auth.rs | 80 ++++++++++--- crates/registry-breg/src/correlation.rs | 111 ++++++++++++++++- .../tests/authentication_refusals.rs | 21 +++- .../tests/concealment_refusals.rs | 36 ++++-- crates/registry-casework/src/auth.rs | 40 ++++++- .../registry-casework/src/auth/delegated.rs | 7 ++ crates/registry-casework/src/http.rs | 113 ++++++++++++++++-- .../registry-casework/tests/refusal_golden.rs | 30 ++++- .../src/content/docs/operate/breg-monitor.mdx | 5 +- docs/site/src/content/docs/security/breg.mdx | 8 +- .../src/content/docs/security/casework.mdx | 8 +- products/breg/CHANGELOG.md | 9 +- products/casework/CHANGELOG.md | 5 + 21 files changed, 582 insertions(+), 70 deletions(-) diff --git a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi index bb7db6f3a9..bd54309017 100644 --- a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi +++ b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi @@ -238,7 +238,7 @@ def verify_hook_delivery( body: bytes, key: bytes, max_skew_seconds: int | None = None, - caller_enforced_freshness: bool = False, + caller_enforced_freshness: bool | None = None, ) -> VerifiedHookDelivery: """Authenticate one exact Base Registry Engine Version 1 hook delivery. The delivery time must be within 300 seconds of the receiver clock unless diff --git a/crates/registry-breg-client-py/tests/python/test_webhook_verification.py b/crates/registry-breg-client-py/tests/python/test_webhook_verification.py index bf4d9a5362..28736aee81 100644 --- a/crates/registry-breg-client-py/tests/python/test_webhook_verification.py +++ b/crates/registry-breg-client-py/tests/python/test_webhook_verification.py @@ -173,6 +173,17 @@ def test_default_window_is_300_seconds_in_both_directions(self) -> None: def test_default_window_refuses_the_old_fixed_vector(self) -> None: self.assert_refused("stale-delivery", caller_enforced_freshness=False) + def test_an_explicit_none_freshness_option_keeps_the_default_window(self) -> None: + self.assert_refused("stale-delivery", caller_enforced_freshness=None) + self.assertEqual( + verify( + headers=signed_headers(datetime.now(timezone.utc)), + max_skew_seconds=None, + caller_enforced_freshness=None, + )["attempt"], + "1", + ) + def test_max_skew_seconds_replaces_the_default_window(self) -> None: stamp = datetime.now(timezone.utc) - timedelta(seconds=600) self.assertEqual(verify_default(stamp, max_skew_seconds=900)["attempt"], "1") diff --git a/crates/registry-breg/src/api/actions.rs b/crates/registry-breg/src/api/actions.rs index 1f2fd0bcb6..a2eb88adb8 100644 --- a/crates/registry-breg/src/api/actions.rs +++ b/crates/registry-breg/src/api/actions.rs @@ -188,6 +188,7 @@ fn authorize_action_checked<'a>( .iter() .all(|scope| claims.has_scope(scope)) { + claims.declare_scope_refusal(&grant.required_scopes, Some(&grant.profile_id)); return Err(FailedCheck::Scope); } if !grant.required_purposes.is_empty() diff --git a/crates/registry-breg/src/api/context.rs b/crates/registry-breg/src/api/context.rs index a214692c46..1c338605eb 100644 --- a/crates/registry-breg/src/api/context.rs +++ b/crates/registry-breg/src/api/context.rs @@ -85,6 +85,16 @@ pub struct VerifiedRequestClaims { grant_subjects: BTreeMap, human_identity: Option, recipients: BTreeSet, + scope_declaration: Option, +} + +/// Where a scope refusal records the values the operator declared: the name of +/// the claim that carries scopes, and the request's slot for the recording +/// layer. Both come from configuration and the request, never from the token. +#[derive(Clone, Debug, Eq, PartialEq)] +struct ScopeDeclaration { + scope_claim: std::sync::Arc, + slot: crate::correlation::DeclaredScopeSlot, } /// The verified claims of an authenticated caller, as a handler extractor. @@ -115,6 +125,47 @@ impl axum::extract::FromRequestParts for Authenticated { } impl VerifiedRequestClaims { + /// Bind the claims to the request's recording slot, so a scope refusal can + /// name the configured scope claim. + #[must_use] + pub(crate) fn with_scope_declaration( + mut self, + scope_claim: &str, + slot: crate::correlation::DeclaredScopeSlot, + ) -> Self { + self.scope_declaration = Some(ScopeDeclaration { + scope_claim: scope_claim.into(), + slot, + }); + self + } + + /// Record, for the operator's refusal line, the scope the operation needs + /// and the access profile that was applied. Both are declared by the + /// package, never read from the token. The first required scope the token + /// lacks is the one named. + pub(crate) fn declare_scope_refusal<'a>( + &self, + required_scopes: impl IntoIterator, + access_profile: Option<&str>, + ) { + let Some(declaration) = &self.scope_declaration else { + return; + }; + let mut declared = + registry_platform_authcommon::DeclaredScope::new(&*declaration.scope_claim); + if let Some(scope) = required_scopes + .into_iter() + .find(|scope| !self.has_scope(scope)) + { + declared = declared.with_required_scope(scope); + } + if let Some(profile) = access_profile { + declared = declared.with_access_profile(profile); + } + declaration.slot.set(declared); + } + pub fn authenticated( principal_claim: impl Into, principal: impl Into, @@ -141,6 +192,7 @@ impl VerifiedRequestClaims { grant_subjects: BTreeMap::new(), human_identity: None, recipients: BTreeSet::new(), + scope_declaration: None, }) } diff --git a/crates/registry-breg/src/api/external_views.rs b/crates/registry-breg/src/api/external_views.rs index 1446b481ed..ee9fc8847d 100644 --- a/crates/registry-breg/src/api/external_views.rs +++ b/crates/registry-breg/src/api/external_views.rs @@ -398,6 +398,7 @@ async fn admit_source_change( } else if claims.requester_client() != Some(notifier.requester_client.as_str()) { Err(FailedCheck::RequesterClient) } else if !claims.has_scope(¬ifier.required_scope) { + claims.declare_scope_refusal([¬ifier.required_scope], None); Err(FailedCheck::Scope) } else { Ok(()) diff --git a/crates/registry-breg/src/api/ingestion.rs b/crates/registry-breg/src/api/ingestion.rs index 1894f8f8c2..889600bbdd 100644 --- a/crates/registry-breg/src/api/ingestion.rs +++ b/crates/registry-breg/src/api/ingestion.rs @@ -708,8 +708,8 @@ fn ingestion_problem(error: IngestionServiceError) -> Response { | IngestionServiceError::InvalidTimerWindow { .. } => invalid_request(), IngestionServiceError::PreconditionFailed => precondition_failed(), IngestionServiceError::NotFound => concealed(FailedCheck::Visibility), - IngestionServiceError::ProfileMismatch => crate::correlation::note_refusal( - fixed_problem(ProblemCode::IngestionProfileMismatch), + IngestionServiceError::ProfileMismatch => refusal_problem( + ProblemCode::IngestionProfileMismatch, FailedCheck::AccessProfile, ), IngestionServiceError::RunNotOpen => fixed_problem(ProblemCode::IngestionRunNotOpen), diff --git a/crates/registry-breg/src/api/mod.rs b/crates/registry-breg/src/api/mod.rs index 9b926ff42a..8a91757c88 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -311,10 +311,7 @@ async fn review_completion( body: Body, ) -> Response { let Some(receiver) = service.review_completions.as_ref() else { - return crate::correlation::note_refusal( - fixed_problem(ProblemCode::ResourceNotFound), - FailedCheck::Visibility, - ); + return concealed(FailedCheck::Visibility); }; let token = match crate::auth::bearer_token(&headers) { Ok(token) => token, @@ -402,7 +399,7 @@ fn recipient_binding(headers: &HeaderMap) -> Result<&str, FailedCheck> { } fn review_completion_refused(check: FailedCheck) -> Response { - crate::correlation::note_refusal(fixed_problem(ProblemCode::AuthenticationRefused), check) + refusal_problem(ProblemCode::AuthenticationRefused, check) } async fn health() -> Response { @@ -3021,6 +3018,7 @@ pub(crate) fn authorize_profile_claims( .iter() .all(|scope| claims.has_scope(scope)) { + claims.declare_scope_refusal(&profile.required_scopes, Some(&profile.id)); return Err(ClaimRefusal::new( "required-scope-missing", FailedCheck::Scope, @@ -5144,13 +5142,16 @@ fn method_name(method: crate::model::HttpMethod) -> &'static str { /// The 404 that hides whether the target exists or what the caller may see. /// The check names, for the operator only, which rule refused. fn concealed(check: FailedCheck) -> Response { - crate::correlation::note_refusal(fixed_problem(ProblemCode::ResourceNotFound), check) + refusal_problem(ProblemCode::ResourceNotFound, check) } /// The 404 of a path or method the service does not serve. No check refused /// the caller, so nothing is counted. fn unknown_route() -> Response { - fixed_problem(ProblemCode::ResourceNotFound) + build_problem( + ProblemCode::ResourceNotFound, + ProblemCode::ResourceNotFound.description(), + ) } fn unavailable() -> Response { @@ -5763,7 +5764,9 @@ fn mutation_problem_response(error: MutationError) -> Response { | MutationError::FieldGuardFailed { .. } | MutationError::ProposalGuardFailed(_) | MutationError::TimerGenerationUnsupported => precondition_failed(), - MutationError::WriteOutsideBoundary => fixed_problem(ProblemCode::WriteOutsideBoundary), + MutationError::WriteOutsideBoundary => { + refusal_problem(ProblemCode::WriteOutsideBoundary, FailedCheck::RowBoundary) + } MutationError::Conflict | MutationError::ProposalUniqueConflict => { fixed_problem(ProblemCode::MutationConflict) } @@ -5834,11 +5837,39 @@ fn mutation_problem_for_fields( } } +/// An answer that is not a refusal of authority. A code that refuses authority +/// (401, 403, or the 404 that conceals) is built with [`refusal_problem`] so it +/// names its check. A refusal code arriving here is a defect: it is answered +/// unchanged and logged once, and a debug build stops. fn fixed_problem(code: ProblemCode) -> Response { problem_with_detail(code, code.description()) } fn problem_with_detail(code: ProblemCode, detail: &'static str) -> Response { + if refuses_authority(code) { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + code = code.code(), + "a refusal was answered without its failed check" + ); + } + build_problem(code, detail) +} + +/// A refusal of authority, with the check it failed. The check reaches the +/// operator's counter and log line through the response extensions and never +/// the caller's body. +fn refusal_problem(code: ProblemCode, check: FailedCheck) -> Response { + crate::correlation::note_refusal(build_problem(code, code.description()), check) +} + +/// The codes answered as a refusal of authority: every 401 and 403, and the +/// 404 that hides what the caller may see. +fn refuses_authority(code: ProblemCode) -> bool { + matches!(code.status(), 401 | 403) || code == ProblemCode::ResourceNotFound +} + +fn build_problem(code: ProblemCode, detail: &'static str) -> Response { let status = StatusCode::from_u16(code.status()).expect("problem catalogue status is valid"); crate::correlation::problem_response(status, code.title(), detail, code.code()) } @@ -6412,6 +6443,55 @@ mod refusal_check_tests { assert_eq!(noted(&unknown), None); } + /// The codes answered as a refusal of authority, read from the catalogue + /// so a code added later is covered. + fn refusal_codes() -> Vec { + ProblemCode::ALL + .iter() + .copied() + .filter(|code| refuses_authority(*code)) + .collect() + } + + /// Every code answered as a 401, a 403 or the concealing 404 is built with + /// its check, and building one without the check is a defect. + #[test] + fn every_refusal_code_is_built_with_its_check() { + let refusals = refusal_codes(); + for status in [401, 403, 404] { + assert!( + refusals.iter().any(|code| code.status() == status), + "the catalogue lists a {status} refusal" + ); + } + for code in ProblemCode::ALL { + let status = code.status(); + if matches!(status, 401 | 403) { + assert!(refusals.contains(code), "{} is a refusal", code.code()); + } + } + for code in refusals { + let response = refusal_problem(code, FailedCheck::Visibility); + assert_eq!(response.status().as_u16(), code.status()); + assert_eq!(noted(&response), Some(FailedCheck::Visibility)); + } + } + + #[cfg(debug_assertions)] + #[test] + fn a_refusal_code_without_its_check_stops_a_debug_build() { + let refusals = refusal_codes(); + assert!(!refusals.is_empty()); + for code in refusals { + let outcome = std::panic::catch_unwind(|| fixed_problem(code)); + assert!( + outcome.is_err(), + "{} was built without a check", + code.code() + ); + } + } + #[test] fn a_mutation_refusal_names_the_check_and_a_plain_failure_names_none() { for (error, check) in [ diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index 94c904c8da..072710c304 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -183,6 +183,7 @@ fn request_matches( return Err(FailedCheck::TokenClaims); } if !required_scopes.iter().all(|scope| claims.has_scope(scope)) { + claims.declare_scope_refusal(required_scopes, None); return Err(FailedCheck::Scope); } if !required_purposes.is_empty() @@ -1300,6 +1301,7 @@ pub(super) async fn review_context_batch( // Bound the aggregate independently of each Proposal's configured context. let mut remaining = 8 * 1024 * 1024 - 64 * 1024; let mut items = Vec::with_capacity(ids.len()); + let mut concealed_items = Vec::new(); for id in ids { let response = review_read( service.clone(), @@ -1322,14 +1324,18 @@ pub(super) async fn review_context_batch( items.push(json!({"id":id,"status":"visible","context":context})); } StatusCode::NOT_FOUND => { - // The batch answers 200, so each concealed item records its - // own refusal here. - crate::correlation::record_noted_refusal(&response, &correlation); + concealed_items.push(response); items.push(json!({"id":id,"status":"concealed"})); } _ => return response, } } + // The batch answers 200, so each concealed item records its own refusal. + // They are recorded only once the batch answers, so a batch that ends with + // another answer counts nothing the caller did not see. + for response in &concealed_items { + crate::correlation::record_noted_refusal(response, &correlation); + } json_response(json!({"items":items}), None) } diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index 070d676254..30bd77e743 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -374,14 +374,7 @@ impl RegistryAuthenticator { if let Some(grant) = &grant { grant .verify_context(&verified, &self.audience) - .map_err(|error| { - invalid_claims(match error { - GrantContextError::ClientMismatch | GrantContextError::ResourceMismatch => { - FailedCheck::TaskGrantBinding - } - _ => FailedCheck::TaskGrantClaims, - }) - })?; + .map_err(|error| invalid_claims(grant_context_check(error)))?; task_grant_token_lifetime(verified.claims.iat, verified.claims.exp, now, self.leeway) .map_err(invalid_claims)?; } @@ -531,6 +524,16 @@ pub(crate) async fn authenticate_request( return authentication_refused(refusal.check); } }; + let claims = match request + .extensions() + .get::() + { + Some(correlation) => claims.with_scope_declaration( + &authenticator.scope_claim, + correlation.declared_scope_slot(), + ), + None => claims, + }; request.extensions_mut().insert(claims); next.run(request).await } @@ -1001,6 +1004,21 @@ fn mapped_scalar_claim( Ok(value) } +/// The check a task grant refused by its token context failed. A token with +/// no usable verified client fails the client check, and a grant bound to +/// another client or resource fails its binding. +fn grant_context_check(error: GrantContextError) -> FailedCheck { + match error { + GrantContextError::MissingVerifiedClient | GrantContextError::InvalidVerifiedClient => { + FailedCheck::TokenClient + } + GrantContextError::ClientMismatch | GrantContextError::ResourceMismatch => { + FailedCheck::TaskGrantBinding + } + _ => FailedCheck::TaskGrantClaims, + } +} + /// The 401 for a missing or refused credential. The answer is the same for /// every check, so a caller learns nothing about which one failed. pub(crate) fn authentication_refused(check: FailedCheck) -> Response { @@ -1019,6 +1037,30 @@ pub(crate) fn authentication_refused(check: FailedCheck) -> Response { mod tests { use super::*; + #[test] + fn a_grant_context_refusal_names_the_check_it_failed() { + for (error, check) in [ + ( + GrantContextError::MissingVerifiedClient, + FailedCheck::TokenClient, + ), + ( + GrantContextError::InvalidVerifiedClient, + FailedCheck::TokenClient, + ), + ( + GrantContextError::ClientMismatch, + FailedCheck::TaskGrantBinding, + ), + ( + GrantContextError::ResourceMismatch, + FailedCheck::TaskGrantBinding, + ), + ] { + assert_eq!(grant_context_check(error), check, "{error:?}"); + } + } + #[test] fn a_bearer_names_the_check_its_header_failed() { let headers = |values: &[&'static str]| { @@ -1107,18 +1149,24 @@ mod tests { /// answer 401 without a check unless it is added to this list on purpose. #[test] fn only_the_noting_constructors_build_a_401() { - fn visit(dir: &std::path::Path, found: &mut Vec) { + fn visit(root: &std::path::Path, dir: &std::path::Path, found: &mut Vec) { for entry in std::fs::read_dir(dir).expect("source directory is readable") { let path = entry.expect("directory entry is readable").path(); if path.is_dir() { - visit(&path, found); + visit(root, &path, found); continue; } - let name = path.to_string_lossy().into_owned(); + // Judge the path below `src`, so where the checkout lives + // cannot exclude the files. + let name = path + .strip_prefix(root) + .expect("the file is below the source directory") + .to_string_lossy() + .into_owned(); if !name.ends_with(".rs") || name.contains("tests") - || name.ends_with("/problem.rs") - || name.ends_with("/compiler.rs") + || name == "problem.rs" + || name == "compiler.rs" { continue; } @@ -1141,10 +1189,8 @@ mod tests { } } let mut found = Vec::new(); - visit( - &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), - &mut found, - ); + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + visit(&root, &root, &mut found); found.sort(); assert_eq!( found, diff --git a/crates/registry-breg/src/correlation.rs b/crates/registry-breg/src/correlation.rs index 5415a5dffd..c0da04c7ba 100644 --- a/crates/registry-breg/src/correlation.rs +++ b/crates/registry-breg/src/correlation.rs @@ -9,7 +9,9 @@ use axum::http::header::{CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE}; use axum::http::{HeaderMap, Request, StatusCode}; use axum::middleware::Next; use axum::response::Response; -use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote}; +use std::sync::{Arc, Mutex, PoisonError}; + +use registry_platform_authcommon::{record_refusal, DeclaredScope, FailedCheck, RefusalNote}; use registry_platform_httpsec::{Problem, ProblemBody, TraceContext, TraceId}; use serde_json::Value; use uuid::Uuid; @@ -23,14 +25,46 @@ use uuid::Uuid; pub struct RequestCorrelation { request_id: Uuid, trace: TraceContext, + declared_scope: DeclaredScopeSlot, +} + +/// The operator-declared values of the scope check a request failed. A scope +/// refusal fills it, the recording layer reads it, and nothing in it is +/// written to the response. Every clone of one request's correlation shares +/// the slot. +#[derive(Clone, Debug, Default)] +pub(crate) struct DeclaredScopeSlot(Arc>>); + +impl DeclaredScopeSlot { + pub(crate) fn set(&self, declared: DeclaredScope) { + *self.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(declared); + } + + fn get(&self) -> Option { + self.0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } +} + +// The slot is bookkeeping for the recording layer, not part of a +// correlation's identity. +impl PartialEq for DeclaredScopeSlot { + fn eq(&self, _: &Self) -> bool { + true + } } +impl Eq for DeclaredScopeSlot {} + impl RequestCorrelation { #[must_use] pub fn from_headers(headers: &HeaderMap) -> Self { Self { request_id: Uuid::new_v4(), trace: TraceContext::from_headers(headers), + declared_scope: DeclaredScopeSlot::default(), } } @@ -39,6 +73,7 @@ impl RequestCorrelation { Self { request_id: Uuid::new_v4(), trace: TraceContext::server_created(), + declared_scope: DeclaredScopeSlot::default(), } } @@ -52,6 +87,10 @@ impl RequestCorrelation { &self.trace.trace_id } + pub(crate) fn declared_scope_slot(&self) -> DeclaredScopeSlot { + self.declared_scope.clone() + } + fn apply_trace(&self, headers: &mut HeaderMap) { self.trace.apply(headers); } @@ -445,6 +484,17 @@ pub(crate) fn finish_response( ); } correlation.apply_trace(response.headers_mut()); + if let Some(problem) = &problem { + if matches!(problem.status.as_u16(), 401 | 403) + && response.extensions().get::().is_none() + { + debug_assert!(false, "a refusal was answered without its failed check"); + tracing::error!( + code = problem.code, + "a refusal was answered without its failed check" + ); + } + } record_noted_refusal(&response, correlation); let status = status_class(response.status()); @@ -467,10 +517,12 @@ pub(crate) fn finish_response( /// folded answer is not itself a refusal. pub(crate) fn record_noted_refusal(response: &Response, correlation: &RequestCorrelation) { if let Some(note) = response.extensions().get::().copied() { + let declared = correlation.declared_scope.get(); record_refusal!( crate::metrics::process_refusal_recorder(), note, - trace_id = correlation.trace_id() + trace_id = correlation.trace_id(), + declared = declared.as_ref() ); } } @@ -500,3 +552,58 @@ pub(crate) fn status_class(status: StatusCode) -> &'static str { fn duration_milliseconds(elapsed: std::time::Duration) -> u64 { u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX) } + +#[cfg(test)] +mod refusal_guard_tests { + use super::*; + + fn refusal_statuses() -> [StatusCode; 2] { + [ + StatusCode::from_u16(401).expect("401 is a status"), + StatusCode::FORBIDDEN, + ] + } + + fn finish(response: Response) -> Response { + let correlation = RequestCorrelation::from_headers(&HeaderMap::new()); + finish_response(response, &correlation, "GET", Instant::now()) + } + + #[test] + fn a_401_or_403_with_its_check_is_answered_unchanged() { + for status in refusal_statuses() { + let response = note_refusal( + problem_response(status, "Refused", "Refused.", "authentication.refused"), + FailedCheck::CredentialMissing, + ); + assert_eq!(finish(response).status(), status); + } + } + + #[cfg(debug_assertions)] + #[test] + fn a_401_or_403_without_a_check_stops_a_debug_build() { + for status in refusal_statuses() { + let outcome = std::panic::catch_unwind(|| { + finish(problem_response( + status, + "Refused", + "Refused.", + "authentication.refused", + )) + }); + assert!(outcome.is_err(), "{status} was answered without a check"); + } + } + + #[test] + fn a_404_without_a_check_is_an_unknown_route() { + let response = finish(problem_response( + StatusCode::NOT_FOUND, + "Not Found", + "The requested resource was not found.", + "resource.not_found", + )); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + } +} diff --git a/crates/registry-breg/tests/authentication_refusals.rs b/crates/registry-breg/tests/authentication_refusals.rs index 318323b357..653a850519 100644 --- a/crates/registry-breg/tests/authentication_refusals.rs +++ b/crates/registry-breg/tests/authentication_refusals.rs @@ -972,10 +972,23 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir u64::try_from(corpus.len()).expect("corpus length fits"), "each malformed token counts once" ); - let log_text = captured - .events() + // The line budget is shared with the cases above, so the corpus writes + // exactly the lines they left: none once they have spent it. The log is + // still searched, because anything else the corpus logged must be value-free. + let spent = observed .iter() - .map(Value::to_string) - .collect::(); + .filter(|case| case.expected_check == "credential-malformed") + .count(); + let events = captured.events(); + let refusal_lines = events + .iter() + .filter(|event| event["fields"]["message"] == "request refused") + .count(); + assert_eq!( + refusal_lines, + (registry_platform_authcommon::REFUSAL_LOG_LINES_PER_WINDOW as usize).saturating_sub(spent), + "the corpus writes the refusal lines the budget admits" + ); + let log_text = events.iter().map(Value::to_string).collect::(); assert!(!log_text.contains("canary"), "the corpus reached the log"); } diff --git a/crates/registry-breg/tests/concealment_refusals.rs b/crates/registry-breg/tests/concealment_refusals.rs index b6d05e7a17..fc25e9cb53 100644 --- a/crates/registry-breg/tests/concealment_refusals.rs +++ b/crates/registry-breg/tests/concealment_refusals.rs @@ -467,7 +467,16 @@ async fn every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wir ( "missing-scope", "scope", - read_request(&record, Some(&token(without(service_claims(), "scope")))), + // The token carries another scope, so the line can be seen to name + // the declared one and not the presented one. + read_request( + &record, + Some(&token(with( + service_claims(), + "scope", + json!("token-held-canary-scope"), + ))), + ), ), ( "purpose-not-declared", @@ -608,15 +617,23 @@ async fn every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wir assert_eq!(fields["failed_check"], case.expected_check, "{}", case.name); assert_eq!(fields["suppressed"], 0, "{}", case.name); let keys: BTreeSet<&str> = fields.keys().map(String::as_str).collect(); + let mut expected = BTreeSet::from([ + "decision", + "failed_check", + "message", + "suppressed", + "trace_id", + ]); + if case.expected_check == "scope" { + // A scope refusal also names what the operator declared: the scope + // claim, the scope the profile needs and the profile. + expected.extend(["scope_claim", "required_scope", "access_profile"]); + assert_eq!(fields["scope_claim"], "scope", "{}", case.name); + assert_eq!(fields["required_scope"], "registry.read", "{}", case.name); + assert_eq!(fields["access_profile"], "reader", "{}", case.name); + } assert_eq!( - keys, - BTreeSet::from([ - "decision", - "failed_check", - "message", - "suppressed", - "trace_id" - ]), + keys, expected, "{}: the line carries only the fixed fields", case.name ); @@ -624,6 +641,7 @@ async fn every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wir PRINCIPAL, "agent-client", "other-client", + "token-held-canary-scope", "nobody", "not-a-uuid", "https://other.example", diff --git a/crates/registry-casework/src/auth.rs b/crates/registry-casework/src/auth.rs index 76f44f7b14..d020845d44 100644 --- a/crates/registry-casework/src/auth.rs +++ b/crates/registry-casework/src/auth.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use registry_casework_core::{ AccessProfile, ActorContext, CaseworkActsAs, CaseworkProject, IssuerPrincipal, }; -use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; +use registry_platform_authcommon::{validate_compact_access_token, DeclaredScope, FailedCheck}; use registry_platform_oidc::{JwksFetcher, TokenVerifier, TokenVerifierConfig}; use serde_json::Value; use thiserror::Error; @@ -25,9 +25,34 @@ pub struct CaseworkAuthenticator { initiator_profiles: BTreeSet, human_identity: HumanIdentityConfig, delegated_staff_readers: BTreeMap, + /// The claim the deployment configured to carry scopes. A scope refusal + /// names it to the operator. + scope_claim: String, +} + +tokio::task_local! { + /// The operator-declared values of the scope check the current request + /// failed. The HTTP edge scopes it around each request and attaches it to + /// the refusal answer's extensions, which are never written to the wire. + pub(crate) static DECLARED_SCOPE: std::cell::RefCell>; } impl CaseworkAuthenticator { + /// Record, for the operator's refusal line, the scope the operation needs + /// and the access profile that was applied. Both are declared by the + /// configuration or the package, never read from the token. + fn declare_scope_refusal(&self, required_scope: Option<&str>, access_profile: Option<&str>) { + let mut declared = DeclaredScope::new(&self.scope_claim); + if let Some(scope) = required_scope { + declared = declared.with_required_scope(scope); + } + if let Some(profile) = access_profile { + declared = declared.with_access_profile(profile); + } + // Outside an HTTP request there is no line to carry it. + let _ = DECLARED_SCOPE.try_with(|slot| *slot.borrow_mut() = Some(declared)); + } + /// Constructs an authenticator from a project already validated by /// [`CaseworkProject::load`] or [`CaseworkProject::check`]. #[must_use] @@ -39,6 +64,7 @@ impl CaseworkAuthenticator { ) -> Self { let audience = verifier.audiences.first().cloned().unwrap_or_default(); Self { + scope_claim: verifier.scope_claim.clone(), source_verifier_config: verifier.clone(), source_keys: Arc::clone(&keys), source_verifiers: BTreeMap::new(), @@ -187,6 +213,7 @@ impl CaseworkAuthenticator { return Err(AuthenticationError::Refused(FailedCheck::Delegation)); } if !verified.scopes.iter().any(|value| value == scope) { + self.declare_scope_refusal(Some(scope), None); return Err(AuthenticationError::Refused(FailedCheck::Scope)); } if verified.matched_client_id().ok().flatten().is_none() { @@ -239,6 +266,9 @@ impl CaseworkAuthenticator { .iter() .any(|scope| scope == &reader.required_scope) { + // The delegated read scope is refused here because it belongs to the + // delegated path, so the line names no scope as required. + self.declare_scope_refusal(None, None); return Err(AuthenticationError::Refused(FailedCheck::Scope)); } } @@ -267,6 +297,14 @@ impl CaseworkAuthenticator { .iter() .all(|scope| actual_scopes.contains(scope.as_str())) { + self.declare_scope_refusal( + profile + .required_scopes + .iter() + .map(String::as_str) + .find(|scope| !actual_scopes.contains(scope)), + Some(&profile.id), + ); return Err(AuthenticationError::Profile(FailedCheck::Scope)); } if requires_person { diff --git a/crates/registry-casework/src/auth/delegated.rs b/crates/registry-casework/src/auth/delegated.rs index 98cf012561..1f1fba6d1a 100644 --- a/crates/registry-casework/src/auth/delegated.rs +++ b/crates/registry-casework/src/auth/delegated.rs @@ -271,6 +271,13 @@ impl CaseworkAuthenticator { if !expected_scopes.is_subset(&actual_scopes) || actual_scopes.len() != verified.scopes.len() { + self.declare_scope_refusal( + expected_scopes + .difference(&actual_scopes) + .next() + .map(String::as_str), + Some(&profile.id), + ); return Err(AuthenticationError::Profile(FailedCheck::Scope)); } if verified diff --git a/crates/registry-casework/src/http.rs b/crates/registry-casework/src/http.rs index a6189d2f84..8a7f019095 100644 --- a/crates/registry-casework/src/http.rs +++ b/crates/registry-casework/src/http.rs @@ -1,6 +1,7 @@ use registry_casework_core::DirectoryTeamUpdateRequest; use std::sync::Arc; +use crate::auth::DECLARED_SCOPE; use axum::body::Bytes; use axum::extract::{FromRequest, Path, Query, Request, State}; use axum::http::header::{ @@ -13,7 +14,8 @@ use axum::routing::{get, post}; use axum::{Json, Router}; use registry_casework_core::*; use registry_platform_authcommon::{ - parse_bearer_token, record_refusal, BearerParseError, FailedCheck, RefusalNote, RefusalRecorder, + parse_bearer_token, record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, + RefusalRecorder, }; use registry_platform_httpsec::{ normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, @@ -288,9 +290,12 @@ async fn record_refusals( ) -> Response { let response = next.run(request).await; if let Some(note) = response.extensions().get::().copied() { + let declared = response.extensions().get::(); match REQUEST_TRACE.try_with(|trace| trace.trace_id.clone()) { - Ok(trace_id) => record_refusal!(recorder, note, trace_id = &trace_id), - Err(_) => record_refusal!(recorder, note), + Ok(trace_id) => { + record_refusal!(recorder, note, trace_id = &trace_id, declared = declared) + } + Err(_) => record_refusal!(recorder, note, declared = declared), } } response @@ -306,10 +311,14 @@ async fn http_boundary( .scope(trace.clone(), async move { REQUEST_CONTRACT .scope(contract, async move { - normalize_framework_rejection( - next.run(request).await, - framework_rejection_problem, - ) + DECLARED_SCOPE + .scope(std::cell::RefCell::new(None), async move { + normalize_framework_rejection( + next.run(request).await, + framework_rejection_problem, + ) + }) + .await }) .await }) @@ -1958,18 +1967,60 @@ impl IntoResponse for HttpError { None => note, } }); - let mut response = problem_response(self.problem(), None, validation); - if let Some(note) = note { - response.extensions_mut().insert(note); + match note { + Some(note) => { + let mut response = refusal_response(self.problem(), note, validation); + let declared = DECLARED_SCOPE + .try_with(|slot| slot.borrow().clone()) + .ok() + .flatten(); + if let Some(declared) = declared.filter(|_| note.check == FailedCheck::Scope) { + response.extensions_mut().insert(declared); + } + response + } + None => problem_response(self.problem(), None, validation), } - response } } +/// A refusal of authority, with the check it failed. The note reaches the +/// operator's counter and log line through the response extensions and never +/// the caller's body. +fn refusal_response( + problem: ProblemCode, + note: RefusalNote, + validation: Option<&ReviewValidationError>, +) -> Response { + let mut response = build_problem_response(problem, validation); + response.extensions_mut().insert(note); + response +} + +/// An answer that is not a refusal of authority. A 401 or 403 is built with +/// [`refusal_response`] so it names its check. One arriving here is a defect: +/// it is answered unchanged and logged once, and a debug build stops. fn problem_response( problem: ProblemCode, _attempt_reference: Option, validation: Option<&ReviewValidationError>, +) -> Response { + if matches!( + problem.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + code = problem.code(), + "a refusal was answered without its failed check" + ); + } + build_problem_response(problem, validation) +} + +fn build_problem_response( + problem: ProblemCode, + validation: Option<&ReviewValidationError>, ) -> Response { let trace = REQUEST_TRACE .try_with(Clone::clone) @@ -3048,6 +3099,46 @@ mod tests { } } + /// Every code answered as a 401 or 403 is built with its check. The list + /// comes from the code catalogue, so a code added later is covered. + #[test] + fn every_refusal_code_is_built_with_its_check() { + let refusals: Vec = ProblemCode::ALL + .iter() + .copied() + .filter(|code| { + matches!( + code.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) + }) + .collect(); + assert!(refusals.len() >= 4, "the catalogue lists its refusals"); + for code in refusals { + let response = refusal_response(code, RefusalNote::new(FailedCheck::Operation), None); + assert_eq!(response.status(), code.status()); + assert!(response.extensions().get::().is_some()); + } + } + + #[cfg(debug_assertions)] + #[test] + fn a_refusal_built_without_its_check_stops_a_debug_build() { + for code in ProblemCode::ALL.iter().copied().filter(|code| { + matches!( + code.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) + }) { + let outcome = std::panic::catch_unwind(|| problem_response(code, None, None)); + assert!( + outcome.is_err(), + "{} was built without a check", + code.code() + ); + } + } + #[tokio::test] async fn a_refusal_logs_one_value_free_line_with_its_check_remedy_and_trace() { use registry_platform_testing::CapturedDiagnosticLogs; diff --git a/crates/registry-casework/tests/refusal_golden.rs b/crates/registry-casework/tests/refusal_golden.rs index 8745163037..4d6423b7f8 100644 --- a/crates/registry-casework/tests/refusal_golden.rs +++ b/crates/registry-casework/tests/refusal_golden.rs @@ -72,6 +72,10 @@ fn case( } } +/// The scope a token holds in the cases that refuse on scope. It is the +/// caller's value, so no log line may carry it. +const HELD_CANARY_SCOPE: &str = "casework:unrelated"; + fn bearer(token: &str) -> String { format!("Bearer {token}") } @@ -582,6 +586,21 @@ fn assert_one_value_free_line(case: &Case, logs: &CapturedDiagnosticLogs, tokens "{}", case.name ); + if case.check == "scope" { + // A scope refusal names what the operator declared, never the scopes + // the token held. + assert_eq!(fields["scope_claim"], "scope", "{}", case.name); + assert!( + fields["required_scope"].is_string(), + "{}: the line names the scope the operation needs", + case.name + ); + assert!(!text.contains(HELD_CANARY_SCOPE), "{}: {text}", case.name); + if case.name == "scope-missing" { + assert_eq!(fields["required_scope"], "casework:staff", "{}", case.name); + assert_eq!(fields["access_profile"], "staff", "{}", case.name); + } + } for name in fields.keys() { assert!( [ @@ -590,14 +609,23 @@ fn assert_one_value_free_line(case: &Case, logs: &CapturedDiagnosticLogs, tokens "failed_check", "suppressed", "trace_id", - "remedy" + "remedy", + "scope_claim", + "required_scope", + "access_profile" ] .contains(&name.as_str()), "{}: unexpected field {name}", case.name ); } + // The profile id the operator declared is also a header value the caller + // sent, so the line may name it. Nothing else the caller sent may appear. + let declared_profile = fields.get("access_profile").and_then(Value::as_str); for secret in tokens.iter().chain([&PRINCIPAL.to_owned()]) { + if Some(secret.as_str()) == declared_profile { + continue; + } assert!(!text.contains(secret.as_str()), "{}: {secret}", case.name); } } diff --git a/docs/site/src/content/docs/operate/breg-monitor.mdx b/docs/site/src/content/docs/operate/breg-monitor.mdx index 4b2b93b930..538f2d1f1c 100644 --- a/docs/site/src/content/docs/operate/breg-monitor.mdx +++ b/docs/site/src/content/docs/operate/breg-monitor.mdx @@ -348,8 +348,7 @@ key source and a refused review completion callback all count. So does a request `404 resource.not_found` because the caller may not see the target (a missing scope or purpose, a row outside the caller's boundary, a refused task grant, a field beyond the profile), and a write refused as outside the caller's boundary. A batch of Proposal review contexts answers `200`, and -each concealed item counts once under its own check. A generic `412` precondition answer, which also -covers a stale version, and a request for an unknown route are not counted. +each concealed item counts once under its own check. A `412` for a stale version and a request for an unknown route are not counted. A failed field guard counts under `action-guard`, also when it answers the generic `412`. Each refusal also writes one `request refused` line at `INFO` level with `failed_check` and the request's trace id, at most five lines per check per minute across the process. At `BREG_LOG=warn` @@ -465,7 +464,7 @@ Find the code the command, log, or HTTP problem printed. A `*` stands for any pa | `apply.successor.roles-differ` | The file names other roles than the active activation. | Apply the active package under the new roles, then the successor. | | `startup.audit.refused` | The audit destination or hash key was refused. | Secret files are regular, owned by the running user, mode `0400` or `0600`, with one link. The audit directory and its files are owned by the running user, the directory `0700`. | | `startup.cursor.refused` | The cursor secret was refused. | As above. | -| `startup.oidc.refused` | The issuer's key set could not be loaded, or a pinned static key set was refused. | Check that this host reaches and trusts the issuer. For a pinned key set, the message names the rule and the key's position: correct that key. | +| `startup.oidc.refused` | The issuer's key set could not be loaded, or a pinned static key set was refused. | Check that this host reaches and trusts the issuer. For a pinned key set refused by the shared key rules, the message names the rule and, for a rule about one key, its position: correct that key. A key set refused by BReg's own rules (`use`, `key_ops`, a denied `kid`, the algorithm, or the number of keys) gets the general OIDC message: check those members. | | `authentication.refused` | A token was refused. | Check [what a token must carry](../breg/#what-a-token-must-carry); `aud` may be a list of up to 16 that includes the audience. | | `breg.runtime.invalid-metrics-listener` | `metricsListener.bind` is invalid. | See [Scrape metrics](#scrape-metrics). | | `postgres.connections.pool-over-half` | One pool may take over half the connections. | Lower the pool or raise `max_connections`. | diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 879725f16a..2c841dfc9c 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -167,8 +167,10 @@ A request that BReg answers `404 resource.not_found` because the caller may not The operator can tell the reasons apart: the counter holds the request under the rule that refused it, for example `scope`, `purpose`, `requester-client`, `row-boundary`, `task-grant-binding`, `disclosure` or `visibility`. A refused write the engine answers with `write.outside-boundary` counts under `row-boundary`, and a Proposal outside the caller's scope counts under `ownership`. A batch of Proposal review contexts answers `200`, and each concealed item counts once under its own check. -A generic `412` precondition answer, which also covers a stale version, and a request for an unknown route are not counted. -Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and recording a refusal changes nothing the caller receives. +A `412` for a stale version and a request for an unknown route are not counted. +A failed field guard counts under `action-guard`, also when it answers the generic `412`. +A refusal on the `scope` check also names the claim that carries scopes, the scope the operation needs and the access profile, each as the configuration or package declares it. +Neither the counter nor the line holds a token, claim, client, subject, scope or identifier from the request, and recording a refusal changes nothing the caller receives. A `visibility` count is a record that is absent or outside the boundary, and BReg does not say which, so it also counts a caller probing for identifiers. The audit journal's `refusalReason` stays the three values it lists below. @@ -512,7 +514,7 @@ The residuals refer to these obligations by number. Loopback HTTP is accepted for an issuer; anything else needs `authentication.oidc.allowInsecureHttp: true`, which is logged at startup and reported by `bregctl doctor` (`BREG-RES-17`). - For an issuer and for `listener.publicOrigin`, loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name `localhost` in any letter case, which BReg connects to only through the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. + For an issuer and for `listener.publicOrigin`, loopback means an address in `127.0.0.0/8`, `::1` or an IPv4-mapped form of a `127.0.0.0/8` address, or the name `localhost` in any letter case. BReg connects to an issuer named `localhost` only through the loopback addresses it resolved. `a.localhost` and `localhost.` are ordinary named hosts. A pinned key set (`authentication.oidc.jwksSource.type: static`) holds public keys only. BReg refuses a key that carries a private or symmetric member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth`, `k`), a repeated member name, a missing or repeated `kid`, or a key that does not match diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index 4694e1fc94..caf1958168 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -181,11 +181,13 @@ grants in [Registry Casework task grants](../../reference/casework-task-grants/) Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. - Neither the counter nor the line holds a token, claim, client, subject, scope or identifier, and - recording a refusal changes nothing the caller receives: the answer is the same + A refusal on the `scope` check also names the claim that carries scopes, the scope the operation + needs and the access profile, each as the configuration or package declares it. + Neither the counter nor the line holds a token, claim, client, subject, scope or identifier from + the request, and recording a refusal changes nothing the caller receives: the answer is the same `operation.not-authorized`, `request.not-found`, `review.distinct-approver-required` or `review.initiator-excluded` body as before. - {/* Evidence: crates/registry-casework/src/http.rs, impl From for HttpError; + {/* Evidence: crates/registry-casework/src/http.rs, the ReviewRuntimeError conversion into HttpError; crates/registry-casework/src/review.rs, a_reviewer_who_already_acted_is_refused_for_separation_of_duties, only_staff_and_supervisors_pass_the_human_reviewer_check; diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index df6533b78f..ea53571bcd 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -30,8 +30,13 @@ task grant counts under `task-grant-expired`, a grant bound to another client or resource under `task-grant-binding`, and a grant token with no `iat`, an `iat` ahead of the clock or an `exp` not after `iat` under - `task-grant-claims`. A generic `412` precondition answer and an unknown route - are not counted. Refusal statuses, headers and bodies are unchanged. + `task-grant-claims`. A `412` for a stale version and an unknown route are not + counted. A failed field guard counts under `action-guard`, also when it + answers the generic `412`. A refusal on the `scope` check also names the + claim that carries scopes, the scope the operation needs and the access + profile, each as the configuration or package declares it. The line never + names a scope the token held. Refusal statuses, headers and bodies are + unchanged. - The BReg MCP gateway and the review page read loopback the way every other service does. Under `development-loopback`, plain HTTP to the diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index c9b59a4907..d677eb7b5f 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -12,6 +12,11 @@ nothing, such as the task grant key set route when task grants are not configured, is not counted. Refusal statuses, headers and bodies are unchanged. +- A refusal on the `scope` check also names, in its `request refused` line, + the claim that carries scopes, the scope the operation needs and the access + profile, each as the configuration or package declares it. The line never + names a scope the token held. Refusal statuses, headers and bodies are + unchanged. - A static key set with a private key member is refused at startup under `casework.runtime.unreadable-jwks-secret`, with the rule it broke and the key's position. Earlier releases loaded such a set, so remove private From 6f68c2929a82d7d6749c679003b8889c8f3b5d65 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:47:46 +0100 Subject: [PATCH 059/136] fix: name declared scope on Messaging refusals and hold tooling issuers to loopback literals A Messaging refusal on the scope check names, in its request refused line, the scope claim the deployment reads, the scope the access profile requires and the profile id, all from configuration and the reviewed package. The answer is unchanged. The development identity issuer and local app origin in the ThunderID tooling accept loopback address literals only, and an exchange issuer that names the development listener in any loopback spelling is refused. The journey scripts read the failed check alone to place a refusal, and the token page describes the request refused line. Signed-off-by: Jeremi Joslin --- crates/registry-adapter/src/serve.rs | 4 +- .../postgres_journal_retention_served.rs | 6 +- crates/registry-messaging/src/auth.rs | 60 +++++++++--- crates/registry-messaging/src/http.rs | 95 ++++++++++++++++--- .../src/diagnostic_capture.rs | 23 ----- .../src/description.rs | 65 +++++++++++-- .../src/identity_facts.rs | 6 +- .../src/identity_facts_tests.rs | 4 +- .../configure/request-an-access-token.mdx | 11 +-- products/messaging/CHANGELOG.md | 4 + .../contracts/security-invariant-matrix.yaml | 9 +- products/platform/CHANGELOG.md | 10 +- products/platform/journeys/README.md | 12 +-- .../platform/journeys/expected-failures.yaml | 4 +- products/platform/journeys/own-provider.sh | 24 ++--- products/platform/journeys/promote.sh | 20 ++-- products/platform/journeys/rstack-dev.sh | 2 +- .../platform/journeys/test_journey_tables.py | 12 ++- 18 files changed, 254 insertions(+), 117 deletions(-) diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 91c4f829b2..527537549f 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -820,8 +820,8 @@ async fn lacking( /// because they would inherit it: the privilege check that follows then /// decides, as it does for a hand-granted deployment. A member that holds /// ADMIN OPTION on the role and has no members of its own does not count. It -/// already controls the role, as the role that created it does when -/// `adapterctl provision` runs. PostgreSQL ignores or refuses a GRANT the +/// already controls the role, as the role that created it does in the layout +/// the shared provisioning plan builds. PostgreSQL ignores or refuses a GRANT the /// migration role has no right to make, so each privilege is checked again /// before the commit, and a shortfall rolls everything back. /// diff --git a/crates/registry-adapter/tests/postgres_journal_retention_served.rs b/crates/registry-adapter/tests/postgres_journal_retention_served.rs index f1bfe2eeeb..f3c6a9f165 100644 --- a/crates/registry-adapter/tests/postgres_journal_retention_served.rs +++ b/crates/registry-adapter/tests/postgres_journal_retention_served.rs @@ -650,7 +650,7 @@ async fn a_runtime_role_with_members_is_granted_nothing_and_refused() { } /// The role that created the runtime role administers it, as in a database -/// built by `adapterctl provision`, so its membership does not stop the grant. +/// built by the shared provisioning plan, so its membership does not stop the grant. #[tokio::test] async fn a_runtime_role_whose_only_member_administers_it_is_granted_its_privileges() { let upstream = UpstreamDouble::start(); @@ -679,7 +679,7 @@ async fn a_runtime_role_whose_only_member_administers_it_is_granted_its_privileg drop_role(&database, &role).await; } -/// Create the runtime role the way `adapterctl provision` does: a +/// Create the runtime role the way the shared provisioning plan does: a /// `LOGIN CREATEROLE` administrator creates it with `createrole_self_grant` /// set to `set,inherit`. PostgreSQL then records two membership rows for the /// administrator in the runtime role, one that carries ADMIN OPTION and one @@ -718,7 +718,7 @@ async fn create_provisioned_runtime_role(database: &str, runtime: &str, administ ); } -/// The layout `adapterctl provision` builds, with the CREATEROLE administrator +/// The layout the shared provisioning plan builds, with the CREATEROLE administrator /// as the runtime role's only member, still receives its grants. Pinned on /// the two-row layout: a per-row test of ADMIN OPTION would count the /// administrator's plain row and refuse every provisioned database. diff --git a/crates/registry-messaging/src/auth.rs b/crates/registry-messaging/src/auth.rs index 120d26d232..36c7d45598 100644 --- a/crates/registry-messaging/src/auth.rs +++ b/crates/registry-messaging/src/auth.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use registry_messaging_core::{ AccessProfiles, AccessRefusal, ActorKind, ActorKindClaim, Caller, VerifiedTokenFacts, }; -use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; +use registry_platform_authcommon::{validate_compact_access_token, DeclaredScope, FailedCheck}; use registry_platform_oidc::{ actor_kind, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, @@ -29,6 +29,8 @@ pub struct MessagingAuthenticator { verifier: TokenVerifier, claim_names: ClaimNames, profiles: AccessProfiles, + /// The claim the deployment reads scopes from, as configured. + scope_claim: String, /// Whether the deployment declared any assertion authority at all. binds_assertion_issuers: bool, } @@ -46,6 +48,7 @@ impl MessagingAuthenticator { .validate() .expect("the default contextual claim names are valid"); Self { + scope_claim: verifier.scope_claim.clone(), verifier: TokenVerifier::new(verifier, keys), claim_names, profiles, @@ -55,6 +58,16 @@ impl MessagingAuthenticator { /// Verify one credential and resolve it to exactly one access profile. pub async fn authenticate(&self, token: &str) -> Result { + self.authenticate_declaring(token) + .await + .map_err(|refusal| refusal.error) + } + + /// As [`Self::authenticate`], and a scope refusal also carries what the + /// deployment declared about it: the scope claim name, the scope the + /// profile requires, and the profile's id. None of it comes from the + /// token. + pub async fn authenticate_declaring(&self, token: &str) -> Result { validate_compact_access_token(token) .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; let verified = self @@ -70,9 +83,7 @@ impl MessagingAuthenticator { if !self.binds_assertion_issuers && verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - return Err(AuthenticationError::Profile( - FailedCheck::TokenAssertionIssuer, - )); + return Err(AuthenticationError::Profile(FailedCheck::TokenAssertionIssuer).into()); } let client_id = verified .matched_client_id() @@ -91,17 +102,26 @@ impl MessagingAuthenticator { } /// The error a refused profile resolution answers with, and the check it - /// names. + /// names. A scope refusal also carries the values configuration declared + /// for it. fn access_refusal( &self, refusal: AccessRefusal, facts: &VerifiedTokenFacts<'_>, - ) -> AuthenticationError { + ) -> DeclaredRefusal { match refusal { AccessRefusal::Profile => { - let check = if self.profiles.missing_scope(facts).is_some() { - FailedCheck::Scope - } else if self.profiles.iter().any(|profile| { + if let Some(missing) = self.profiles.missing_scope(facts) { + return DeclaredRefusal { + error: AuthenticationError::Profile(FailedCheck::Scope), + declared: Some( + DeclaredScope::new(&self.scope_claim) + .with_required_scope(missing.scope) + .with_access_profile(missing.profile), + ), + }; + } + let check = if self.profiles.iter().any(|profile| { facts.client_id.is_some_and(|client| { profile .requester_clients @@ -113,7 +133,7 @@ impl MessagingAuthenticator { } else { FailedCheck::AccessProfile }; - AuthenticationError::Profile(check) + AuthenticationError::Profile(check).into() } AccessRefusal::Claims => AuthenticationError::Claims( if matches!(facts.actor_kind, ActorKindClaim::Malformed) { @@ -121,7 +141,8 @@ impl MessagingAuthenticator { } else { FailedCheck::TokenClaims }, - ), + ) + .into(), } } } @@ -136,6 +157,23 @@ impl std::fmt::Debug for MessagingAuthenticator { } } +/// A refusal of authentication with the values the deployment declared about +/// it, when it is a scope refusal. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DeclaredRefusal { + pub error: AuthenticationError, + pub declared: Option, +} + +impl From for DeclaredRefusal { + fn from(error: AuthenticationError) -> Self { + Self { + error, + declared: None, + } + } +} + #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] diff --git a/crates/registry-messaging/src/http.rs b/crates/registry-messaging/src/http.rs index 916a8a87e5..4a32be83c5 100644 --- a/crates/registry-messaging/src/http.rs +++ b/crates/registry-messaging/src/http.rs @@ -51,7 +51,7 @@ use registry_messaging_core::{ PROVIDER_CALLBACK_TOKEN_PATH, READY_PATH, TEMPLATE_PREVIEW_PATH, }; use registry_platform_authcommon::{ - parse_bearer_token, record_refusal, BearerParseError, FailedCheck, RefusalNote, + parse_bearer_token, record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, }; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httpsec::{ @@ -954,12 +954,12 @@ impl PreviewRecord { async fn authenticate(state: &HttpState, headers: &HeaderMap) -> Result { let result = match bearer_token(headers) { - Ok(token) => state.authenticator.authenticate(token).await, - Err(check) => Err(AuthenticationError::Refused(check)), + Ok(token) => state.authenticator.authenticate_declaring(token).await, + Err(check) => Err(AuthenticationError::Refused(check).into()), }; - result.map_err(|error| { - state.metrics.record_authentication_refusal(error); - authentication_problem(error) + result.map_err(|refusal| { + state.metrics.record_authentication_refusal(refusal.error); + authentication_problem(refusal.error).with_declared(refusal.declared) }) } @@ -1003,6 +1003,9 @@ fn authentication_problem(error: AuthenticationError) -> HttpError { pub struct HttpError { problem: ProblemCode, check: Option, + /// What the deployment declared about a scope refusal. It rides with the + /// check to the recording layer and is never written to the response. + declared: Option, } impl HttpError { @@ -1012,9 +1015,16 @@ impl HttpError { Self { problem, check: Some(check), + declared: None, } } + /// Attach the values a scope refusal's log line may name. + #[must_use] + pub(crate) fn with_declared(self, declared: Option) -> Self { + Self { declared, ..self } + } + /// An answer whose check follows from its problem code alone: the /// problems the service answers once a caller is resolved. /// [`attribution`] sorts every problem code, so a code added to the @@ -1028,7 +1038,11 @@ impl HttpError { None } }; - Self { problem, check } + Self { + problem, + check, + declared: None, + } } /// The problem this answer carries. @@ -1112,7 +1126,8 @@ async fn record_refusals( record_refusal!( metrics.refusal_recorder(), note, - trace_id = current_trace().trace_id + trace_id = current_trace().trace_id, + declared = response.extensions().get::() ); } response @@ -1146,7 +1161,11 @@ fn retry_after_seconds(wait: std::time::Duration) -> u64 { impl IntoResponse for HttpError { fn into_response(self) -> Response { - problem_answer(self.problem, self.check) + let mut response = problem_answer(self.problem, self.check); + if let Some(declared) = self.declared { + response.extensions_mut().insert(declared); + } + response } } @@ -3168,6 +3187,49 @@ mod tests { } } + /// A scope refusal's line names the values the deployment declared: the + /// scope claim it reads, the scope the profile requires and the profile. + /// The scope the token carries never reaches the line, and no other + /// refusal writes any of the three. + #[tokio::test] + async fn a_scope_refusal_line_names_the_declared_scope_and_none_of_the_tokens() { + use crate::smtp::tests::Captured; + let message = "/v1/messages/0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; + let canary = "canary:never-logged"; + let mut scoped = sender_claims(); + scoped["registry_scopes"] = json!(canary); + let (first_app, _metrics) = app(); + let captured = Captured::install(); + let response = first_app + .oneshot(request("GET", message, bearer(&token(scoped)), None)) + .await + .unwrap(); + let logs = captured.finish(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(!logs.contains(canary), "{logs}"); + assert!(logs.contains("failed_check=\"scope\""), "{logs}"); + assert!(logs.contains("scope_claim=\"registry_scopes\""), "{logs}"); + assert!(logs.contains("required_scope=\"messaging:send\""), "{logs}"); + assert!(logs.contains("access_profile=\"case-notices\""), "{logs}"); + + let mut unprofiled = sender_claims(); + unprofiled["azp"] = json!(UNPROFILED_CLIENT); + unprofiled["registry_scopes"] = json!(canary); + let (second_app, _metrics) = app(); + let captured = Captured::install(); + let response = second_app + .oneshot(request("GET", message, bearer(&token(unprofiled)), None)) + .await + .unwrap(); + let logs = captured.finish(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(logs.contains("failed_check=\"access-profile\""), "{logs}"); + for name in ["scope_claim", "required_scope", "access_profile="] { + assert!(!logs.contains(name), "{name}: {logs}"); + } + assert!(!logs.contains(canary), "{logs}"); + } + #[tokio::test] async fn a_key_endpoint_outage_counts_under_the_key_source() { use crate::smtp::tests::Captured; @@ -3342,14 +3404,20 @@ mod tests { let logs = captured.finish(); assert!(logs.contains("failed_check=\"scope\""), "{logs}"); assert!(logs.contains("scopeClaim"), "{logs}"); + // The scope refusal names the configured scope claim, scope and + // profile, and nothing the credential or the request carried. + for needle in [ + "scope_claim=\"registry_scopes\"", + "required_scope=\"messaging:send\"", + "access_profile=\"case-notices\"", + ] { + assert!(logs.contains(needle), "logs lack {needle:?}:\n{logs}"); + } for needle in [ credential.as_str(), "messaging:read", "case-system", "registry_actor_kind", - "registry_scopes", - "messaging:send", - "case-notices", "m-1", ] { assert!(!logs.contains(needle), "logs carry {needle:?}:\n{logs}"); @@ -3364,6 +3432,9 @@ mod tests { let logs = captured.finish(); assert!(logs.contains("failed_check=\"actor-kind\""), "{logs}"); assert!(!logs.contains("scopeClaim"), "{logs}"); + for needle in ["scope_claim", "required_scope", "access_profile="] { + assert!(!logs.contains(needle), "logs carry {needle:?}:\n{logs}"); + } } fn sender_claims_with_scope(scope: &str) -> serde_json::Value { diff --git a/crates/registry-platform-testing/src/diagnostic_capture.rs b/crates/registry-platform-testing/src/diagnostic_capture.rs index 8ea00768db..9bfb92863b 100644 --- a/crates/registry-platform-testing/src/diagnostic_capture.rs +++ b/crates/registry-platform-testing/src/diagnostic_capture.rs @@ -54,29 +54,6 @@ impl CapturedDiagnosticLogs { .finish(), ) } - - /// Assert that the capture holds exactly one header-stage diagnostic and - /// that it renders none of the supplied credentials. - /// - /// # Panics - /// - /// Panics when the capture is not one value-free header diagnostic. - pub fn assert_one_value_free_header_diagnostic(&self, tokens: &[String]) { - let rendered = self.text(); - assert_eq!( - rendered.lines().count(), - 1, - "one bounded diagnostic per header stage" - ); - assert!(rendered.contains(r#""stage":"header""#)); - assert!(!rendered.contains("canary")); - for token in tokens.iter().filter(|token| !token.is_empty()) { - assert!( - !rendered.contains(token), - "diagnostics must not contain credentials" - ); - } - } } impl Write for CapturedDiagnosticLogs { diff --git a/crates/registry-thunderid-tooling/src/description.rs b/crates/registry-thunderid-tooling/src/description.rs index ae36e69fde..734555dc4d 100644 --- a/crates/registry-thunderid-tooling/src/description.rs +++ b/crates/registry-thunderid-tooling/src/description.rs @@ -330,12 +330,26 @@ fn development_host(host: &str) -> bool { registry_platform_loopback::loopback_host(host).is_some() || host == "host.docker.internal" } +/// Whether an address names the development issuer's listener: a loopback +/// host in any spelling (a literal, its IPv4-mapped form or the name +/// `localhost`) on the listener's port, with no path or the root path. +fn names_development_listener(address: &str, port: u16) -> bool { + url::Url::parse(address).is_ok_and(|url| { + url.scheme() == "http" + && url + .host_str() + .is_some_and(|host| registry_platform_loopback::loopback_host(host).is_some()) + && url.port() == Some(port) + && matches!(url.path(), "" | "/") + }) +} + fn local_url(value: &str) -> bool { url::Url::parse(value).is_ok_and(|url| { url.scheme() == "http" && url .host_str() - .is_some_and(|host| registry_platform_loopback::loopback_host(host).is_some()) + .is_some_and(|host| registry_platform_loopback::loopback_literal(host).is_some()) && url.port().is_some_and(|port| port != 0) && url.username().is_empty() && url.password().is_none() @@ -633,11 +647,11 @@ impl IssuerDescription { return refuse("exchange issuer and JWKS URLs require HTTPS or an explicit development host"); } } - let own_issuer = match profile { - Profile::Development => format!("http://127.0.0.1:{}", self.port), - Profile::Deployment { issuer } => issuer.to_owned(), + let names_this_issuer = match profile { + Profile::Development => names_development_listener(&issuer.issuer, self.port), + Profile::Deployment { issuer: own } => issuer.issuer == own, }; - if issuer.issuer == own_issuer { + if names_this_issuer { return refuse("an external exchange issuer cannot name this issuer"); } } @@ -977,8 +991,8 @@ mod tests { ("127.0.0.2", true), ("[::1]", true), ("[::ffff:127.0.0.1]", true), - ("localhost", true), - ("LOCALHOST", true), + ("localhost", false), + ("LOCALHOST", false), ("a.localhost", false), ("localhost.", false), ("10.0.0.1", false), @@ -993,6 +1007,43 @@ mod tests { assert!(!local_url("http://127.0.0.1"), "a port is required"); } + #[test] + fn an_exchange_issuer_cannot_name_the_listener_in_any_loopback_spelling() { + let port = crate::testing::synthetic_description().port; + for host in [ + "127.0.0.1", + "127.0.0.2", + "[::1]", + "[::ffff:127.0.0.1]", + "localhost", + "LOCALHOST", + ] { + for path in ["", "/"] { + let mut description = exchange_description(); + description.exchange_issuers[0].issuer = format!("http://{host}:{port}{path}"); + description.exchange_issuers[0].jwks_endpoint = + format!("http://{host}:{port}/jwks"); + assert!( + matches!( + description.validate(), + Err(ToolingError::InvalidDescription { + reason: "an external exchange issuer cannot name this issuer" + }) + ), + "{host}{path}" + ); + } + } + let mut description = exchange_description(); + description.exchange_issuers[0].issuer = format!("http://127.0.0.1:{}", port + 1); + description.exchange_issuers[0].jwks_endpoint = + format!("http://127.0.0.1:{}/jwks", port + 1); + assert!( + description.validate().is_ok(), + "another loopback port is another issuer" + ); + } + #[test] fn development_hosts_are_loopback_or_the_docker_host_name() { for (host, loopback) in [ diff --git a/crates/registry-thunderid-tooling/src/identity_facts.rs b/crates/registry-thunderid-tooling/src/identity_facts.rs index 63006bda42..845f8dca53 100644 --- a/crates/registry-thunderid-tooling/src/identity_facts.rs +++ b/crates/registry-thunderid-tooling/src/identity_facts.rs @@ -479,15 +479,15 @@ pub(crate) fn https_url(value: &str) -> bool { }) } -/// An `https` URL, or `http` to 127.0.0.1, without user information, query -/// or fragment. A facts document may describe a development issuer. +/// An `https` URL, or `http` to a loopback address literal, without user +/// information, query or fragment. A facts document may describe a development issuer. fn issuer_url(value: &str) -> bool { https_url(value) || (Url::new(value).is_ok() && url::Url::parse(value).is_ok_and(|url| { url.scheme() == "http" && url.host_str().is_some_and(|host| { - registry_platform_loopback::loopback_host(host).is_some() + registry_platform_loopback::loopback_literal(host).is_some() }) && url.username().is_empty() && url.password().is_none() diff --git a/crates/registry-thunderid-tooling/src/identity_facts_tests.rs b/crates/registry-thunderid-tooling/src/identity_facts_tests.rs index 564d4a56a2..59c27f4ddc 100644 --- a/crates/registry-thunderid-tooling/src/identity_facts_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_facts_tests.rs @@ -536,8 +536,8 @@ fn an_http_issuer_follows_the_shared_loopback_rule() { ("127.0.0.2", true), ("[::1]", true), ("[::ffff:127.0.0.1]", true), - ("localhost", true), - ("LOCALHOST", true), + ("localhost", false), + ("LOCALHOST", false), ("a.localhost", false), ("localhost.", false), ("10.0.0.1", false), diff --git a/docs/site/src/content/docs/configure/request-an-access-token.mdx b/docs/site/src/content/docs/configure/request-an-access-token.mdx index bd744f578d..1b900996f4 100644 --- a/docs/site/src/content/docs/configure/request-an-access-token.mdx +++ b/docs/site/src/content/docs/configure/request-an-access-token.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to persona: - consumer or verifier @@ -109,8 +109,7 @@ Existing bounded multi-audience tokens remain accepted where the owning profile A token without the target audience grants no access to that resource. Casework task-client profiles keep their narrower audience rules. -{/* Evidence: crates/registry-platform-oidc/src/diagnostics.rs failed_check; - crates/registry-messaging/src/auth.rs access_token_profile, AUDIENCE. */} +{/* Evidence: crates/registry-messaging/src/auth.rs access_token_profile, AUDIENCE. */} {/* TODO[evidence]: the multi-audience acceptance rule and the Casework task-client audience rule have no single code anchor. */} ## Token profile each service accepts @@ -190,13 +189,13 @@ A hostname that resolves to loopback is not a literal-loopback exception. Public invalid-credential responses remain a generic 401 `authentication.refused`. Authenticated profile and route failures keep their documented 403 or concealment, and a verifier outage keeps its product's 503. -Internal verification stages are fixed labels: header, algorithm, token-type, key, signature, issuer, audience, time, client, scope, profile, and unavailable. -Each verifier emits at most one diagnostic per stage per minute. +Each refusal writes one `request refused` log line with a fixed `failed_check` label, and the product counts it by that label where it serves metrics. +A verifier writes at most five lines per check per minute, and the next line reports how many refusals of that check the window counted but did not log. These logs contain no credential, claim, issuer, audience, scope, key, or subject values. Use the selected configuration and safe local validation to identify the mismatched field, and never add token contents to runtime logs. Local fixture validation names the field or rule and the expected profile category without printing input values. -{/* Evidence: crates/registry-platform-oidc/src/diagnostics.rs failed_check; +{/* Evidence: crates/registry-platform-authcommon/src/refusal.rs failed_check; crates/registry-adapter-core/src/problem.rs AUTHENTICATION_REFUSED_PROBLEM. */} ## Troubleshooting diff --git a/products/messaging/CHANGELOG.md b/products/messaging/CHANGELOG.md index 05e5f78e41..51e8323086 100644 --- a/products/messaging/CHANGELOG.md +++ b/products/messaging/CHANGELOG.md @@ -12,6 +12,10 @@ check its producer names, and a key endpoint outage under `key-source-unavailable`. `messaging_authentication_refusals_total{reason}` is unchanged. Refusal statuses, headers and bodies are unchanged. +- A scope refusal line also names the scope claim the deployment reads, the + scope the access profile requires and the profile's id. The values come from + the configuration and the reviewed package, never from the token. No other + refusal line carries them, and the answer is unchanged. - A static key set with a private key member or a repeated member name is refused at startup under `messaging.runtime.unreadable-jwks-secret`, with the rule it broke, and `messagingctl` names the rule when it refuses a diff --git a/products/messaging/contracts/security-invariant-matrix.yaml b/products/messaging/contracts/security-invariant-matrix.yaml index 4f3e407729..61616c854a 100644 --- a/products/messaging/contracts/security-invariant-matrix.yaml +++ b/products/messaging/contracts/security-invariant-matrix.yaml @@ -214,10 +214,11 @@ invariants: template reference, correlation, outcome class, and a keyed recipient reference; log fields never carry payload values; metric labels are closed sets fixed in code. Authentication refusal diagnostics use only - fixed stage labels and static remedy keys, at most once per stage per - minute per verifier. This includes HTTP bearer and compact-token - admission failures; required time claims and maximum-lifetime failures - are time-stage refusals. These diagnostics never contain credentials, + a fixed failed-check label and static remedy keys, at most five lines + per check per minute, with every refusal counted by its check. This + includes HTTP bearer and compact-token admission failures; required + time claims and maximum-lifetime failures are token-time refusals. + These diagnostics never contain credentials, claim or scope values, issuer URLs, or underlying error text, and do not change public refusal/outage status or audit acceptance. The audit writer opens before serving and its diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 47235331c8..10e867c46f 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -133,10 +133,12 @@ spellings than before, for example `127.0.0.2` and `[::ffff:127.0.0.1]`. - `registry-thunderid-tooling` reads development identity files and task - connections with the same loopback rule. A development issuer, exchange - issuer or local app origin may be any `127.0.0.0/8` address, `[::1]`, the - IPv4-mapped form or `localhost`. The identity facts issuer and the local app - origin accepted only `127.0.0.1` before. + connections with the same loopback rule. A development issuer or local app + origin may be any `127.0.0.0/8` address, `[::1]` or the IPv4-mapped form, + and never the name `localhost`. An exchange issuer may also use `localhost` + or `host.docker.internal`, as before, and one that names the development + issuer's own listener in any of those spellings is refused. The identity + facts issuer and the local app origin accepted only `127.0.0.1` before. - Every client built by `OutboundClientBuilder` resolves the name `localhost` to `127.0.0.1` and `::1` itself, so no resolver is asked for diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index 2b7303d7e3..c11b2f964b 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -48,12 +48,12 @@ forms. - `journey.promote.`, `journey.keep.`, `journey.attach.`: the step named in the form found nothing to work with, lost the written record or refused the reader's own setup. -- `http..`: a refused call. The stage is one of the - authentication stages the shared OIDC crate reports. The journeys read it - from the product's `stage` log field or from the `failed_check` label of its - refusal line, mapped onto the stage words (for example `token-key` is `key` - and `credential-malformed` is `header`). A label with no stage word leaves the - stage empty, and the cell records the problem code instead. +- `http..`: a refused call. The stage is a word from + the table's `authenticationStages`. The journeys read the `failed_check` label + of the product's last refusal line and map it onto a stage word (for example + `token-key` is `key` and `credential-malformed` is `header`). A label with no + stage word leaves the stage empty, and the cell records the problem code + instead. - `product.`: the diagnostic code a product prints. Each row has a `basis`. A `predicted` row was inferred from reading the code. A diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index aa414f7d58..58821fb92e 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -23,8 +23,8 @@ # journey.promote. a promote step with no input or nothing to refuse # journey.keep. the keep step lost the written record # journey.attach. the attach step refused the reader's own setup -# http.. a refused call: the HTTP status and the -# authentication stage in the operator log +# http.. a refused call: the HTTP status and the stage word +# mapped from the operator log's failed_check # product. the diagnostic code a product prints for a refused # check or start diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 9faf1ccf6f..708847b04b 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -80,8 +80,8 @@ REALM=registry-journey POSTGRES_IMAGE=postgres:18.7@sha256:2ea8630df176ad090ec92136dee850397c5af8781e4bcf2e4162593691c61bbc PROJECTS_DIR=$JOURNEY_LIB_DIR/projects SECRETS=$JOURNEY_OUT/secrets -# The stages a token characterisation result value may name (`Stage` in -# registry-platform-testing), the same list as authenticationStages in the table. +# The stage words of the ratchet table (authenticationStages), a subset of the +# `Stage` words a token characterisation result value may name. STAGES=' header algorithm token-type key signature issuer audience time client scope profile unavailable ' # Every product a token reaches. The realm names a caller client for each, so # every one of their client secrets is generated even when fewer are selected. @@ -961,8 +961,8 @@ missing_claims() { journey_harness_failure "cannot read the claims of the token of $CELL" } -# logged_stage FILE...: the last authentication stage the product logged, -# from its `stage` field or the `failed_check` label of its refusal line. +# logged_stage FILE...: the stage word for the `failed_check` label of the last +# refusal line the product logged, or nothing when that label has no stage word. logged_stage() { perl -e ' my $stage = ""; @@ -986,16 +986,12 @@ logged_stage() { my $text = <$fh>; next unless defined $text; $text =~ s/\e\[[0-9;]*m//g; - # A product logs `stage`, or the refusal recorder `failed_check` - # label, which the map turns into the stage word the table lists. - # A label with no stage word is skipped, so the problem code names - # the refusal instead. - while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2|\bfailed_check"?[:=]\s*"([a-z]+(?:-[a-z]+)*)"/g) { - if (defined $4) { - $stage = $check_stage{$4} if exists $check_stage{$4}; - } else { - $stage = defined $1 ? $1 : $3; - } + # The refusal recorder writes a `failed_check` label, which the map + # turns into the stage word the table lists. The last refusal + # decides, and a label with no stage word leaves the stage empty, + # so the problem code names the refusal instead. + while ($text =~ /\bfailed_check"?[:=]\s*"([a-z]+(?:-[a-z]+)*)"/g) { + $stage = exists $check_stage{$1} ? $check_stage{$1} : ""; } } print $stage;' "$@" diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 91b2ef82dd..704d58352d 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -378,8 +378,8 @@ claim_names() { journey_harness_failure "cannot read the claims of the token of $CELL" } -# logged_stage FILE...: the last authentication stage the product logged, -# from its `stage` field or the `failed_check` label of its refusal line. +# logged_stage FILE...: the stage word for the `failed_check` label of the last +# refusal line the product logged, or nothing when that label has no stage word. logged_stage() { perl -e ' my $stage = ""; @@ -403,16 +403,12 @@ logged_stage() { my $text = <$fh>; next unless defined $text; $text =~ s/\e\[[0-9;]*m//g; - # A product logs `stage`, or the refusal recorder `failed_check` - # label, which the map turns into the stage word the table lists. - # A label with no stage word is skipped, so the problem code names - # the refusal instead. - while ($text =~ /"stage"\s*:\s*"([a-z]+(?:-[a-z]+)*)"|\bstage=("?)([a-z]+(?:-[a-z]+)*)\2|\bfailed_check"?[:=]\s*"([a-z]+(?:-[a-z]+)*)"/g) { - if (defined $4) { - $stage = $check_stage{$4} if exists $check_stage{$4}; - } else { - $stage = defined $1 ? $1 : $3; - } + # The refusal recorder writes a `failed_check` label, which the map + # turns into the stage word the table lists. The last refusal + # decides, and a label with no stage word leaves the stage empty, + # so the problem code names the refusal instead. + while ($text =~ /\bfailed_check"?[:=]\s*"([a-z]+(?:-[a-z]+)*)"/g) { + $stage = exists $check_stage{$1} ? $check_stage{$1} : ""; } } print $stage;' "$@" diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 1383045071..033c2b50b0 100644 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -251,7 +251,7 @@ issue_token() { # code for. It is a harness failure so that a new kind of refusal is looked at # and named, never recorded under a code the product did not print. unexpected_answer() { - journey_harness_failure "step $1 of $CELL answered HTTP $JOURNEY_HTTP_STATUS (problem code '${JOURNEY_HTTP_PROBLEM_CODE:-none}'); name the authentication stage from the operator log and extend rstack-dev.sh" + journey_harness_failure "step $1 of $CELL answered HTTP $JOURNEY_HTTP_STATUS (problem code '${JOURNEY_HTTP_PROBLEM_CODE:-none}'); name the stage word for the operator log's failed_check and extend rstack-dev.sh" } # walk_product PRODUCT: walk one product through the steps. diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 37bb8aabc9..3c7db27d24 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -279,11 +279,12 @@ def test_realm_import_has_no_protocol_mappers(self): class LoggedStage(unittest.TestCase): - """`logged_stage` reads a refused call's stage from `stage` or from `failed_check`.""" + """`logged_stage` maps the last refusal line's `failed_check` label onto a stage word.""" CASES = ( - ('{"stage":"token-type","msg":"refused"}', "token-type"), - ("WARN refused stage=audience", "audience"), + ('{"stage":"token-type","msg":"refused"}', ""), + ("WARN refused stage=audience", ""), + ('failed_check="token-time"\n{"stage":"extract"}', "time"), ('INFO request refused decision="refused" failed_check="token-type" suppressed=0', "token-type"), ('{"fields":{"decision":"refused","failed_check":"credential-malformed"}}', "header"), ('failed_check="token-client"', "client"), @@ -291,7 +292,8 @@ class LoggedStage(unittest.TestCase): ('failed_check="key-source-unavailable"', "unavailable"), ('failed_check="token-key"\nfailed_check="token-time"', "time"), ('failed_check="credential-missing"', ""), - ('failed_check="token-time"\nfailed_check="operation"', "time"), + ('failed_check="token-time"\nfailed_check="operation"', ""), + ('failed_check="token-type"\nfailed_check="access-profile"', ""), ("no refusal here", ""), ) @@ -302,7 +304,7 @@ def function(script: str) -> str: assert match, f"{script} has no logged_stage" return match.group(0) - def test_the_stage_reads_both_log_fields(self): + def test_the_last_refusal_label_decides_the_stage(self): for script in ("own-provider.sh", "promote.sh"): function = self.function(script) for log, expected in self.CASES: From 742a5e23a3ead5cb54477cdc6e94406778c1d3a6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 09:56:05 +0100 Subject: [PATCH 060/136] fix: bring side lockfiles and four tests in line with the branch The BReg WASM handler SDK and the manifest and platform fuzz workspaces lock the new loopback and posture crates, so their locked update check passes again. The provision tests build their synthetic audit key instead of spelling a key-shaped literal. The OID4VCI metrics docs test counts the refusal family the shared recorder renders, the Messaging tutorial test expects the new provision section, and the Adapter live contract test expects a binding on a reserved facade path to refuse the deployment at startup, as the workspace check now does. Signed-off-by: Jeremi Joslin --- .../tests/effective_contract_live.rs | 41 ++++++-------- .../tests/provision_cli.rs | 2 +- .../tests/provision_postgres.rs | 2 +- .../tests/provision_cli.rs | 2 +- .../tests/provision_postgres.rs | 2 +- .../scripts/check-messaging-tutorial.test.mjs | 1 + .../scripts/evidence-gateway-docs.test.mjs | 5 ++ products/breg/wasm-handler-sdk/Cargo.lock | 25 +++++++++ products/manifest/fuzz/Cargo.lock | 55 +++++++++++++++++++ products/platform/fuzz/Cargo.lock | 14 ++++- 10 files changed, 120 insertions(+), 29 deletions(-) diff --git a/crates/registry-adapter/tests/effective_contract_live.rs b/crates/registry-adapter/tests/effective_contract_live.rs index a0ed4ba49c..62deebdd01 100644 --- a/crates/registry-adapter/tests/effective_contract_live.rs +++ b/crates/registry-adapter/tests/effective_contract_live.rs @@ -366,7 +366,7 @@ async fn authentication_and_admission_precede_the_pin_which_precedes_body_and_so } #[tokio::test] -async fn a_valid_concrete_collision_is_unserved_before_router_construction() { +async fn a_concrete_collision_with_a_reserved_route_refuses_to_start() { let upstream = UpstreamDouble::start(); let directory = tempfile::tempdir().expect("a copied Adapter project"); copy_example_project(directory.path()); @@ -386,32 +386,25 @@ async fn a_valid_concrete_collision_is_unserved_before_router_construction() { &project_path, project.replace("person", "effective-contract"), ) - .expect("write the valid concrete-collision project"); + .expect("write the concrete-collision project"); - let served = Served::start_with_project(&upstream.url(""), directory.path()).await; - let token = served.token(""); - let readback = served.get(WELL_KNOWN_PATH, Some(&token)); - assert_eq!(readback.0, 200, "{}", readback.2); - let unserved = readback.2["contract"]["unserved"] - .as_array() - .expect("the contract carries unserved operations"); - for binding in ["effective-contract-search", "effective-contract-create"] { - let colliding = unserved - .iter() - .find(|entry| entry["bindingId"] == binding) - .unwrap_or_else(|| panic!("the {binding} collision is explicitly unserved")); - assert_eq!( - colliding["reasonCode"], - "adapter.operation.reserved-facade-path" - ); - assert_eq!( - colliding["reason"], - "the facade path is reserved for the Adapter effective-contract, health and ready routes" - ); - } + // The workspace check refuses both colliding bindings before the facade + // builds a router, so the reserved route is never shadowed. + let stderr = Served::refusal_with_project(&upstream.url(""), directory.path()).await; + assert!( + stderr.contains("the workspace check refused the deployment"), + "{stderr}" + ); + assert_eq!( + stderr + .matches("adapter.project.reserved-facade-path") + .count(), + 2, + "{stderr}" + ); assert_eq!( upstream.request_count(), 0, - "the built-in protected route wins without source I/O" + "a refused deployment performs no source I/O" ); } diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs index 1fb28ea3b0..dcb70b1813 100644 --- a/crates/registry-messagingctl/tests/provision_cli.rs +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -36,7 +36,7 @@ fn write_runtime_for(directory: &Path, database: &str) -> String { "runtime-database-url", format!("postgresql://messaging_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/{database}"), ), - ("audit-key", "0123456789abcdef0123456789abcdef".to_owned()), + ("audit-key", "5a".repeat(16)), ( "jwks.json", r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), diff --git a/crates/registry-messagingctl/tests/provision_postgres.rs b/crates/registry-messagingctl/tests/provision_postgres.rs index 611f04e31e..2b9be2835f 100644 --- a/crates/registry-messagingctl/tests/provision_postgres.rs +++ b/crates/registry-messagingctl/tests/provision_postgres.rs @@ -37,7 +37,7 @@ impl Deployment { std::fs::create_dir(&secrets).unwrap(); std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); let deployment = Self { directory, admin }; - deployment.secret("audit-key", "0123456789abcdef0123456789abcdef"); + deployment.secret("audit-key", &"5a".repeat(16)); // The runtime verifies tokens against a static key set, so it starts // without reaching the issuer. deployment.secret( diff --git a/crates/registry-schedulingctl/tests/provision_cli.rs b/crates/registry-schedulingctl/tests/provision_cli.rs index b0709fdab4..6f6addbe10 100644 --- a/crates/registry-schedulingctl/tests/provision_cli.rs +++ b/crates/registry-schedulingctl/tests/provision_cli.rs @@ -32,7 +32,7 @@ fn write_runtime(directory: &Path) -> String { "postgresql://scheduling_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/scheduling" ), ), - ("audit-key", "0123456789abcdef0123456789abcdef".to_owned()), + ("audit-key", "5a".repeat(16)), ( "jwks.json", r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), diff --git a/crates/registry-schedulingctl/tests/provision_postgres.rs b/crates/registry-schedulingctl/tests/provision_postgres.rs index 9fcbd14251..cd5942f7fc 100644 --- a/crates/registry-schedulingctl/tests/provision_postgres.rs +++ b/crates/registry-schedulingctl/tests/provision_postgres.rs @@ -37,7 +37,7 @@ impl Deployment { std::fs::create_dir(&secrets).unwrap(); std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); let deployment = Self { directory, admin }; - deployment.secret("audit-key", "0123456789abcdef0123456789abcdef"); + deployment.secret("audit-key", &"5a".repeat(16)); // The runtime verifies tokens against a static key set, so it starts // without reaching the issuer. deployment.secret( diff --git a/docs/site/scripts/check-messaging-tutorial.test.mjs b/docs/site/scripts/check-messaging-tutorial.test.mjs index 085c33e202..87c79ad536 100644 --- a/docs/site/scripts/check-messaging-tutorial.test.mjs +++ b/docs/site/scripts/check-messaging-tutorial.test.mjs @@ -135,6 +135,7 @@ test('the gate executes the local journey and names the hosted fences it omits', [ 'Install the binaries', 'Check the runtime file', + 'Provision PostgreSQL', 'Record and serve the package', 'Operate messages', 'Erase expired data on demand', diff --git a/docs/site/scripts/evidence-gateway-docs.test.mjs b/docs/site/scripts/evidence-gateway-docs.test.mjs index 5d8d2e229e..d4310ce1e2 100644 --- a/docs/site/scripts/evidence-gateway-docs.test.mjs +++ b/docs/site/scripts/evidence-gateway-docs.test.mjs @@ -116,6 +116,11 @@ test('names exactly the metrics the OID4VCI delivery front end renders', () => { ); const rendered = new Set([...observability.matchAll(/"(evidence_oid4vci_\w+)"/g)].map((match) => match[1])); assert.ok(rendered.size > 0, 'expected observability.rs to name metric families'); + // The shared refusal recorder renders `_request_refusals_total` for + // the prefix the service gives it. + for (const match of observability.matchAll(/RefusalRecorder::new\("(evidence_oid4vci)"\)/g)) { + rendered.add(`${match[1]}_request_refusals_total`); + } const page = readFileSync(resolve(docsRoot, 'configure/evidence-oid4vci.mdx'), 'utf8'); const metricsSection = page.split(/^## Metrics$/m)[1]?.split(/^## /m)[0] ?? ''; diff --git a/products/breg/wasm-handler-sdk/Cargo.lock b/products/breg/wasm-handler-sdk/Cargo.lock index b984a86086..01143aa7fc 100644 --- a/products/breg/wasm-handler-sdk/Cargo.lock +++ b/products/breg/wasm-handler-sdk/Cargo.lock @@ -3021,12 +3021,15 @@ name = "registry-platform-config" version = "0.49.0" dependencies = [ "registry-platform-canonical-json", + "registry-platform-loopback", + "registry-platform-posture", "registry-platform-yaml", "rustix 1.1.6", "serde", "serde_json", "sha2 0.11.1", "thiserror 2.0.21", + "tracing", "url", "zeroize", ] @@ -3074,6 +3077,7 @@ name = "registry-platform-httpsec" version = "0.49.0" dependencies = [ "http", + "registry-platform-loopback", "serde", "serde_json", "thiserror 2.0.21", @@ -3094,6 +3098,7 @@ dependencies = [ "registry-platform-authcommon", "registry-platform-canonical-json", "registry-platform-crypto", + "registry-platform-loopback", "reqwest", "rustls-native-certs", "serde", @@ -3107,6 +3112,14 @@ dependencies = [ "zeroize", ] +[[package]] +name = "registry-platform-loopback" +version = "0.49.0" + +[[package]] +name = "registry-platform-posture" +version = "0.49.0" + [[package]] name = "registry-platform-script" version = "0.49.0" @@ -4159,9 +4172,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tracing-core" version = "0.1.36" diff --git a/products/manifest/fuzz/Cargo.lock b/products/manifest/fuzz/Cargo.lock index d6ad1c6bc6..06a9797800 100644 --- a/products/manifest/fuzz/Cargo.lock +++ b/products/manifest/fuzz/Cargo.lock @@ -431,6 +431,12 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -452,6 +458,12 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + [[package]] name = "potential_utf" version = "0.1.6" @@ -491,6 +503,7 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" name = "registry-cli-report" version = "0.49.0" dependencies = [ + "registry-platform-posture", "serde", "serde_json", ] @@ -552,16 +565,27 @@ name = "registry-platform-config" version = "0.49.0" dependencies = [ "registry-platform-canonical-json", + "registry-platform-loopback", + "registry-platform-posture", "registry-platform-yaml", "rustix", "serde", "serde_json", "sha2", "thiserror", + "tracing", "url", "zeroize", ] +[[package]] +name = "registry-platform-loopback" +version = "0.49.0" + +[[package]] +name = "registry-platform-posture" +version = "0.49.0" + [[package]] name = "registry-platform-text" version = "0.49.0" @@ -766,6 +790,37 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + [[package]] name = "typenum" version = "1.20.1" diff --git a/products/platform/fuzz/Cargo.lock b/products/platform/fuzz/Cargo.lock index b61301373e..1ed8663648 100644 --- a/products/platform/fuzz/Cargo.lock +++ b/products/platform/fuzz/Cargo.lock @@ -1796,12 +1796,15 @@ name = "registry-platform-config" version = "0.49.0" dependencies = [ "registry-platform-canonical-json", + "registry-platform-loopback", + "registry-platform-posture", "registry-platform-yaml", "rustix", "serde", "serde_json", "sha2 0.11.1", "thiserror", + "tracing", "url", "zeroize", ] @@ -1863,6 +1866,7 @@ dependencies = [ "registry-platform-authcommon", "registry-platform-canonical-json", "registry-platform-crypto", + "registry-platform-loopback", "reqwest", "rustls-native-certs", "serde", @@ -1876,6 +1880,10 @@ dependencies = [ "zeroize", ] +[[package]] +name = "registry-platform-loopback" +version = "0.49.0" + [[package]] name = "registry-platform-oidc" version = "0.49.0" @@ -1883,6 +1891,7 @@ dependencies = [ "base64 0.23.1", "chrono", "jsonwebtoken", + "registry-platform-authcommon", "registry-platform-config", "registry-platform-crypto", "registry-platform-httputil", @@ -1892,10 +1901,13 @@ dependencies = [ "serde_json", "thiserror", "tokio", - "tracing", "uuid", ] +[[package]] +name = "registry-platform-posture" +version = "0.49.0" + [[package]] name = "registry-platform-sdjwt" version = "0.49.0" From 53657a59a5ffe9d6fc3ab5ce93e77677275740ee Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:07:39 +0100 Subject: [PATCH 061/136] feat(platform): mark development responses in the shared security headers security_headers takes the declared posture. In development every response carries Registry-Posture: development, and in production no mark is sent. posture_mark sets only the mark, for routers that do not use the shared headers. Callers move to security_headers_without_posture, which behaves as production, until each runtime adopts the posture. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-breg-review/src/lib.rs | 4 +- crates/registry-breg/src/api/mod.rs | 6 +- crates/registry-casework/src/http.rs | 6 +- crates/registry-coordinator/src/http.rs | 2 +- crates/registry-coordinator/src/metrics.rs | 2 +- crates/registry-discovery/src/server.rs | 4 +- crates/registry-documents/src/http.rs | 6 +- .../registry-evidence-oid4vci/src/service.rs | 8 +- .../registry-evidence-oid4vp/src/service.rs | 8 +- crates/registry-evidence/src/server.rs | 3 +- crates/registry-mcp-edge/src/server.rs | 6 +- crates/registry-messaging/src/http.rs | 6 +- crates/registry-platform-httpsec/Cargo.toml | 1 + crates/registry-platform-httpsec/README.md | 14 +- .../registry-platform-httpsec/src/server.rs | 202 +++++++++++++++++- .../tests/cross_crate_integration.rs | 12 +- crates/registry-render/src/server.rs | 6 +- crates/registry-scheduling/src/http.rs | 6 +- products/platform/CHANGELOG.md | 7 + 20 files changed, 258 insertions(+), 52 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a755f8d6e2..6cd4041082 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7952,6 +7952,7 @@ dependencies = [ "http", "registry-platform-authcommon", "registry-platform-loopback", + "registry-platform-posture", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/registry-breg-review/src/lib.rs b/crates/registry-breg-review/src/lib.rs index 14eccf5fb4..240b6c8afb 100644 --- a/crates/registry-breg-review/src/lib.rs +++ b/crates/registry-breg-review/src/lib.rs @@ -44,7 +44,7 @@ use jsonwebtoken::Algorithm; use registry_breg_client::{BaseRegistryClient, BaseRegistryClientConfig}; use registry_platform_audit::{AuditProfile, AuditWriter}; use registry_platform_crypto::PrivateJwk; -use registry_platform_httpsec::{security_headers, CspBuilder}; +use registry_platform_httpsec::{security_headers_without_posture, CspBuilder}; use registry_platform_httputil::client::{PrivateKeyJwt, PrivateKeyJwtConfig}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ @@ -727,7 +727,7 @@ async fn build(config: RuntimeConfig, writer: Option) -> Result) -> Router { .merge(probe_routes(service)) .layer(middleware::from_fn(metadata::no_store)) .layer(middleware::from_fn(crate::correlation::observe)) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers_without_posture(CspBuilder::restrictive())) } fn route_set(service: Arc) -> Router { @@ -302,7 +302,7 @@ pub fn authenticated_router( }; app.layer(middleware::from_fn(metadata::no_store)) .layer(middleware::from_fn(crate::correlation::observe)) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers_without_posture(CspBuilder::restrictive())) } async fn review_completion( diff --git a/crates/registry-casework/src/http.rs b/crates/registry-casework/src/http.rs index 8a7f019095..0db408d148 100644 --- a/crates/registry-casework/src/http.rs +++ b/crates/registry-casework/src/http.rs @@ -18,8 +18,8 @@ use registry_platform_authcommon::{ RefusalRecorder, }; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, - FrameworkRejection, ProblemBody, TraceContext, + normalize_framework_rejection, request_body_limit_default, security_headers_without_posture, + CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use serde_json::error::Category; @@ -278,7 +278,7 @@ where .layer(middleware::from_fn(move |request, next| { http_boundary(contract, request, next) })) - .layer(security_headers(CspBuilder::restrictive()).without_hsts()) + .layer(security_headers_without_posture(CspBuilder::restrictive()).without_hsts()) } /// Counts and logs the refusal a response carries in its extensions. The diff --git a/crates/registry-coordinator/src/http.rs b/crates/registry-coordinator/src/http.rs index 27bcc9301a..362fc3ae89 100644 --- a/crates/registry-coordinator/src/http.rs +++ b/crates/registry-coordinator/src/http.rs @@ -175,7 +175,7 @@ fn http_edge(router: Router, signed_events: Router, refusals: Arc) -> Router { Router::new() .route(METRICS_PATH, get(serve_metrics)) .layer(registry_platform_httpsec::request_body_limit(65_536)) - .layer(registry_platform_httpsec::security_headers( + .layer(registry_platform_httpsec::security_headers_without_posture( registry_platform_httpsec::CspBuilder::deny_by_default(), )) .with_state(MetricsState { store }) diff --git a/crates/registry-discovery/src/server.rs b/crates/registry-discovery/src/server.rs index b0251b7615..d765f2cf2a 100644 --- a/crates/registry-discovery/src/server.rs +++ b/crates/registry-discovery/src/server.rs @@ -12,7 +12,7 @@ use axum::middleware; use axum::routing::{get, post}; use axum::Router; use registry_platform_canonical_json::parse_json_strict; -use registry_platform_httpsec::{security_headers, CspBuilder}; +use registry_platform_httpsec::{security_headers_without_posture, CspBuilder}; use serde::de::DeserializeOwned; use serde::Serialize; use thiserror::Error; @@ -179,7 +179,7 @@ pub fn router( }, ), ) - .layer(security_headers(CspBuilder::restrictive()))) + .layer(security_headers_without_posture(CspBuilder::restrictive()))) } async fn enforce_http_limits( diff --git a/crates/registry-documents/src/http.rs b/crates/registry-documents/src/http.rs index be23fc788a..e4bd1bcb21 100644 --- a/crates/registry-documents/src/http.rs +++ b/crates/registry-documents/src/http.rs @@ -30,8 +30,8 @@ use registry_platform_authcommon::{ parse_bearer_token, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, }; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, - FrameworkRejection, ProblemBody, TraceContext, + normalize_framework_rejection, request_body_limit_default, security_headers_without_posture, + CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; use serde::de::DeserializeOwned; @@ -66,7 +66,7 @@ fn finish(limited: Router, unlimited: Router) -> Router { .fallback(route_not_found) .method_not_allowed_fallback(method_not_allowed) .layer(middleware::from_fn(http_boundary)) - .layer(security_headers(CspBuilder::restrictive()).without_hsts()) + .layer(security_headers_without_posture(CspBuilder::restrictive()).without_hsts()) } /// The operator-private router the metrics listener serves: the series, with diff --git a/crates/registry-evidence-oid4vci/src/service.rs b/crates/registry-evidence-oid4vci/src/service.rs index 3008926864..cd07624bf5 100644 --- a/crates/registry-evidence-oid4vci/src/service.rs +++ b/crates/registry-evidence-oid4vci/src/service.rs @@ -58,8 +58,8 @@ use registry_platform_authcommon::{FailedCheck, RefusalNote}; use registry_platform_config::describe_secret_failure; use registry_platform_crypto::PublicJwk; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit, security_headers, CspBuilder, - FrameworkRejection, + normalize_framework_rejection, request_body_limit, security_headers_without_posture, + CspBuilder, FrameworkRejection, }; use registry_platform_ratelimit::token_bucket::{ TokenBucketConfig, TokenBucketError, TokenBucketLimiter, @@ -617,7 +617,9 @@ pub fn build_app(service: Arc) -> Router { refuse_a_stalled_request, )) .layer(from_fn(normalize_rejections)) - .layer(security_headers(CspBuilder::deny_by_default())) + .layer(security_headers_without_posture( + CspBuilder::deny_by_default(), + )) .layer(from_fn_with_state(metrics, observability::observe)) .layer(from_fn(add_no_store)) } diff --git a/crates/registry-evidence-oid4vp/src/service.rs b/crates/registry-evidence-oid4vp/src/service.rs index 9cc7a91c75..22e6a6332a 100644 --- a/crates/registry-evidence-oid4vp/src/service.rs +++ b/crates/registry-evidence-oid4vp/src/service.rs @@ -26,8 +26,8 @@ use chrono::{DateTime, SecondsFormat, Utc}; use registry_platform_authcommon::{DeclaredScope, FailedCheck, RefusalNote, RefusalRecorder}; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit, security_headers, CspBuilder, - FrameworkRejection, Problem, TraceContext, + normalize_framework_rejection, request_body_limit, security_headers_without_posture, + CspBuilder, FrameworkRejection, Problem, TraceContext, }; use registry_platform_ratelimit::token_bucket::{ TokenBucketConfig, TokenBucketError, TokenBucketLimiter, @@ -433,7 +433,9 @@ pub fn build_app(service: Arc) -> Router { .with_state(service) .layer(from_fn_with_state(timeout, bound_request_time)) .layer(from_fn(normalize_rejections)) - .layer(security_headers(CspBuilder::deny_by_default())) + .layer(security_headers_without_posture( + CspBuilder::deny_by_default(), + )) .layer(from_fn(apply_trace_context)) .layer(from_fn_with_state(refusals, record_refusals)) } diff --git a/crates/registry-evidence/src/server.rs b/crates/registry-evidence/src/server.rs index 9a6518cd82..33a215927d 100644 --- a/crates/registry-evidence/src/server.rs +++ b/crates/registry-evidence/src/server.rs @@ -278,7 +278,8 @@ fn response_layers(routes: Router, metrics: Arc) -> Router { .layer(from_fn(add_no_store)) .layer(registry_platform_httpsec::corp_conditional()) .layer( - registry_platform_httpsec::security_headers(CspBuilder::restrictive()).without_hsts(), + registry_platform_httpsec::security_headers_without_posture(CspBuilder::restrictive()) + .without_hsts(), ) // Outermost, so that every response including both fallbacks carries a // correlation identifier and produces exactly one operational record. diff --git a/crates/registry-mcp-edge/src/server.rs b/crates/registry-mcp-edge/src/server.rs index 83fdc4574f..ba478b8a20 100644 --- a/crates/registry-mcp-edge/src/server.rs +++ b/crates/registry-mcp-edge/src/server.rs @@ -12,7 +12,9 @@ use axum::{ Json, Router, }; use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote, RefusalRecorder}; -use registry_platform_httpsec::{request_body_limit, security_headers, CspBuilder, Problem}; +use registry_platform_httpsec::{ + request_body_limit, security_headers_without_posture, CspBuilder, Problem, +}; use rmcp::transport::streamable_http_server::{ session::never::NeverSessionManager, StreamableHttpServerConfig, StreamableHttpService, }; @@ -139,7 +141,7 @@ pub fn router( .route(METADATA_PREFIX, get(metadata)) .route(&metadata_path, get(metadata)) .with_state(resource_server); - let headers = security_headers(CspBuilder::restrictive()); + let headers = security_headers_without_posture(CspBuilder::restrictive()); let headers = if options.hsts { headers } else { diff --git a/crates/registry-messaging/src/http.rs b/crates/registry-messaging/src/http.rs index 4a32be83c5..190dfaedc0 100644 --- a/crates/registry-messaging/src/http.rs +++ b/crates/registry-messaging/src/http.rs @@ -55,8 +55,8 @@ use registry_platform_authcommon::{ }; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, - FrameworkRejection, ProblemBody, TraceContext, + normalize_framework_rejection, request_body_limit_default, security_headers_without_posture, + CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; use serde::Serialize; @@ -421,7 +421,7 @@ fn http_edge(router: Router) -> Router { .method_not_allowed_fallback(method_not_allowed) .layer(request_body_limit_default()) .layer(middleware::from_fn(http_boundary)) - .layer(security_headers(CspBuilder::restrictive()).without_hsts()) + .layer(security_headers_without_posture(CspBuilder::restrictive()).without_hsts()) } async fn http_boundary(request: axum::http::Request, next: Next) -> Response { diff --git a/crates/registry-platform-httpsec/Cargo.toml b/crates/registry-platform-httpsec/Cargo.toml index 9bbc8d0cb0..0332ab1ecd 100644 --- a/crates/registry-platform-httpsec/Cargo.toml +++ b/crates/registry-platform-httpsec/Cargo.toml @@ -35,6 +35,7 @@ axum = { workspace = true, optional = true } http.workspace = true registry-platform-authcommon = { workspace = true, optional = true } registry-platform-loopback.workspace = true +registry-platform-posture.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/crates/registry-platform-httpsec/README.md b/crates/registry-platform-httpsec/README.md index 928febe62e..0f085410c3 100644 --- a/crates/registry-platform-httpsec/README.md +++ b/crates/registry-platform-httpsec/README.md @@ -8,8 +8,14 @@ Client-safe HTTP validation plus Axum and Tower helpers for HTTP security. - Restrictive CSP header generation through `CspBuilder`, including a `deny_by_default` policy (`default-src 'none'`) and an optional `form-action` directive for server-rendered forms. -- `security_headers` middleware for CSP, content sniffing, referrer, and frame - protections. +- `security_headers(csp, posture)` middleware for CSP, content sniffing, + referrer, and frame protections. A development process also marks every + response with `Registry-Posture: development`, overwriting a value a handler + set. A production process sends no mark. `security_headers_without_posture` + is the transitional entry point for a caller that holds no posture yet, and + behaves as production. +- `posture_mark(posture)`, a layer that only sets the development mark, for + routers that do not use `security_headers`. - Conditional Cross-Origin-Resource-Policy handling. - Request body limit layer construction. - RFC 9457 Problem Details responses with `application/problem+json`. @@ -50,6 +56,7 @@ use axum::{http::Method, Router}; use registry_platform_httpsec::{ corp_conditional, request_body_limit, security_headers, CorsPolicy, CspBuilder, }; +use registry_platform_posture::Posture; let cors = CorsPolicy { allowed_origins: vec!["https://app.example.test".to_string()], @@ -60,7 +67,7 @@ let cors = CorsPolicy { let app = Router::new() .layer(corp_conditional()) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers(CspBuilder::restrictive(), Posture::Production)) .layer(cors.layer()) .layer(request_body_limit(1024 * 1024)); let _ = app; @@ -73,6 +80,7 @@ let _ = app; - HTTPS origins are accepted. HTTP origins are accepted only for loopback development origins. - Existing security headers are preserved when `security_headers` is applied. + The development posture mark is the exception: it overwrites. - Invalid, duplicate, or absent inbound `traceparent` values receive a fresh server trace. One valid lower-case W3C version 0 `traceparent` is retained. Caller `tracestate` is never echoed. diff --git a/crates/registry-platform-httpsec/src/server.rs b/crates/registry-platform-httpsec/src/server.rs index d4292bd0b3..a2bbe6a7c9 100644 --- a/crates/registry-platform-httpsec/src/server.rs +++ b/crates/registry-platform-httpsec/src/server.rs @@ -14,6 +14,7 @@ use axum::body::Body; use axum::http::header::{HeaderName, HeaderValue, CONTENT_TYPE}; use axum::http::{HeaderMap, Method, Request, Response, StatusCode}; use axum::response::IntoResponse; +use registry_platform_posture::{Posture, POSTURE_HEADER}; use serde::Serialize; use serde_json::Value; use tower::{Layer, Service}; @@ -344,10 +345,87 @@ fn checked_sources(sources: &[&'static str]) -> Vec<&'static str> { /// HSTS for deployments that terminate TLS upstream or serve plain HTTP. pub const DEFAULT_HSTS_VALUE: &str = "max-age=63072000; includeSubDomains"; -pub fn security_headers(csp: CspBuilder) -> SecurityHeadersLayer { +/// The shared response-header baseline for a service of the given posture. +/// +/// A development process also marks every response with `Registry-Posture: +/// development`, overwriting a value a handler set. A production process sends +/// no mark, so an absent field makes no claim. +pub fn security_headers(csp: CspBuilder, posture: Posture) -> SecurityHeadersLayer { SecurityHeadersLayer { csp: csp.header_value(), hsts: Some(HeaderValue::from_static(DEFAULT_HSTS_VALUE)), + posture, + } +} + +/// [`security_headers`] for a caller that does not yet hold a posture. It +/// behaves as production: no mark is sent. +pub fn security_headers_without_posture(csp: CspBuilder) -> SecurityHeadersLayer { + security_headers(csp, Posture::Production) +} + +/// A layer that only sets the posture mark, for routers that do not use +/// [`security_headers`]. A development process sets `Registry-Posture: +/// development` on every response, overwriting a handler value. A production +/// process sets nothing. +pub fn posture_mark(posture: Posture) -> PostureMarkLayer { + PostureMarkLayer { posture } +} + +fn mark_development(response: &mut Response, posture: Posture) { + if posture == Posture::Development { + response.headers_mut().insert( + HeaderName::from_static(POSTURE_HEADER), + HeaderValue::from_static(Posture::Development.as_str()), + ); + } +} + +#[derive(Debug, Clone)] +pub struct PostureMarkLayer { + posture: Posture, +} + +impl Layer for PostureMarkLayer { + type Service = PostureMarkService; + + fn layer(&self, inner: S) -> Self::Service { + PostureMarkService { + inner, + posture: self.posture, + } + } +} + +#[derive(Debug, Clone)] +pub struct PostureMarkService { + inner: S, + posture: Posture, +} + +impl Service> for PostureMarkService +where + S: Service, Response = Response> + Send + 'static, + S::Future: Send + 'static, + S::Error: Send + 'static, + ResBody: Send + 'static, +{ + type Response = Response; + type Error = S::Error; + type Future = Pin> + Send>>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, request: Request) -> Self::Future { + let future = self.inner.call(request); + let posture = self.posture; + Box::pin(async move { + let mut response = future.await?; + mark_development(&mut response, posture); + Ok(response) + }) } } @@ -359,6 +437,7 @@ pub struct SecurityHeadersLayer { /// [`SecurityHeadersLayer::without_hsts`] for deployments that terminate /// TLS upstream or serve plain HTTP. hsts: Option, + posture: Posture, } impl SecurityHeadersLayer { @@ -390,6 +469,7 @@ impl Layer for SecurityHeadersLayer { inner, csp: self.csp.clone(), hsts: self.hsts.clone(), + posture: self.posture, } } } @@ -399,6 +479,7 @@ pub struct SecurityHeadersService { inner: S, csp: HeaderValue, hsts: Option, + posture: Posture, } impl Service> for SecurityHeadersService @@ -420,6 +501,7 @@ where let future = self.inner.call(request); let csp = self.csp.clone(); let hsts = self.hsts.clone(); + let posture = self.posture; Box::pin(async move { let mut response = future.await?; insert_if_missing( @@ -461,6 +543,7 @@ where hsts_value, ); } + mark_development(&mut response, posture); Ok(response) }) } @@ -1036,16 +1119,16 @@ mod tests { use tower::service_fn; use tower::ServiceExt; - let service = security_headers(CspBuilder::restrictive()).layer(service_fn( - |_request: Request| async { + let service = security_headers_without_posture(CspBuilder::restrictive()).layer( + service_fn(|_request: Request| async { let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("content-security-policy"), HeaderValue::from_static("default-src 'none'"), ); Ok::<_, std::convert::Infallible>(response) - }, - )); + }), + ); let response = service .oneshot(Request::new(Body::empty())) @@ -1091,11 +1174,11 @@ mod tests { use tower::service_fn; use tower::ServiceExt; - let service = security_headers(CspBuilder::restrictive()).layer(service_fn( - |_request: Request| async { + let service = security_headers_without_posture(CspBuilder::restrictive()).layer( + service_fn(|_request: Request| async { Ok::<_, std::convert::Infallible>(Response::new(Body::empty())) - }, - )); + }), + ); let response = service .oneshot(Request::new(Body::empty())) .await @@ -1113,7 +1196,7 @@ mod tests { use tower::service_fn; use tower::ServiceExt; - let service = security_headers(CspBuilder::restrictive()) + let service = security_headers_without_posture(CspBuilder::restrictive()) .without_hsts() .layer(service_fn(|_request: Request| async { Ok::<_, std::convert::Infallible>(Response::new(Body::empty())) @@ -1131,6 +1214,105 @@ mod tests { ); } + async fn mark_of(layer: L, handler_mark: Option<&'static str>) -> Option + where + L: Layer< + tower::util::BoxCloneService, Response, std::convert::Infallible>, + >, + L::Service: Service, Response = Response> + Send + 'static, + >>::Error: std::fmt::Debug, + >>::Future: Send + 'static, + { + use tower::ServiceExt; + + let inner = tower::service_fn(move |_request: Request| async move { + let mut response = Response::new(Body::empty()); + if let Some(value) = handler_mark { + response.headers_mut().insert( + HeaderName::from_static(registry_platform_posture::POSTURE_HEADER), + HeaderValue::from_static(value), + ); + } + Ok::<_, std::convert::Infallible>(response) + }); + let response = layer + .layer(tower::util::BoxCloneService::new(inner)) + .oneshot(Request::new(Body::empty())) + .await + .expect("service responds"); + response + .headers() + .get(registry_platform_posture::POSTURE_HEADER) + .cloned() + } + + #[tokio::test] + async fn development_security_headers_set_the_mark_over_a_handler_value() { + let layer = security_headers(CspBuilder::restrictive(), Posture::Development); + assert_eq!( + mark_of(layer.clone(), None).await, + Some(HeaderValue::from_static("development")) + ); + assert_eq!( + mark_of(layer, Some("production")).await, + Some(HeaderValue::from_static("development")), + "the layer overwrites a value a handler set" + ); + } + + #[tokio::test] + async fn production_security_headers_set_no_mark_and_leave_handler_values() { + let layer = security_headers(CspBuilder::restrictive(), Posture::Production); + assert_eq!(mark_of(layer.clone(), None).await, None); + assert_eq!( + mark_of(layer, Some("handler")).await, + Some(HeaderValue::from_static("handler")), + "production neither adds nor strips the field" + ); + } + + #[tokio::test] + async fn transitional_security_headers_behave_as_production() { + let layer = security_headers_without_posture(CspBuilder::restrictive()); + assert_eq!(mark_of(layer, None).await, None); + } + + #[tokio::test] + async fn development_posture_mark_sets_the_field_on_a_bare_service() { + let layer = posture_mark(Posture::Development); + assert_eq!( + mark_of(layer.clone(), None).await, + Some(HeaderValue::from_static("development")) + ); + assert_eq!( + mark_of(layer, Some("production")).await, + Some(HeaderValue::from_static("development")) + ); + } + + #[tokio::test] + async fn production_posture_mark_sets_nothing() { + let layer = posture_mark(Posture::Production); + assert_eq!(mark_of(layer, None).await, None); + } + + #[tokio::test] + async fn development_posture_mark_applies_to_an_axum_router() { + use tower::ServiceExt; + + let router = axum::Router::new() + .route("/", axum::routing::get(|| async { "ok" })) + .layer(posture_mark(Posture::Development)); + let response = router + .oneshot(Request::new(Body::empty())) + .await + .expect("router responds"); + assert_eq!( + response.headers().get("registry-posture"), + Some(&HeaderValue::from_static("development")) + ); + } + #[test] fn conditional_corp_matches_cors_response() { let mut response = Response::new(()); diff --git a/crates/registry-platform-testing/tests/cross_crate_integration.rs b/crates/registry-platform-testing/tests/cross_crate_integration.rs index 12f6c6ef28..9cb613a386 100644 --- a/crates/registry-platform-testing/tests/cross_crate_integration.rs +++ b/crates/registry-platform-testing/tests/cross_crate_integration.rs @@ -10,8 +10,8 @@ use registry_platform_audit::{ AuditDestination, AuditEntry, AuditPhase, AuditWriter, FileDestination, }; use registry_platform_httpsec::{ - body_limit_problem_response, corp_conditional, request_body_limit, security_headers, - CorsPolicy, CspBuilder, Problem, + body_limit_problem_response, corp_conditional, request_body_limit, + security_headers_without_posture, CorsPolicy, CspBuilder, Problem, }; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ @@ -68,16 +68,16 @@ async fn sample_axum_app_wires_middleware_oidc_and_audit_writer() { Some(&HeaderValue::from_static("cross-origin")) ); - let security_service = security_headers(CspBuilder::restrictive()).layer(service_fn( - |_request: Request| async { + let security_service = security_headers_without_posture(CspBuilder::restrictive()).layer( + service_fn(|_request: Request| async { Ok::<_, std::convert::Infallible>( axum::response::Response::builder() .status(StatusCode::OK) .body(Body::empty()) .expect("response builds"), ) - }, - )); + }), + ); let secured = security_service .oneshot(Request::new(Body::empty())) .await diff --git a/crates/registry-render/src/server.rs b/crates/registry-render/src/server.rs index 9ede4a4af9..a6acfe26e2 100644 --- a/crates/registry-render/src/server.rs +++ b/crates/registry-render/src/server.rs @@ -32,7 +32,7 @@ use registry_platform_authcommon::{ RefusalNote, RefusalRecorder, MIN_API_KEY_ENTROPY_BYTES, }; use registry_platform_canonical_json::parse_json_preserving_integers; -use registry_platform_httpsec::{request_body_limit, security_headers, CspBuilder}; +use registry_platform_httpsec::{request_body_limit, security_headers_without_posture, CspBuilder}; use crate::audit::{RenderAudit, RenderAuditEvent}; use crate::auth::{RENDER_SCOPE, SCOPE_CLAIM, SEAL_SCOPE}; @@ -433,7 +433,7 @@ pub(crate) fn router(service: Arc) -> Router { } app.fallback(not_found) .with_state(service) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers_without_posture(CspBuilder::restrictive())) } /// The public application: the router under the request log, the refusal @@ -733,7 +733,7 @@ pub fn metrics_router(service: Arc, metrics: Arc) -> Router { Router::new() .route(METRICS_PATH, get(serve_metrics)) .with_state(MetricsState { metrics, service }) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers_without_posture(CspBuilder::restrictive())) } async fn serve_metrics(State(state): State) -> Response { diff --git a/crates/registry-scheduling/src/http.rs b/crates/registry-scheduling/src/http.rs index f64705e3b8..8b24b4a14d 100644 --- a/crates/registry-scheduling/src/http.rs +++ b/crates/registry-scheduling/src/http.rs @@ -37,8 +37,8 @@ use registry_platform_authcommon::{ RefusalRecorder, }; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, - FrameworkRejection, ProblemBody, TraceContext, + normalize_framework_rejection, request_body_limit_default, security_headers_without_posture, + CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use registry_scheduling_core::{ @@ -224,7 +224,7 @@ where .method_not_allowed_fallback(method_not_allowed) .layer(request_body_limit_default()) .layer(middleware::from_fn(http_boundary)) - .layer(security_headers(CspBuilder::restrictive()).without_hsts()) + .layer(security_headers_without_posture(CspBuilder::restrictive()).without_hsts()) } async fn http_boundary(request: axum::http::Request, next: Next) -> Response { diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 10e867c46f..eb3b883f45 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -67,6 +67,13 @@ into a CLI report body after the command members. A report built without it is unchanged. +- `registry-platform-httpsec`: `security_headers(csp, posture)` takes the + declared posture. In development it sets `Registry-Posture: development` on + every response, over any value a handler set, and in production it sends no + mark. `posture_mark(posture)` sets only the mark, for routers that do not use + `security_headers`. Migration: call `security_headers_without_posture(csp)`, + which behaves as production, until the runtime adopts the posture. + - `registry-platform-httpsec` implements authcommon's `RefusalTraceId` for `TraceId` behind the opt-in `refusal-trace-id` feature, not `server`. A service that only serves HTTP no longer links `registry-platform-authcommon` From 985588d0152cdcdb512bb5ce8fff41cab9be9194 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:07:48 +0100 Subject: [PATCH 062/136] docs(breg): introduce the engine's short name before the refusal metric The monitor page names Base Registry Engine (BReg) in full before its first short use, as the docs style check requires. Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/operate/breg-monitor.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/operate/breg-monitor.mdx b/docs/site/src/content/docs/operate/breg-monitor.mdx index 538f2d1f1c..c47b113267 100644 --- a/docs/site/src/content/docs/operate/breg-monitor.mdx +++ b/docs/site/src/content/docs/operate/breg-monitor.mdx @@ -341,7 +341,7 @@ with one of the `breg.external-refresh.*` codes in [Troubleshooting](#troublesho ## Watch refused requests -`breg_request_refusals_total{check}` counts the requests BReg refused, by the check that refused +`breg_request_refusals_total{check}` counts the requests Base Registry Engine (BReg) refused, by the check that refused it, since the process started. Every `check` value is published from the first scrape at zero, so a rate needs no `absent()` guard. A missing or refused credential, a refused token, an unreachable key source and a refused review completion callback all count. So does a request answered From 1a63dadcbe3a67474c1078c527bfa53078128a03 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:11:20 +0100 Subject: [PATCH 063/136] test(mcp-edge): rebuild the tracing interest cache before asserting the refusal line A test on another thread can register the refusal line's callsite while no scoped subscriber exists, which caches it as never enabled, so the unreachable key set test missed the line it asserts on Linux runners. Signed-off-by: Jeremi Joslin --- crates/registry-mcp-edge/src/compatibility_tests/inbound.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs index 963bf9334e..57c8aff95e 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs @@ -560,6 +560,10 @@ async fn an_unreachable_key_set_is_the_operators_failure() { let router = Router::new() .route("/mcp", post(|| async { "ok" })) .layer(axum::middleware::from_fn_with_state(server, require_caller)); + // A test on another thread can register the refusal line's callsite + // while no scoped subscriber exists, which caches it as never enabled. + // Rebuild the cache so this thread's subscriber is asked again. + tracing::callsite::rebuild_interest_cache(); assert_eq!( call(&router, Some(&token)).await.status(), StatusCode::SERVICE_UNAVAILABLE From fd991d75507b5ad75ccfc827d30a4d4f6d146e8e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:30:09 +0100 Subject: [PATCH 064/136] feat(platform): add loopback-plaintext termination and a development test issuer key source The shared private listener accepts tlsTermination: loopback-plaintext, valid in every posture and limited to a loopback bind. The shared OIDC issuer block accepts jwksSource type test-issuer, which reads the key set from a secret like static. A posture-aware load refuses it in production and admits and lists it in development. Every runtime that reads the shared blocks resolves the new key source like static, and Evidence keeps refusing every source other than uri. The shared and product runtime schemas and the identifier catalog are regenerated. Signed-off-by: Jeremi Joslin --- crates/registry-adapter/src/serve.rs | 2 +- crates/registry-breg-mcp/src/runtime.rs | 2 +- crates/registry-breg/src/runtime_config.rs | 14 +-- crates/registry-casework/src/config.rs | 2 +- crates/registry-coordinator/src/access.rs | 2 +- crates/registry-documents/src/config.rs | 2 +- crates/registry-evidence-oid4vp/src/auth.rs | 2 +- crates/registry-evidence-oid4vp/src/config.rs | 4 +- crates/registry-mcp/src/runtime.rs | 2 +- crates/registry-messaging/src/config.rs | 3 +- crates/registry-platform-config/src/blocks.rs | 66 ++++++++++-- .../src/blocks_tests.rs | 91 ++++++++++++++++ .../registry-platform-config/src/posture.rs | 9 ++ .../src/posture_load_tests.rs | 101 +++++++++++++++++- crates/registry-render/src/auth.rs | 3 +- crates/registry-render/src/runtime.rs | 3 +- crates/registry-scheduling/src/config.rs | 39 ++++++- .../schemas/job-runtime.v1alpha1.schema.json | 19 +++- .../schemas/runtime.v1alpha1.schema.json | 23 +++- .../mcp-runtime/mcp-runtime.schema.json | 37 ++++++- .../review-runtime/review-runtime.schema.json | 19 +++- .../generated/runtime/runtime.schema.json | 23 +++- .../generated/runtime/runtime.schema.json | 42 ++++++-- .../generated/runtime/runtime.schema.json | 42 ++++++-- .../generated/runtime/runtime.schema.json | 42 ++++++-- .../oid4vp-runtime/oid4vp-runtime.schema.json | 28 ++++- .../identifiers/generated/catalog.v1.json | 26 ++--- .../generated/runtime/runtime.schema.json | 42 ++++++-- products/platform/CHANGELOG.md | 16 +++ .../mcp-runtime/mcp-runtime.schema.json | 37 ++++++- .../runtime-config-blocks.schema.json | 42 ++++++-- products/render/schemas/runtime.schema.json | 23 +++- .../generated/runtime/runtime.schema.json | 42 ++++++-- 33 files changed, 749 insertions(+), 101 deletions(-) diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 527537549f..76733a9606 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -205,7 +205,7 @@ pub(crate) async fn authenticator( JwksFetcherConfig::defaults(), network.declared_jwks_fetch_policy(), ), - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = resolver .resolve(document_ref) .map_err(|_| invalid("the static key document could not be resolved"))?; diff --git a/crates/registry-breg-mcp/src/runtime.rs b/crates/registry-breg-mcp/src/runtime.rs index cb09aaeb5d..c47c51a907 100644 --- a/crates/registry-breg-mcp/src/runtime.rs +++ b/crates/registry-breg-mcp/src/runtime.rs @@ -154,7 +154,7 @@ async fn assemble(config: &RuntimeConfig) -> Result { policy, ) } - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = resolve( &secrets, "resourceServer.jwksSource.documentRef", diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 5efadd285a..9b858900be 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -2407,12 +2407,14 @@ impl OidcJwksSource { JwksSource::Uri { uri } => Ok(Self::Uri { uri: uri.into_string(), }), - JwksSource::Static { document_ref } => Ok(Self::Static { - document_ref: parse_secret_reference( - document_ref, - RuntimeConfigError::InvalidOidc, - )?, - }), + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { + Ok(Self::Static { + document_ref: parse_secret_reference( + document_ref, + RuntimeConfigError::InvalidOidc, + )?, + }) + } } } diff --git a/crates/registry-casework/src/config.rs b/crates/registry-casework/src/config.rs index b5ac68f348..8e1490c9de 100644 --- a/crates/registry-casework/src/config.rs +++ b/crates/registry-casework/src/config.rs @@ -1732,7 +1732,7 @@ impl RuntimeConfig { policy, ) } - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets.resolve(document_ref).map_err(|error| { RuntimeConfigError::OidcJwksSecret(describe_secret_failure( "authentication.oidc.jwksSource.documentRef", diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index bce7905514..2e976a4a1f 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -309,7 +309,7 @@ impl AccessConfig { IssuerNetworkPolicy::new(self.issuer.issuer.as_str(), self.issuer.allow_insecure_http) .map_err(|_| refused())?; let keys = match &self.issuer.jwks_source { - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let value = secrets .resolver() .map_err(|_| refused())? diff --git a/crates/registry-documents/src/config.rs b/crates/registry-documents/src/config.rs index cfc71de5fd..9e1b659374 100644 --- a/crates/registry-documents/src/config.rs +++ b/crates/registry-documents/src/config.rs @@ -608,7 +608,7 @@ impl RuntimeConfig { JwksFetcherConfig::defaults(), network.declared_jwks_fetch_policy(), ), - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets.resolve(document_ref).map_err(|error| { RuntimeConfigError::OidcJwksSecret(describe_secret_failure( "authentication.oidc.jwksSource.documentRef", diff --git a/crates/registry-evidence-oid4vp/src/auth.rs b/crates/registry-evidence-oid4vp/src/auth.rs index 2f12ca6c7e..809858bab6 100644 --- a/crates/registry-evidence-oid4vp/src/auth.rs +++ b/crates/registry-evidence-oid4vp/src/auth.rs @@ -113,7 +113,7 @@ impl TokenAuthenticator { policy, ) } - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets .resolve(document_ref) .map_err(|_| AuthSetupError::StaticKeySecret)?; diff --git a/crates/registry-evidence-oid4vp/src/config.rs b/crates/registry-evidence-oid4vp/src/config.rs index 09fa8f827b..30f6e508f8 100644 --- a/crates/registry-evidence-oid4vp/src/config.rs +++ b/crates/registry-evidence-oid4vp/src/config.rs @@ -1288,7 +1288,9 @@ impl VerifierDocument { ("/applicantTokens", &self.applicant_tokens.provider), ("/evidenceCredentials", &self.evidence_credentials.provider), ] { - if let JwksSource::Static { document_ref } = &provider.jwks_source { + if let JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } = + &provider.jwks_source + { if self .secret_providers .check_reference(pointer, document_ref) diff --git a/crates/registry-mcp/src/runtime.rs b/crates/registry-mcp/src/runtime.rs index 68cbb7d6d7..a74337a847 100644 --- a/crates/registry-mcp/src/runtime.rs +++ b/crates/registry-mcp/src/runtime.rs @@ -195,7 +195,7 @@ pub async fn build(config: &RuntimeConfig) -> Result { JwksFetcherConfig::defaults(), policy.declared_jwks_fetch_policy(), ), - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let bytes = secret( &secrets, document_ref, diff --git a/crates/registry-messaging/src/config.rs b/crates/registry-messaging/src/config.rs index a65cf11363..213aaadaa8 100644 --- a/crates/registry-messaging/src/config.rs +++ b/crates/registry-messaging/src/config.rs @@ -932,7 +932,8 @@ impl RuntimeConfig { policy, ) } - OidcJwksSource::Static { document_ref } => { + OidcJwksSource::Static { document_ref } + | OidcJwksSource::TestIssuer { document_ref } => { let document = secrets.resolve(document_ref).map_err(|error| { RuntimeConfigError::OidcJwksSecret(describe_secret_failure( "authentication.oidc.jwksSource.documentRef", diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index e8fcfd1ce0..31e5631664 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -532,10 +532,36 @@ pub enum JwksSource { #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] document_ref: String, }, + /// Read the key set from a secret, as `static` does, for a test issuer a + /// development run supervises. Development only: production refuses it. + TestIssuer { + #[serde(rename = "documentRef")] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + document_ref: String, + }, } registry_platform_yaml::tagged_union!(JwksSource); +static TEST_ISSUER: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.test-issuer", + key: "type", + summary: "The issuer's signing keys come from a test issuer", + production: + "Write jwksSource: {type: discovery}, or a static or uri source for the real issuer.", +}; + +impl DevelopmentClass for JwksSource { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&TEST_ISSUER]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + match self { + Self::Discovery {} | Self::Uri { .. } | Self::Static { .. } => None, + Self::TestIssuer { .. } => Some(&TEST_ISSUER), + } + } +} + impl Serialize for JwksSource { fn serialize(&self, serializer: S) -> Result { use serde::ser::SerializeMap; @@ -545,6 +571,9 @@ impl Serialize for JwksSource { Self::Static { document_ref } => { ("static", Some(("documentRef", document_ref.as_str()))) } + Self::TestIssuer { document_ref } => { + ("test-issuer", Some(("documentRef", document_ref.as_str()))) + } }; let mut map = serializer.serialize_map(Some(1 + usize::from(member.is_some())))?; map.serialize_entry("type", tag)?; @@ -593,7 +622,7 @@ impl JwksSource { )) } } - Self::Static { document_ref } => { + Self::Static { document_ref } | Self::TestIssuer { document_ref } => { if document_ref.is_empty() { let field = format!("{field}.documentRef"); Err(ConfigBlockError::new( @@ -617,11 +646,11 @@ impl JwksSource { } } - /// The secret reference a `static` source reads. + /// The secret reference a `static` or `test-issuer` source reads. #[must_use] pub fn document_ref(&self) -> Option<&str> { match self { - Self::Static { document_ref } => Some(document_ref), + Self::Static { document_ref } | Self::TestIssuer { document_ref } => Some(document_ref), _ => None, } } @@ -738,7 +767,11 @@ pub struct OidcIssuerConfig { pub audience: String, /// Where the issuer's signing keys come from. Absent reads the issuer's /// OpenID Connect discovery document. - #[serde(default)] + #[serde(default, deserialize_with = "deserialize_jwks_source")] + #[cfg_attr( + feature = "schema", + schemars(extend("x-registry-development-only" = ["platform.posture.test-issuer"])) + )] pub jwks_source: JwksSource, /// Permit plain HTTP beyond loopback to the configured issuer and to a /// JWKS URI declared in configuration. Loopback needs no setting. The @@ -780,6 +813,14 @@ fn deserialize_insecure_http<'de, D: Deserializer<'de>>(deserializer: D) -> Resu .map(|value| value.development_setting().is_some()) } +/// Read `jwksSource` through [`Gated`], so a loader that collects +/// development-only settings records a test issuer with its pointer. +fn deserialize_jwks_source<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result { + Gated::::deserialize(deserializer).map(Gated::into_inner) +} + impl OidcIssuerConfig { /// The issuer is an absolute `https` URL without credentials, query, or /// fragment, a loopback `http` one, or a plain `http` one when @@ -1486,6 +1527,10 @@ pub struct MetricsListenerConfig { pub enum TlsTermination { OperatorControlledUpstream, DevelopmentLoopback, + /// Plaintext on a loopback bind, behind a proxy on the same host. Valid + /// in every posture. It is placement only: it relaxes nothing a product + /// relaxes under `development-loopback`. + LoopbackPlaintext, } /// The operator-declared private network placement of an HTTP listener. @@ -1521,9 +1566,16 @@ impl PrivateListenerConfig { if address.is_multicast() { return false; } - if self.tls_termination == TlsTermination::DevelopmentLoopback { - return self.network_exposure == ListenerNetworkExposure::PrivateAddress - && address.is_loopback(); + match self.tls_termination { + TlsTermination::DevelopmentLoopback => { + return self.network_exposure == ListenerNetworkExposure::PrivateAddress + && address.is_loopback(); + } + TlsTermination::LoopbackPlaintext => { + return self.network_exposure == ListenerNetworkExposure::PrivateAddress + && registry_platform_loopback::loopback_address(address); + } + TlsTermination::OperatorControlledUpstream => {} } match (address, self.network_exposure) { (IpAddr::V4(address), ListenerNetworkExposure::PrivateAddress) => { diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 24cea8b96f..06da2d29d2 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -370,6 +370,97 @@ fn private_listener_follows_the_declared_boundary() { )); } +#[test] +fn loopback_plaintext_is_placement_only_and_follows_the_loopback_rule() { + use ListenerNetworkExposure::{ContainerPrivate, PrivateAddress}; + use TlsTermination::{DevelopmentLoopback, LoopbackPlaintext}; + let listener: PrivateListenerConfig = + read_block("bind: 127.0.0.1:8080\ntlsTermination: loopback-plaintext") + .expect("loopback-plaintext decodes"); + assert_eq!(listener.tls_termination, LoopbackPlaintext); + assert!(listener.is_valid()); + let unknown = read_block::( + "bind: 127.0.0.1:8080\ntlsTermination: loopback-plaintxt", + ); + assert!(unknown.is_err(), "a misspelt value is refused"); + + let valid = |bind: &str, tls, exposure| { + PrivateListenerConfig { + bind: bind.parse().unwrap(), + tls_termination: tls, + network_exposure: exposure, + } + .is_valid() + }; + for bind in ["127.0.0.1:1", "[::1]:1", "127.0.0.2:1"] { + assert!(valid(bind, LoopbackPlaintext, PrivateAddress), "{bind}"); + } + // The refusals match `development-loopback` for every bind and exposure. + for bind in [ + "127.0.0.1:1", + "[::1]:1", + "127.0.0.2:1", + "10.0.0.1:1", + "[fd00::1]:1", + "0.0.0.0:1", + "[::]:1", + "8.8.8.8:1", + "224.0.0.1:1", + ] { + for exposure in [PrivateAddress, ContainerPrivate] { + assert_eq!( + valid(bind, LoopbackPlaintext, exposure), + valid(bind, DevelopmentLoopback, exposure), + "{bind} {exposure:?}" + ); + } + } + assert!(!valid("10.0.0.1:1", LoopbackPlaintext, PrivateAddress)); + assert!(!valid("127.0.0.1:1", LoopbackPlaintext, ContainerPrivate)); + assert_eq!( + serde_json::to_value(LoopbackPlaintext).unwrap(), + "loopback-plaintext" + ); +} + +#[test] +fn test_issuer_reads_a_secret_reference_like_static_and_nothing_else() { + let source: JwksSource = + read_block("type: test-issuer\ndocumentRef: secret:env/TEST_JWKS").expect("decodes"); + assert_eq!( + source, + JwksSource::TestIssuer { + document_ref: "secret:env/TEST_JWKS".to_owned() + } + ); + assert_eq!(source.document_ref(), Some("secret:env/TEST_JWKS")); + source + .check("authentication.oidc", false) + .expect("a reference passes"); + let empty = JwksSource::TestIssuer { + document_ref: String::new(), + }; + assert_eq!( + empty + .check("authentication.oidc", false) + .expect_err("empty reference") + .field(), + "authentication.oidc.documentRef" + ); + assert_eq!( + serde_json::to_value(&source).unwrap(), + serde_json::json!({"type": "test-issuer", "documentRef": "secret:env/TEST_JWKS"}) + ); + for text in [ + "type: test-issuer", + "type: test-issuer\ndocumentRef: secret:env/X\nuri: https://x.example.test", + "type: test-issuer\ndocumentRef: secret:env/X\nunknown: 1", + "type: test-issuer\ndocumentRf: secret:env/X", + ] { + assert!(read_block::(text).is_err(), "{text}"); + } +} + #[test] fn sha256_label_shape() { assert!(is_sha256_label(&crate::sha256_uri(b"x"))); diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs index 6301f110f8..21dd03c21c 100644 --- a/crates/registry-platform-config/src/posture.rs +++ b/crates/registry-platform-config/src/posture.rs @@ -176,6 +176,15 @@ impl Gated { } } +impl Gated { + /// The value, whatever it selects, for a shared block that decodes a + /// member through the gate so the loader records it, and keeps the member + /// readable by products that have not adopted the posture. + pub(crate) fn into_inner(self) -> T { + self.0 + } +} + impl Gated { /// The value, when it is valid in every posture or the caller holds the /// witness. diff --git a/crates/registry-platform-config/src/posture_load_tests.rs b/crates/registry-platform-config/src/posture_load_tests.rs index c21dd2fdcf..ef21e0bc68 100644 --- a/crates/registry-platform-config/src/posture_load_tests.rs +++ b/crates/registry-platform-config/src/posture_load_tests.rs @@ -10,10 +10,11 @@ use serde::Deserialize; use crate::blocks::{ plaintext_permitted_with, AuditKeyConfig, AuditKeyCustody, DatabaseConfig, DatabaseHost, - DatabaseTransport, DatabaseTransportError, OidcIssuerConfig, + DatabaseTransport, DatabaseTransportError, JwksSource, OidcIssuerConfig, }; use crate::{ - DeclaredPosture, Posture, PostureSource, RuntimeConfigLoader, RuntimeEnvelope, DEFAULT_STAND_IN, + DeclaredPosture, Gated, Posture, PostureSource, RuntimeConfigLoader, RuntimeEnvelope, + DEFAULT_STAND_IN, }; const ENVELOPE: RuntimeEnvelope = RuntimeEnvelope { @@ -526,3 +527,99 @@ fn test_only_plaintext_is_refused_outside_test_builds() { ); assert_eq!(database(None, false).check(false), Ok(())); } + +/// A file whose issuer reads its keys from a test issuer. +fn test_issuer_file() -> String { + format!( + "{HEAD}database:\n runtimeUrlRef: secret:env/DB_RUNTIME\n migrationUrlRef: secret:env/DB_MIGRATION\nauthentication:\n oidc:\n issuer: https://issuer.example.test\n audience: api\n jwksSource:\n type: test-issuer\n documentRef: secret:env/TEST_JWKS\naudit:\n path: /var/lib/audit\n hashKeyRef: secret:env/AUDIT_KEY\n" + ) +} + +#[test] +fn production_refuses_a_test_issuer_with_its_code_and_pointer() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let error = parse(&loader, &test_issuer_file()).expect_err("production refuses"); + let diagnostics = error.diagnostics(); + let found = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == "platform.posture.test-issuer") + .unwrap_or_else(|| panic!("the test issuer is listed: {diagnostics:?}")); + assert_eq!(found.path, "/authentication/oidc/jwksSource"); + assert_eq!(found.severity, Severity::Error); + assert!(found.source.as_ref().unwrap().line.is_some()); + assert_eq!(diagnostics.len(), 1, "{diagnostics:?}"); +} + +#[test] +fn development_admits_a_test_issuer_lists_it_and_the_witness_reads_it() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)); + let loaded = parse(&loader, &test_issuer_file()).expect("development admits"); + let listed: Vec<(&str, Option<&str>)> = loaded + .posture + .settings() + .iter() + .map(|found| (found.setting.code, found.pointer.as_deref())) + .collect(); + assert_eq!( + listed, + [( + "platform.posture.test-issuer", + Some("/authentication/oidc/jwksSource") + )] + ); + let witness = loaded.development.as_ref().expect("a witness"); + let source = &loaded.config.authentication.oidc.provider.jwks_source; + assert_eq!(source.document_ref(), Some("secret:env/TEST_JWKS")); + let gated = Gated::everywhere(JwksSource::default()).expect("discovery is valid everywhere"); + assert!(gated.get(None).is_ok()); + let gated = Gated::for_tests(source.clone()); + assert_eq!( + gated.get(None).unwrap_err().setting.code, + "platform.posture.test-issuer" + ); + assert_eq!(gated.get(Some(witness)).unwrap(), source); +} + +#[test] +fn the_transitional_loader_reads_a_test_issuer_like_static() { + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE); + let loaded = parse(&loader, &test_issuer_file()).expect("the transitional loader admits"); + assert_eq!(loaded.posture.posture(), Posture::Production); + assert!(loaded.posture.settings().is_empty()); + let from_static = test_issuer_file().replace("type: test-issuer", "type: static"); + let loaded_static = parse(&loader, &from_static).expect("static loads"); + assert_eq!( + loaded + .config + .authentication + .oidc + .provider + .jwks_source + .document_ref(), + loaded_static + .config + .authentication + .oidc + .provider + .jwks_source + .document_ref() + ); +} + +#[test] +fn an_unknown_member_beside_a_test_issuer_is_refused() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)); + let text = test_issuer_file().replace( + " documentRef: secret:env/TEST_JWKS\n", + " documentRef: secret:env/TEST_JWKS\n uri: https://issuer.example.test/jwks\n", + ); + let error = parse(&loader, &text).expect_err("an unknown member"); + assert!( + error + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == "config.unknown-key"), + "{:?}", + error.diagnostics() + ); +} diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index a59ae79ec5..c528c69162 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -59,7 +59,8 @@ pub(crate) async fn verifier( network.declared_jwks_fetch_policy(), ) } - registry_platform_config::JwksSource::Static { document_ref } => { + registry_platform_config::JwksSource::Static { document_ref } + | registry_platform_config::JwksSource::TestIssuer { document_ref } => { let bytes = crate::runtime::resolve_secret(runtime, document_ref)?; let keys = registry_platform_oidc::parse_static_jwks(&bytes).map_err(|error| match error { diff --git a/crates/registry-render/src/runtime.rs b/crates/registry-render/src/runtime.rs index 03f126e354..c0943787ae 100644 --- a/crates/registry-render/src/runtime.rs +++ b/crates/registry-render/src/runtime.rs @@ -1123,6 +1123,7 @@ fn findings( matches!( oidc.provider.jwks_source, registry_platform_config::JwksSource::Static { .. } + | registry_platform_config::JwksSource::TestIssuer { .. } ) }); if needs_secrets @@ -1137,7 +1138,7 @@ fn findings( match (&runtime.authentication.oidc, &runtime.authentication.api_key_ref) { (Some(oidc), None) => { findings.extend([oidc.provider.check_without_posture("authentication.oidc", true), oidc.clients.check("authentication.oidc")].iter().filter_map(|result| result.as_ref().err()).map(block_finding)); - if let registry_platform_config::JwksSource::Static { document_ref } = &oidc.provider.jwks_source { + if let registry_platform_config::JwksSource::Static { document_ref } | registry_platform_config::JwksSource::TestIssuer { document_ref } = &oidc.provider.jwks_source { if let Err(error) = runtime.secret_providers.check_reference("authentication.oidc.jwksSource.documentRef", document_ref) { findings.push(block_finding(&error)); } } } diff --git a/crates/registry-scheduling/src/config.rs b/crates/registry-scheduling/src/config.rs index 56f57dd031..1acd894e26 100644 --- a/crates/registry-scheduling/src/config.rs +++ b/crates/registry-scheduling/src/config.rs @@ -1160,7 +1160,7 @@ impl RuntimeConfig { policy, ) } - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets.resolve(document_ref).map_err(|error| { RuntimeConfigError::OidcJwksSecret(describe_secret_failure( "authentication.oidc.jwksSource.documentRef", @@ -4428,6 +4428,43 @@ holdPolicy: ); } + /// `loopback-plaintext` places the listener on loopback in every posture + /// and relaxes nothing: a plain http issuer on loopback is admitted under + /// `development-loopback` and refused under `loopback-plaintext`. + #[test] + fn loopback_plaintext_places_the_listener_and_relaxes_nothing() { + let root = canonical_tempdir(); + let (_, base) = development(root.path()); + let load = |tls: &str, bind: &str, issuer: Option<&str>| { + let mut document = base.clone(); + document["listener"]["tlsTermination"] = serde_json::json!(tls); + document["listener"]["bind"] = serde_json::json!(bind); + if let Some(issuer) = issuer { + document["authentication"]["oidc"]["issuer"] = serde_json::json!(issuer); + } + RuntimeConfig::load(write_operator(root.path(), document)) + }; + + load("loopback-plaintext", "127.0.0.1:8105", None).expect("a loopback bind is admitted"); + for tls in ["development-loopback", "loopback-plaintext"] { + let error = load(tls, "10.20.30.40:8105", None).unwrap_err(); + assert_eq!( + refusal(&error), + ( + "scheduling.runtime.invalid-listener".to_owned(), + "/listener/bind".to_owned() + ), + "{tls}" + ); + } + + let issuer = "http://127.0.0.1:8082"; + load("development-loopback", "127.0.0.1:8105", Some(issuer)) + .expect("development-loopback admits a loopback http issuer"); + let error = load("loopback-plaintext", "127.0.0.1:8105", Some(issuer)).unwrap_err(); + assert_eq!(error.pointer(), "/authentication/oidc/issuer"); + } + /// The runtime's static JWKS arm hands the resolved document to the /// shared parser and refuses a key set it cannot trust before any /// verifier exists: a symmetric key, an unnamed key, two keys sharing a diff --git a/products/adapter/schemas/job-runtime.v1alpha1.schema.json b/products/adapter/schemas/job-runtime.v1alpha1.schema.json index 32093e776f..05c419c9a4 100644 --- a/products/adapter/schemas/job-runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/job-runtime.v1alpha1.schema.json @@ -993,11 +993,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "TrustProfile": { "additionalProperties": false, diff --git a/products/adapter/schemas/runtime.v1alpha1.schema.json b/products/adapter/schemas/runtime.v1alpha1.schema.json index c9a3ef65b3..e0bc59573f 100644 --- a/products/adapter/schemas/runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/runtime.v1alpha1.schema.json @@ -255,6 +255,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -353,7 +371,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] } }, "required": [ diff --git a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json index 7ecd14df72..712504ac38 100644 --- a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json @@ -261,6 +261,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -589,11 +607,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "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.", diff --git a/products/breg/generated/review-runtime/review-runtime.schema.json b/products/breg/generated/review-runtime/review-runtime.schema.json index 14a3d68106..dcb17ed224 100644 --- a/products/breg/generated/review-runtime/review-runtime.schema.json +++ b/products/breg/generated/review-runtime/review-runtime.schema.json @@ -396,11 +396,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "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.", diff --git a/products/breg/generated/runtime/runtime.schema.json b/products/breg/generated/runtime/runtime.schema.json index b6cc828e75..680738124e 100644 --- a/products/breg/generated/runtime/runtime.schema.json +++ b/products/breg/generated/runtime/runtime.schema.json @@ -778,6 +778,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -1604,7 +1622,10 @@ }, "jwksSource": { "$ref": "#/$defs/JwksSource", - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] }, "leewayMilliseconds": { "format": "uint64", diff --git a/products/casework/generated/runtime/runtime.schema.json b/products/casework/generated/runtime/runtime.schema.json index 9175ae0e65..8157541e5a 100644 --- a/products/casework/generated/runtime/runtime.schema.json +++ b/products/casework/generated/runtime/runtime.schema.json @@ -443,6 +443,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -566,7 +584,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] }, "maximumTokenLifetimeSeconds": { "description": "Optional deployment bound on the lifetime declared by an incoming\naccess token, independently of the issuer's own policy.", @@ -782,11 +803,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "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.", diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index 200f4b2b82..53250f3fb3 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -48,7 +48,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] }, "policies": { "additionalProperties": { @@ -840,6 +843,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -1025,11 +1046,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "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.", diff --git a/products/documents/generated/runtime/runtime.schema.json b/products/documents/generated/runtime/runtime.schema.json index 7933501e9e..4183fcd8bd 100644 --- a/products/documents/generated/runtime/runtime.schema.json +++ b/products/documents/generated/runtime/runtime.schema.json @@ -324,6 +324,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -429,7 +447,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] }, "scopeClaim": { "$ref": "#/$defs/ExternalId", @@ -644,11 +665,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "TransfersConfig": { "additionalProperties": false, diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index 06758de8d5..19607c4cb6 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -50,7 +50,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] }, "maximumTokenLifetimeSeconds": { "default": 900, @@ -380,7 +383,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] }, "maximumTokenLifetimeSeconds": { "default": 900, @@ -477,6 +483,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index a4aa7010e6..900259df1b 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -4716,7 +4716,7 @@ }, "artifact": { "path": "products/adapter/schemas/job-runtime.v1alpha1.schema.json", - "sha256": "948d893e3e3613e2577ad131ac07eac7440a66fcfd9368f7219636891245bda6", + "sha256": "039e8186453aaa3fc9b1fa0cb230172dfe58f05c7b240bfd03f3e5404ef0338c", "mediaType": "application/schema+json" } }, @@ -4896,7 +4896,7 @@ }, "artifact": { "path": "products/adapter/schemas/runtime.v1alpha1.schema.json", - "sha256": "de83cc5d1e6fd93c2a3f624ba02a44e7f8eaf08d2a48ec8ca8ad25aa1baae5f6", + "sha256": "51585af5aeff6da47672cfb2defc6a82b0da0a0fe748b09863e184c588c0f1c5", "mediaType": "application/schema+json" } }, @@ -5112,7 +5112,7 @@ }, "artifact": { "path": "products/breg/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "4a9161e749da012552829c6c6e1f58a365d457fd30db7bca4a4f6342e4af9318", + "sha256": "ee35b984ef1bf88adcd1e34d7940dae7f9d79c1da3dfdd77ee36433569b69e13", "mediaType": "application/schema+json" } }, @@ -5256,7 +5256,7 @@ }, "artifact": { "path": "products/breg/generated/review-runtime/review-runtime.schema.json", - "sha256": "4b912d75812d2ae988192dd50ca4ce54e9c72da2ba9e62b614aeff188b1cae92", + "sha256": "abdb67296c19d687187ce2fea55bef59a47d5212ec5bb3925dcbef35778d5fc8", "mediaType": "application/schema+json" } }, @@ -5292,7 +5292,7 @@ }, "artifact": { "path": "products/breg/generated/runtime/runtime.schema.json", - "sha256": "2e1a00a54542705141801fef4112443d715fdbde6842e2684fa801a3f5388392", + "sha256": "50c12375f8e3410c00d9dbfc9d7460370e0c69a757992975fa5fa96189e06fe7", "mediaType": "application/schema+json" } }, @@ -5400,7 +5400,7 @@ }, "artifact": { "path": "products/casework/generated/runtime/runtime.schema.json", - "sha256": "035b9d0040bf61f7bfff4f8827547e711b05bdafe2b5da4561f73db46dbf85c1", + "sha256": "0c6aef414ad9becb38794ad1eb0b00b3c8220b507670e27de6b79da710f9b787", "mediaType": "application/schema+json" } }, @@ -5436,7 +5436,7 @@ }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", - "sha256": "a6da5b7691382e9e412b9e67233228d6c18bf76a44cad0fd75c3b1dbbdae7429", + "sha256": "e2c774bceda48bfd6814629e779fee5a9613ac82b3c72ccd4a915d0c4e4dd1ee", "mediaType": "application/schema+json" } }, @@ -5616,7 +5616,7 @@ }, "artifact": { "path": "products/documents/generated/runtime/runtime.schema.json", - "sha256": "1207d9ae54688fbc9b2cf69a75baed8008b0eedb0bfd8c7722629726e43016bc", + "sha256": "4d22626676c3d535dcca2c86c2d0f675b52b8dce81e3040ddee0462e7ed90420", "mediaType": "application/schema+json" } }, @@ -5796,7 +5796,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "6efae3b628362ddeb7c9e470cb7ee9c0dcd9b61431580836cf873d45c21b75dd", + "sha256": "b6ecde469f66120d97fbfb2840fecd42c564642510bda26b98b26ee7ab13cdfa", "mediaType": "application/schema+json" } }, @@ -6012,7 +6012,7 @@ }, "artifact": { "path": "products/messaging/generated/runtime/runtime.schema.json", - "sha256": "6d75d4e0abeeae4b5b6dfbec8d6fdc6576199654ff5f8b4720dea634230ee241", + "sha256": "a91a90441db07340c50710d3bf2aa1a4d3eaf034af0ff1bda7eaa5ea299e09db", "mediaType": "application/schema+json" } }, @@ -6156,7 +6156,7 @@ }, "artifact": { "path": "products/platform/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "2a4c006f8666d8ec3f9d1a9a511041525753ffa97526f4275ce22a64ca0c4531", + "sha256": "9c10f7ac0154005eca148084abf7a0e1980642fbea9e8f2fa30da1c8d5fffa49", "mediaType": "application/schema+json" } }, @@ -6264,7 +6264,7 @@ }, "artifact": { "path": "products/render/schemas/runtime.schema.json", - "sha256": "dbf6eb70c49c15e54ad435adc77446eebbe2a1dbd16f2eb707465c6bc89effd6", + "sha256": "dfcd05130394e2dec5b8c9d739b2c8c60b680cb399a94c406125f80a707ae5f1", "mediaType": "application/schema+json" } }, @@ -6372,7 +6372,7 @@ }, "artifact": { "path": "products/scheduling/generated/runtime/runtime.schema.json", - "sha256": "319d14d8c66ea2eee3d77577d0b8924478b4b5e86893dce390533298cd9910d1", + "sha256": "27a6be5ada98978ac33e80e9054540b65c091748e9548744922d08e917ebd739", "mediaType": "application/schema+json" } }, diff --git a/products/messaging/generated/runtime/runtime.schema.json b/products/messaging/generated/runtime/runtime.schema.json index 152461c5cc..6a4481d1b1 100644 --- a/products/messaging/generated/runtime/runtime.schema.json +++ b/products/messaging/generated/runtime/runtime.schema.json @@ -521,6 +521,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -626,7 +644,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] }, "scopeClaim": { "default": "scope", @@ -930,11 +951,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "TlsTrustProfileConfig": { "additionalProperties": false, diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index eb3b883f45..73991b2494 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -62,6 +62,22 @@ the new members yet, and a runtime that has not adopted the posture behaves as before. +- The shared private listener adds `tlsTermination: loopback-plaintext`: + plaintext on a loopback bind behind a proxy on the same host, valid in + every posture. It is placement only. A non-loopback bind is refused as under + `development-loopback`, and it relaxes nothing a runtime relaxes under + `development-loopback`. The shared OIDC issuer block adds + `jwksSource: {type: test-issuer, documentRef: }`, which + reads the key set from the secret like `static`, for a development run's + test issuer. A posture-aware load refuses it in production with + `platform.posture.test-issuer` and admits and lists it in development. A + runtime that has not adopted the posture reads it like `static`, and + Evidence, which reads access-token keys only from `uri`, refuses it. The + shared and product runtime schemas gain both values. Migration: add + `JwksSource::TestIssuer { document_ref }` beside `Static { document_ref }` + in an exhaustive match, and a `LoopbackPlaintext` arm where + `TlsTermination` is matched exhaustively. + - `registry-cli-report` adds `Report::with_posture`, which writes `posture.value` and `posture.source` (`flag`, `environment` or `default`) into a CLI report body after the command members. A report built without it diff --git a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json index 8f1cdc5b7c..4e611deea9 100644 --- a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json @@ -349,6 +349,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -800,11 +818,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "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.", diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index f4238f38f8..53e54c7b4b 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -209,6 +209,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -393,7 +411,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] } }, "required": [ @@ -593,11 +614,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "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.", diff --git a/products/render/schemas/runtime.schema.json b/products/render/schemas/runtime.schema.json index bcc483eb62..df91dbfad2 100644 --- a/products/render/schemas/runtime.schema.json +++ b/products/render/schemas/runtime.schema.json @@ -216,6 +216,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -406,7 +424,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] } }, "required": [ diff --git a/products/scheduling/generated/runtime/runtime.schema.json b/products/scheduling/generated/runtime/runtime.schema.json index fdbfcc1afe..a3d1a69b97 100644 --- a/products/scheduling/generated/runtime/runtime.schema.json +++ b/products/scheduling/generated/runtime/runtime.schema.json @@ -348,6 +348,24 @@ "documentRef" ], "type": "object" + }, + { + "additionalProperties": false, + "description": "Read the key set from a secret, as `static` does, for a test issuer a\ndevelopment run supervises. Development only: production refuses it.", + "properties": { + "documentRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "test-issuer", + "type": "string" + } + }, + "required": [ + "type", + "documentRef" + ], + "type": "object" } ] }, @@ -469,7 +487,10 @@ "default": { "type": "discovery" }, - "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document." + "description": "Where the issuer's signing keys come from. Absent reads the issuer's\nOpenID Connect discovery document.", + "x-registry-development-only": [ + "platform.posture.test-issuer" + ] }, "readsScope": { "default": "scheduling:read", @@ -847,11 +868,20 @@ }, "TlsTermination": { "description": "Declares the trusted transport boundary for a runtime's plaintext HTTP\nlistener. Production listeners require operator-controlled upstream TLS\ntermination; direct plaintext is limited to the explicit loopback-only\ndevelopment mode.", - "enum": [ - "operator-controlled-upstream", - "development-loopback" - ], - "type": "string" + "oneOf": [ + { + "enum": [ + "operator-controlled-upstream", + "development-loopback" + ], + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "Plaintext on a loopback bind, behind a proxy on the same host. Valid\nin every posture. It is placement only: it relaxes nothing a product\nrelaxes under `development-loopback`.", + "type": "string" + } + ] }, "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.", From 3c93fcb5e94aa21e743a69082c7649aad14813e1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:31:54 +0100 Subject: [PATCH 065/136] test: expect the Adapter release image and a refused start for a reserved probe path The release packaging test lists the Adapter among the images the build script accepts. A project whose binding would take the health or ready path now fails the workspace check at startup, so the health-route test asserts the refusal and that no source request was made. Signed-off-by: Jeremi Joslin --- .../registry-adapter/tests/health_routes.rs | 44 +++++++------------ release/scripts/test_registry_release.py | 2 +- 2 files changed, 17 insertions(+), 29 deletions(-) diff --git a/crates/registry-adapter/tests/health_routes.rs b/crates/registry-adapter/tests/health_routes.rs index 7497faa650..3dc3612411 100644 --- a/crates/registry-adapter/tests/health_routes.rs +++ b/crates/registry-adapter/tests/health_routes.rs @@ -14,7 +14,6 @@ use std::io::{Read, Write}; use std::net::TcpStream; use std::time::Duration; -use registry_adapter::engine::effective_contract::WELL_KNOWN_PATH; use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use served_harness::upstream::UpstreamDouble; use served_harness::{copy_example_project, replace_profile_text, Served}; @@ -201,11 +200,8 @@ async fn probes_append_no_journal_row() { } #[tokio::test] -async fn a_project_declaring_health_or_ready_is_unserved_with_the_reserved_path_reason() { - for (record_type, probe_path, body) in [ - ("health", HEALTH_PATH, HEALTH_BODY), - ("ready", READY_PATH, READY_BODY), - ] { +async fn a_project_declaring_health_or_ready_refuses_to_start() { + for record_type in ["health", "ready"] { let upstream = UpstreamDouble::start(); let directory = tempfile::tempdir().expect("a copied Adapter project"); copy_example_project(directory.path()); @@ -220,29 +216,21 @@ async fn a_project_declaring_health_or_ready_is_unserved_with_the_reserved_path_ std::fs::write(&project_path, project.replace("person", record_type)) .expect("write the colliding project"); - let served = Served::start_with_project(&upstream.url(""), directory.path()).await; - assert_probe(&raw(&served, "GET", probe_path, None), 200, body); - - let token = served.token(""); - let readback = served.get(WELL_KNOWN_PATH, Some(&token)); - assert_eq!(readback.0, 200, "{}", readback.2); - let unserved = readback.2["contract"]["unserved"] - .as_array() - .expect("the contract carries unserved operations"); - let colliding: Vec<_> = unserved - .iter() - .filter(|entry| entry["reasonCode"] == "adapter.operation.reserved-facade-path") - .collect(); + // The workspace check refuses the colliding binding before the facade + // builds a router, so the probe route is never shadowed. + let stderr = Served::refusal_with_project(&upstream.url(""), directory.path()).await; assert!( - !colliding.is_empty(), - "{probe_path} is refused as reserved: {unserved:?}" + stderr.contains("the workspace check refused the deployment"), + "{record_type}: {stderr}" + ); + assert!( + stderr.contains("adapter.project.reserved-facade-path"), + "{record_type}: {stderr}" + ); + assert_eq!( + upstream.request_count(), + 0, + "a refused deployment performs no source I/O" ); - for entry in colliding { - assert_eq!( - entry["reason"], - "the facade path is reserved for the Adapter effective-contract, health and ready routes" - ); - } - assert_eq!(upstream.request_count(), 0); } } diff --git a/release/scripts/test_registry_release.py b/release/scripts/test_registry_release.py index 45b79ee0a9..972276ff0e 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -3489,7 +3489,7 @@ def test_release_packaging_uses_retained_artifact_identities(self) -> None: ) self.assertNotIn("THIRD_PARTY_NOTICES", release_dockerfiles["discovery"]) self.assertIn( - "discovery|evidence|evidence-oid4vci|registry-render|breg|breg-mcp|breg-review|casework|scheduling|messaging|coordinator)", + "discovery|evidence|evidence-oid4vci|registry-render|breg|breg-mcp|breg-review|casework|scheduling|messaging|coordinator|adapter)", image_recipe, ) self.assertNotIn("registry-relay)", image_recipe) From a7780af41985820962dc8f5764e1d6354d932dd0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:41:48 +0100 Subject: [PATCH 066/136] feat(adapter): create the Adapter database and roles with adapterctl provision adapterctl provision reads the runtime file and creates the migration role, the runtime role and the database over verified TLS as a non-superuser administrator, or prints the script with --print-sql. It converges on a second run and refuses a role whose password differs from its URL. The Adapter dependency gate admits the shared CLI report crate that the provision verb links. The shared --runtime-config help no longer names a verb that Adapter does not have, and the CLI and identifier catalogs are regenerated. Signed-off-by: Jeremi Joslin --- Cargo.lock | 3 + crates/registry-adapterctl/Cargo.toml | 12 + crates/registry-adapterctl/src/lib.rs | 27 +- crates/registry-adapterctl/src/provision.rs | 105 +++++++ .../tests/provision_cli.rs | 193 +++++++++++++ .../tests/provision_postgres.rs | 270 ++++++++++++++++++ crates/registry-cli-docs/catalog.json | 108 ++++++- crates/registry-platform-provision/src/cli.rs | 2 +- .../site/src/content/docs/operate/adapter.mdx | 46 +++ products/adapter/AGENTS.md | 4 + products/adapter/CHANGELOG.md | 7 + .../scripts/check_dependency_direction.py | 4 +- .../scripts/test_dependency_direction.py | 18 ++ .../identifiers/generated/catalog.v1.json | 2 +- 14 files changed, 791 insertions(+), 10 deletions(-) create mode 100644 crates/registry-adapterctl/src/provision.rs create mode 100644 crates/registry-adapterctl/tests/provision_cli.rs create mode 100644 crates/registry-adapterctl/tests/provision_postgres.rs diff --git a/Cargo.lock b/Cargo.lock index 6cd4041082..782729f702 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6156,6 +6156,7 @@ dependencies = [ "registry-platform-buildinfo", "registry-platform-config", "registry-platform-httputil", + "registry-platform-provision", "registry-platform-script", "registry-platform-yaml", "registry-record", @@ -6164,7 +6165,9 @@ dependencies = [ "serde_json", "tempfile", "tokio", + "tokio-postgres", "tokio-rustls", + "uuid", "zeroize", ] diff --git a/crates/registry-adapterctl/Cargo.toml b/crates/registry-adapterctl/Cargo.toml index ea6fa6f302..0432882102 100644 --- a/crates/registry-adapterctl/Cargo.toml +++ b/crates/registry-adapterctl/Cargo.toml @@ -19,6 +19,10 @@ workspace = true # Enables only the platform's pinned-loopback HTTPS profile for the real TLS # verify tests. Default and release builds retain production address policy. tls-test = ["registry-platform-httputil/test-support"] +# Gates the suite that needs a disposable PostgreSQL server offering verified +# TLS (tests/provision_postgres.rs), so a plain cargo test run never fails +# for want of one and never silently skips it either. +postgres-test = [] [dependencies] base64.workspace = true @@ -37,6 +41,7 @@ registry-payment-mifos-connector.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config = { workspace = true, features = ["schema"] } registry-platform-httputil.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-script.workspace = true registry-platform-yaml.workspace = true schemars.workspace = true @@ -48,6 +53,13 @@ zeroize.workspace = true [dev-dependencies] jsonschema.workspace = true rcgen.workspace = true +registry-platform-provision = { workspace = true, features = ["test-support"] } registry-record.workspace = true tempfile.workspace = true +tokio-postgres.workspace = true tokio-rustls.workspace = true +uuid.workspace = true + +[[test]] +name = "provision_postgres" +required-features = ["postgres-test"] diff --git a/crates/registry-adapterctl/src/lib.rs b/crates/registry-adapterctl/src/lib.rs index 97bf7ce62c..eefaa46d3b 100644 --- a/crates/registry-adapterctl/src/lib.rs +++ b/crates/registry-adapterctl/src/lib.rs @@ -5,7 +5,7 @@ //! This crate owns the `adapterctl` binary. Its commands: `check`, the //! offline check over authored artifacts (project, profile, pack, fixtures, //! and with `--runtime` the runtime config); `job check`, the offline -//! compile of one ingestion job; `job lock`, the job's pin rewriter; `mapping check`, `mapping generate`, and +//! compile of one ingestion job; `provision`, the creation of the roles and the database the runtime file names; `job lock`, the job's pin rewriter; `mapping check`, `mapping generate`, and //! `mapping preview`, the checks, script generator, and offline preview of //! an `AdapterMapping` model; `project lock`, the pin rewriter; `schemas`, the generator and drift gate of the Adapter format //! JSON Schemas; `compile`, the per-deployment contract compiler; @@ -25,6 +25,7 @@ mod mapping; mod payment_fixtures; mod payments; mod project; +mod provision; mod report; mod schemas; mod verify; @@ -70,6 +71,8 @@ enum Command { Project(project::ProjectArgs), /// Check typed payment connections or export their fixed operation contract. Payments(payments::PaymentsArgs), + /// Create the roles and the database the runtime file names, or print the SQL. + Provision(registry_platform_provision::ProvisionArgs), /// Write the generated JSON Schemas of every Adapter format, or /// check the committed ones for drift. Schemas(schemas::SchemasArgs), @@ -144,6 +147,9 @@ where } }; let Cli { format, command } = cli; + if let Command::Provision(args) = &command { + return provision(args, format); + } let command_name = match &command { Command::Check(_) => "check", Command::Job(job) => match job.command { @@ -154,6 +160,7 @@ where Command::Project(project) => match project.command { project::ProjectCommand::Lock(_) => "project lock", }, + Command::Provision(_) => "provision", Command::Schemas(_) => "schemas", Command::Payments(args) => payments::command_name(&args.command), Command::Compile(_) => "compile", @@ -172,6 +179,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::Provision(_) => unreachable!("provision writes its own report above"), 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), @@ -184,6 +192,23 @@ where } } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: ®istry_platform_provision::ProvisionArgs, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "adapterctl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + shared, + provision::load, + ) +} + fn usage_failure(message: String) -> Value { failure( "usage", diff --git a/crates/registry-adapterctl/src/provision.rs b/crates/registry-adapterctl/src/provision.rs new file mode 100644 index 0000000000..a53ee854da --- /dev/null +++ b/crates/registry-adapterctl/src/provision.rs @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `adapterctl provision`: the shared command over the Adapter's runtime +//! file. The file's two database URLs name the roles, the database and both +//! passwords, so nothing is written twice. + +use std::path::Path; + +use registry_adapter_core::{ + AdapterRuntimeConfig, ADAPTER_REMOVED_KEYS, ADAPTER_RUNTIME_API_VERSION, ADAPTER_RUNTIME_KIND, +}; +use registry_platform_config::{ + describe_secret_failure, RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, SecretResolver, +}; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +/// The Adapter keeps its tables in the schema on the migration role's search +/// path, handed to the migration role, and needs no extension. +fn product() -> ProductDatabase { + ProductDatabase { + product: "adapter", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } +} + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(ADAPTER_RUNTIME_KIND.to_owned()); + Box::new(diagnostic) +} + +/// Reads the runtime file exactly as `adapter serve` does and resolves the +/// two database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path) -> Result> { + let absolute = std::fs::canonicalize(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be read".to_owned(), + "Pass --runtime-config as a path to the runtime file.", + ) + })?; + let config = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { + api_version: ADAPTER_RUNTIME_API_VERSION, + kind: ADAPTER_RUNTIME_KIND, + }) + .removed_keys(ADAPTER_REMOVED_KEYS) + .load::(&absolute) + .map_err(|error| Box::new(error.deciding_diagnostic().clone()))? + .config; + let secrets = match config.secret_providers.as_ref() { + Some(providers) => providers.resolver(), + None => SecretResolver::new([SecretProvider::Environment], ""), + } + .map_err(|error| { + refused( + "config.refused", + "/secretProviders", + error.to_string(), + "Correct secretProviders in the runtime file, then run provision again.", + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refused( + "config.refused", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; + let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let ca_pem = config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + Ok(ProvisionInput { + product: product(), + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-adapterctl/tests/provision_cli.rs b/crates/registry-adapterctl/tests/provision_cli.rs new file mode 100644 index 0000000000..0f62a2cc73 --- /dev/null +++ b/crates/registry-adapterctl/tests/provision_cli.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `adapterctl provision` without a database: print mode reads the runtime +//! file and writes the script without connecting or printing a password, and +//! the administrator flags refuse the combinations the shared command +//! refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file whose secret files name a migration and a runtime login on +/// one server that does not exist, so a connection attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!("postgresql://adapter_migration:{MIGRATION_PASSWORD}@db.invalid:5432/adapter"), + ), + ( + "runtime-database-url", + format!("postgresql://adapter_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/adapter"), + ), + ( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), + ), + ("cursor-key", "0123456789abcdef0123456789abcdef".to_owned()), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/adapter/runtime/v1alpha1 +kind: AdapterRuntimeConfig +id: adapter-provision-cli-test +endpoints: + - endpoint: tracker + baseUrl: https://192.168.1.10 + credential: + type: basic + usernameRef: secret:file/jwks.json + passwordRef: secret:file/jwks.json +secretProviders: + file: + root: {secrets} +listener: + bind: 127.0.0.1:0 +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url +oidc: + issuer: https://identity.example.test + audience: urn:example:adapter + jwksSource: + type: static + documentRef: secret:file/jwks.json +allowedClients: + - provision-test-client +allowedPrivateCidrs: + - 192.168.0.0/16 +audit: + retentionDays: 90 +idempotency: + responseRetentionSeconds: 86400 +cursorKeyRef: secret:file/cursor-key +", + secrets = secrets.display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_adapterctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in ["adapter_migration", "adapter_runtime", "adapter"] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "adapter"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "adapter"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } +} + +#[test] +fn a_runtime_file_the_loader_refuses_is_reported_without_connecting() { + let directory = scratch(); + let runtime = directory.path().join("runtime.yaml"); + std::fs::write(&runtime, "kind: AdapterRuntimeConfig\n").unwrap(); + std::fs::set_permissions(&runtime, std::fs::Permissions::from_mode(0o600)).unwrap(); + let output = ctl(&[ + "provision", + "--runtime-config", + runtime.to_str().unwrap(), + "--print-sql", + ]); + assert_ne!(output.status.code(), Some(0)); + assert!(output.stdout.is_empty()); +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for arguments in [ + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "ADAPTER_ADMIN_URL", + ], + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "ADAPTER_ADMIN_URL", + ], + vec!["provision", "--runtime-config", &runtime], + ] { + let output = ctl(&arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty(), "{arguments:?}"); + } +} diff --git a/crates/registry-adapterctl/tests/provision_postgres.rs b/crates/registry-adapterctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..70fbaba022 --- /dev/null +++ b/crates/registry-adapterctl/tests/provision_postgres.rs @@ -0,0 +1,270 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `adapterctl provision` against a real server, then `adapter serve` on what +//! it created: the facade migrates as the migration role, grants the runtime +//! role what its deployment uses, and listens with split roles and no hand +//! SQL. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. The administrator sessions of this suite +//! use verified TLS, so the server must offer it. Without the variables the +//! test fails on the spot: a skipped database test is not database +//! verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Duration; + +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use serde_json::Value; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use uuid::Uuid; + +fn repository(relative: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../..") + .join(relative) +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&str]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_adapterctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stdout))); + (output.status.code().unwrap(), report) +} + +/// Read one HTTP status code from `GET path`, or none when nothing answers. +async fn http_status(address: &str, path: &str) -> Option { + let mut stream = tokio::net::TcpStream::connect(address).await.ok()?; + stream + .write_all( + format!("GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await + .ok()?; + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.ok()?; + let text = String::from_utf8_lossy(&response); + text.split_whitespace().nth(1)?.parse().ok() +} + +/// `provision` as the operate page runs it, from the administrator URL of a +/// non-superuser that holds only `CREATEROLE` and `CREATEDB`, over a runtime +/// file whose two URLs name the roles and the database. `adapter serve` then +/// migrates over the migration credential, grants the runtime role its +/// privileges, and answers a request over the runtime credential. +#[tokio::test] +async fn provision_then_serve_with_split_roles() { + let (base_url, ca) = provision_test_env(); + let admin = connect_verified(&base_url, &ca, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let secret = |name: &str, value: &str| { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + }; + secret("cursor-key", "0123456789abcdef0123456789abcdef"); + secret("upstream-user", "upstream-user"); + secret("upstream-password", "upstream-password"); + // The runtime verifies tokens against a static key set, so it starts + // without reaching the issuer. + secret( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + ); + secret("postgres-ca.pem", &String::from_utf8_lossy(&ca)); + + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let bind = format!("127.0.0.1:{port}"); + let runtime_file = directory.path().join("runtime.yaml"); + std::fs::write( + &runtime_file, + format!( + "\ +apiVersion: id.registrystack.org/formats/adapter/runtime/v1alpha1 +kind: AdapterRuntimeConfig +id: adapter-provision-test +endpoints: + - endpoint: tracker + baseUrl: https://192.168.1.10 + credential: + type: basic + usernameRef: secret:file/upstream-user + passwordRef: secret:file/upstream-password +secretProviders: + file: + root: {secrets} +listener: + bind: {bind} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/postgres-ca.pem +oidc: + issuer: https://identity.example.test + audience: urn:example:adapter + jwksSource: + type: static + documentRef: secret:file/jwks.json +allowedClients: + - provision-test-client +allowedPrivateCidrs: + - 192.168.0.0/16 +audit: + retentionDays: 90 +idempotency: + responseRetentionSeconds: 86400 +cursorKeyRef: secret:file/cursor-key +", + secrets = secrets.display(), + ), + ) + .unwrap(); + let runtime = runtime_file.display().to_string(); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let (owner, migration, runtime_role, database) = ( + format!("adapter_owner_{suffix}"), + format!("adapter_mig_{suffix}"), + format!("adapter_rt_{suffix}"), + format!("adapter_db_{suffix}"), + ); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let (owner_password, migration_password, runtime_password) = ( + password("owner"), + password("migration"), + password("runtime"), + ); + admin + .batch_execute(&format!( + "CREATE ROLE {owner} LOGIN PASSWORD '{owner_password}' NOSUPERUSER CREATEROLE CREATEDB" + )) + .await + .unwrap(); + + let base = registry_platform_provision::admin_config(&base_url, Some(&ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, db_port) = (base.host(), base.port()); + let url = |role: &str, password: &str, database: &str| { + format!("postgresql://{role}:{password}@{host}:{db_port}/{database}") + }; + secret( + "migration-database-url", + &url(&migration, &migration_password, &database), + ); + secret( + "runtime-database-url", + &url(&runtime_role, &runtime_password, &database), + ); + let admin_file = directory.path().join("admin-url"); + std::fs::write(&admin_file, url(&owner, &owner_password, "postgres")).unwrap(); + std::fs::set_permissions(&admin_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let (code, provisioned) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], database.as_str()); + for secret in [&owner_password, &migration_password, &runtime_password] { + assert!( + !provisioned.to_string().contains(secret.as_str()), + "the report holds no password" + ); + } + + let (code, again) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "a second run converges: {again:#}"); + + let server = tokio::spawn({ + let project = repository("products/adapter/examples/dhis2-tracker"); + let profile = repository("products/adapter/profiles/breg-records/profile.yaml"); + let pack = repository("products/adapter/packs/dhis2-tracker/pack.yaml"); + let runtime = runtime_file.clone(); + async move { + registry_adapter::serve::run(&project, Some(&profile), Some(&pack), &runtime).await + } + }); + // An unauthenticated request reaches the facade and is refused by its + // authenticator, so a 401 shows the runtime role serving. + let route = "/.well-known/registry-adapter/effective-contract"; + let mut status = None; + for _ in 0..300 { + if server.is_finished() { + break; + } + status = http_status(&bind, route).await; + if status.is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + if server.is_finished() { + let outcome = server.await.expect("the server task does not panic"); + panic!("the facade stopped instead of serving: {outcome:?}"); + } + assert_eq!(status, Some(401), "the facade never answered"); + server.abort(); + + // The runtime role holds what the deployment uses and nothing on the + // migration ledger of the idempotency store. + let runtime_session = + connect_verified(&url(&runtime_role, &runtime_password, &database), &ca, None).await; + let granted = runtime_session + .query_one( + "SELECT has_table_privilege(current_user, 'adapter_journal_events', 'INSERT'), \ + has_table_privilege(current_user, 'adapter_idempotency_schema_migrations', 'SELECT')", + &[], + ) + .await + .unwrap(); + assert!(granted.get::<_, bool>(0), "the journal is writable"); + assert!( + !granted.get::<_, bool>(1), + "the idempotency migration ledger is not readable" + ); + drop(runtime_session); + + for statement in [ + format!("DROP DATABASE {database} WITH (FORCE)"), + format!("DROP ROLE {runtime_role}"), + format!("DROP ROLE {migration}"), + format!("DROP ROLE {owner}"), + ] { + admin.batch_execute(&statement).await.unwrap(); + } +} diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index d8b70967a7..11c94f6978 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -1744,6 +1744,102 @@ } ] }, + { + "name": "provision", + "invocation": "adapterctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", + "long_about": null, + "usage": "adapterctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one the service runs with", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "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": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "schemas", "invocation": "adapterctl schemas", @@ -5551,7 +5647,7 @@ "options": [ { "display": "--runtime-config ", - "description": "Runtime configuration file, the one `apply` reads. A symbolic link at any component of this path is refused.", + "description": "Runtime configuration file, the one the service runs with. A symbolic link at any component of this path is refused.", "always_required": true, "repeatable": false, "default_values": [], @@ -10313,7 +10409,7 @@ "options": [ { "display": "--runtime-config ", - "description": "Runtime configuration file, the one `apply` reads", + "description": "Runtime configuration file, the one the service runs with", "always_required": true, "repeatable": false, "default_values": [], @@ -12548,7 +12644,7 @@ }, { "display": "--runtime-config ", - "description": "Runtime configuration file, the one `apply` reads", + "description": "Runtime configuration file, the one the service runs with", "always_required": false, "repeatable": false, "default_values": [], @@ -14279,7 +14375,7 @@ "options": [ { "display": "--runtime-config ", - "description": "Runtime configuration file, the one `apply` reads", + "description": "Runtime configuration file, the one the service runs with", "always_required": true, "repeatable": false, "default_values": [], @@ -21283,7 +21379,7 @@ "options": [ { "display": "--runtime-config ", - "description": "Runtime configuration file, the one `apply` reads", + "description": "Runtime configuration file, the one the service runs with", "always_required": true, "repeatable": false, "default_values": [], @@ -26314,7 +26410,7 @@ "options": [ { "display": "--runtime-config ", - "description": "Runtime configuration file, the one `apply` reads", + "description": "Runtime configuration file, the one the service runs with", "always_required": true, "repeatable": false, "default_values": [], diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs index 9d2e4d23fd..7b7509b20a 100644 --- a/crates/registry-platform-provision/src/cli.rs +++ b/crates/registry-platform-provision/src/cli.rs @@ -42,7 +42,7 @@ pub enum OutputFormat { /// `--format` flag, passed to [`run_provision`]. #[derive(clap::Args, Debug, Clone)] pub struct ProvisionArgs { - /// Runtime configuration file, the one `apply` reads + /// Runtime configuration file, the one the service runs with #[arg(long, value_name = "FILE")] pub runtime_config: PathBuf, /// File holding the administrator PostgreSQL URL diff --git a/docs/site/src/content/docs/operate/adapter.mdx b/docs/site/src/content/docs/operate/adapter.mdx index f91aa9fed1..77cdbefb03 100644 --- a/docs/site/src/content/docs/operate/adapter.mdx +++ b/docs/site/src/content/docs/operate/adapter.mdx @@ -59,6 +59,52 @@ You build it from a reviewed source checkout (see [Build the job host](#build-th {/* Evidence: docs/site/src/data/cli-reference.yaml source_build_only_binaries. */} +## Provision PostgreSQL + +Your runtime file already names the roles, their passwords and the database. They are the URLs in +`database.migrationUrlRef` and `database.runtimeUrlRef`. +Put both URLs in their secret files, then run `adapterctl provision` once as a PostgreSQL role that +can create roles and databases: + +```sh +adapterctl provision --runtime-config runtime.yaml --admin-url-file admin-url +``` + +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. +The administrator needs `CREATEROLE` and `CREATEDB` and does not need to be a superuser. +To pass the URL in an environment variable instead, use `--admin-url-env NAME`. +The connection requires TLS and verifies the server certificate. +Set `database.caBundleRef` in the runtime file to trust a private CA. +The command never prints the administrator URL or a password. + +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it + from `PUBLIC`. + +Run it again at any time. +It creates only what is missing. +It refuses a role that exists with a different password than its URL holds, and tells you which role. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. +The command connects to nothing and prints the script, with a `\password` prompt after each +`CREATE ROLE` so the script holds no password. +Add `--format json` for a report of each statement and its outcome. + +`provision` grants the runtime role nothing beyond `CONNECT`. +`adapter serve` grants the table privileges when it starts, as the next section describes. +An administrator that is not a superuser becomes a member of the roles it creates, holding +`ADMIN OPTION`, and that membership does not stop the grant. + +{/* Evidence: crates/registry-adapterctl/src/provision.rs; + crates/registry-adapterctl/tests/provision_cli.rs; + crates/registry-adapterctl/tests/provision_postgres.rs provision_then_serve_with_split_roles. */} + ## Grant the runtime database role The facade journals every request and, when it serves a write, keeps idempotency state in diff --git a/products/adapter/AGENTS.md b/products/adapter/AGENTS.md index a16f09f45b..7f30979aa4 100644 --- a/products/adapter/AGENTS.md +++ b/products/adapter/AGENTS.md @@ -82,6 +82,10 @@ bad-authoring corpus. `test-postgres.sh` runs the adapter crates' `postgres-test` suites: without `ADAPTER_TEST_DATABASE_URL` it starts and removes its own loopback PostgreSQL 17 container; with the variable set it uses that server as given. +The `provision_postgres` target of `registry-adapterctl` (feature `postgres-test`) +needs `PROVISION_TEST_DATABASE_URL`, a disposable superuser URL +(`sslmode=verify-full` on a server that offers verified TLS), and +`PROVISION_TEST_DATABASE_CA`, the path of the CA PEM. It fails without them. ## Verify commands diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index cc8eac6cb9..87c29cb453 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- `adapterctl provision --runtime-config FILE` creates the migration and + runtime roles and the database from the runtime file's two database URLs, as + a non-superuser administrator over verified TLS, or prints the script with + `--print-sql`. Running it again creates only what is missing and refuses a + role whose password differs from its URL. The runtime role gets only + `CONNECT`, and `adapter serve` grants its table privileges at startup as + before. - A scope refusal on the facade and the payment routes now writes the scope claim name, the scope the operation requires and the access profile or payment connection it applies to on its `request refused` line. The values diff --git a/products/adapter/scripts/check_dependency_direction.py b/products/adapter/scripts/check_dependency_direction.py index 9e1836093b..6e7a8f4d2a 100755 --- a/products/adapter/scripts/check_dependency_direction.py +++ b/products/adapter/scripts/check_dependency_direction.py @@ -325,7 +325,9 @@ def authoring_refused(start, names, every, linked) -> set[str]: or name.startswith("registry-platform-") ) else: - permits = lambda name: engine_may_reach("registry-adapterctl", name) + permits = lambda name: ( + engine_may_reach("registry-adapterctl", name) or name == "registry-cli-report" + ) 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]): diff --git a/products/adapter/scripts/test_dependency_direction.py b/products/adapter/scripts/test_dependency_direction.py index f6f6a4df5e..c5dc353ffb 100755 --- a/products/adapter/scripts/test_dependency_direction.py +++ b/products/adapter/scripts/test_dependency_direction.py @@ -44,6 +44,7 @@ "coordinator-client": "registry-coordinator-client", "stack-client": "registry-stack-client", "cli-docs": "registry-cli-docs", + "cli-report": "registry-cli-report", "evidence": "registry-evidence", "casework": "registry-casework", "caseworkctl": "registry-caseworkctl", @@ -89,6 +90,7 @@ "coordinator-client": ["platform"], "stack-client": ["breg-client", "coordinator-client"], "cli-docs": ["engine", "ctl", "job"], + "cli-report": ["serde"], "evidence": ["shared-engine", "core", "platform"], "casework": ["platform", "breg"], "caseworkctl": ["casework"], @@ -177,6 +179,22 @@ def test_authoring_replays_a_payment_provider_without_reaching_product_clients(s failures(ctl=[*INTENDED["ctl"], "breg-client"]), ) + def test_authoring_reports_through_the_shared_cli_report_crate_only(self): + graph = metadata(ctl=[*INTENDED["ctl"], "cli-report"]) + self.assertEqual(MODULE.violations(graph), []) + for reached in ("bregctl", "breg-client", "coordinator"): + with self.subTest(reached=reached): + self.assertIn( + NAMES[reached], + failures(ctl=[*INTENDED["ctl"], "cli-report", reached]), + ) + for owner in ("shared-engine", "engine", "job"): + with self.subTest(owner=owner): + self.assertIn( + NAMES["cli-report"], + failures(**{owner: [*INTENDED[owner], "cli-report"]}), + ) + 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/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 900259df1b..edabecfe43 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -6098,7 +6098,7 @@ "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions.", "source": { "path": "crates/registry-platform-provision/src/cli.rs", - "sha256": "43ad277b6695e1ceff8bdf6b917f19e19531a2fa954d4a8283367615bf3f17b7" + "sha256": "152dfe5949fc2c35a374b18409a8d19b0da0f967ebff3758ab0d17982af8ace7" }, "artifact": { "path": "crates/registry-platform-provision/schema/provision-report.schema.json", From c9541853003daf2d130fec0cdb661ef9865b4198 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:42:12 +0100 Subject: [PATCH 067/136] docs(evidence): cite the OID4VCI service security header call by its current name The rate-limit evidence comment on the OID4VCI configuration page names the transitional security header function the service calls. Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/configure/evidence-oid4vci.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx index acbcb76f76..6408a7f248 100644 --- a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx +++ b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx @@ -246,7 +246,7 @@ front of those three paths as well. Check that the defaults suit your wallet tra upgrade a busy deployment, and raise them in `rateLimits` rather than behind the proxy alone. {/* Evidence: crates/registry-evidence-oid4vci/src/service.rs, Limits, admit, limiter_refusal, offer_limiter_key, wallet_endpoint, - build_app, normalize_rejections, security_headers; + build_app, normalize_rejections, security_headers_without_posture; crates/registry-evidence-oid4vci/src/config.rs, RateLimitsConfig, maximum_request_bytes; products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json, rateLimits, offersPerPrincipalPerMinute, walletRequestsPerMinute; From 250864b932955281139883cb0e312225388ba51e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:42:32 +0100 Subject: [PATCH 068/136] docs: state that the hook verifier refuses a stale delivery The client API page says the BReg hook verifier refuses a delivery time more than 300 seconds from the receiver clock, names the window and opt-out options, and drops the hand-written skew check from both receiver examples. Signed-off-by: Jeremi Joslin --- .../src/content/docs/reference/client-api.mdx | 23 +++++++------------ 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/docs/site/src/content/docs/reference/client-api.mdx b/docs/site/src/content/docs/reference/client-api.mdx index 6d2aa6f3cc..e03ec9fc6e 100644 --- a/docs/site/src/content/docs/reference/client-api.mdx +++ b/docs/site/src/content/docs/reference/client-api.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-10-23" +last_reviewed: "2026-11-27" doc_type: reference locale: en standards_referenced: @@ -738,8 +738,12 @@ identifiers using an undocumented spelling. `verifyHookDelivery` in Node and `verify_hook_delivery` in Python authenticate one exact BReg Version 1 hook request with the shared Rust verifier. Pass the received method, request target, headers, body bytes, and key without normalising them. The result carries the authenticated -CloudEvents attributes, delivery metadata, and body. It does not decide whether the delivery is -fresh, expected by this receiver, or already applied; the receiver checks those, in this order. +CloudEvents attributes, delivery metadata, and body. It refuses a delivery time more than 300 +seconds from the receiver clock, either way, with the code `stale-delivery`. `maxSkewSeconds` +(Python `max_skew_seconds`, 1 to 3600) sets another window, and `callerEnforcedFreshness: true` +(Python `caller_enforced_freshness=True`) leaves the check to the receiver. It does not decide +whether the delivery is expected by this receiver or already applied; the receiver checks those, in +this order. In both examples, `event_store.apply_once()` (`eventStore.applyOnce()` in Node) is an application-owned transaction that claims the event identity and commits the effect once, and @@ -749,7 +753,6 @@ application-owned transaction that claims the event identity and commits the eff const { breg } = require('@registrystack/client'); const MAX_BODY_BYTES = 1_048_576; -const MAX_CLOCK_SKEW_MS = 5 * 60 * 1_000; const EXPECTED_SOURCE = 'urn:registrystack:registry:example:instance:primary'; const EXPECTED_TYPE = 'case-created-v1'; const EXPECTED_DATASCHEMA = @@ -790,10 +793,6 @@ async function receiveWebhook(request, response, key, eventStore) { key, }); - const skew = Math.abs(Date.now() - Date.parse(delivery.deliveryTime)); - if (!Number.isFinite(skew) || skew > MAX_CLOCK_SKEW_MS) { - throw new Error('hook delivery is outside the accepted clock skew'); - } if (delivery.source !== EXPECTED_SOURCE || delivery.type !== EXPECTED_TYPE || delivery.dataschema !== EXPECTED_DATASCHEMA) { @@ -810,11 +809,9 @@ async function receiveWebhook(request, response, key, eventStore) { ```python import json -from datetime import datetime, timezone from registry_client import breg -MAX_CLOCK_SKEW_SECONDS = 5 * 60 EXPECTED_SOURCE = "urn:registrystack:registry:example:instance:primary" EXPECTED_TYPE = "case-created-v1" EXPECTED_DATASCHEMA = ( @@ -827,10 +824,6 @@ def receive_webhook(method, path, headers, body, key, event_store): method=method, path=path, headers=headers, body=body, key=key, ) - sent = datetime.fromisoformat(delivery["delivery_time"]) - skew = abs((datetime.now(timezone.utc) - sent).total_seconds()) - if skew > MAX_CLOCK_SKEW_SECONDS: - raise ValueError("hook delivery is outside the accepted clock skew") if (delivery["source"], delivery["type"], delivery["dataschema"]) != ( EXPECTED_SOURCE, EXPECTED_TYPE, EXPECTED_DATASCHEMA, ): @@ -851,7 +844,7 @@ Keep the key in server-side secret storage and never log the input or a failed d raises `BaseRegistryClientError` with kind `hook-verification`; its `code` and message name the input to check without rendering its value. Generation and attempt are decimal strings, so a 64-bit generation never rounds in JavaScript. A delivery outside the skew bound can still carry a valid -signature, so reject it before deduplication. The idempotency key identifies one delivery generation +signature, so the verifier refuses it before deduplication. The idempotency key identifies one delivery generation and survives automatic retries, but an operator replay creates a new generation and key. Deduplicate an effect that must happen once on `source` plus `id`, or on a business key. [Webhooks](../../operate/breg-webhooks/) covers provisioning the key and building a receiver. From 1424749fabf27b3789787eeeefb2818c4f028074 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:43:16 +0100 Subject: [PATCH 069/136] docs: state the platforms Messaging, Render and the BReg citizen services ship for The install sections name the Linux amd64, Linux arm64 and macOS arm64 builds and the installers each release publishes, and say the images stay amd64 only. Signed-off-by: Jeremi Joslin --- .../src/content/docs/configure/breg-mcp.mdx | 4 +-- .../src/content/docs/operate/messaging.mdx | 31 +++++++++---------- .../content/docs/operate/registry-render.mdx | 7 +++-- .../docs/tutorials/first-render-document.mdx | 4 +-- 4 files changed, 24 insertions(+), 22 deletions(-) diff --git a/docs/site/src/content/docs/configure/breg-mcp.mdx b/docs/site/src/content/docs/configure/breg-mcp.mdx index 3200843698..2ac283fe4e 100644 --- a/docs/site/src/content/docs/configure/breg-mcp.mdx +++ b/docs/site/src/content/docs/configure/breg-mcp.mdx @@ -450,8 +450,8 @@ calls BReg or the issuer. ### Install or run the images -Each release publishes both services as `linux-amd64` binaries, verified as -[Obtain the runtime](../../operate/breg/#obtain-the-runtime) describes, and as images under +Each release publishes both services as binaries for Linux amd64, Linux arm64, and macOS arm64, +verified as [Obtain the runtime](../../operate/breg/#obtain-the-runtime) describes, and as images under `ghcr.io/registrystack/`. Deploy both from one tag, and images by digest. Each image runs as the Distroless `nonroot` user and reads `/etc//runtime.yaml`. Mount diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index d36e8ab6d4..2a475be444 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -32,35 +32,34 @@ Messaging needs no broker or cache, and connects to no database but its own. ## Install the binaries -Choose a tag, normally the -[latest release](https://github.com/registrystack/registry-stack/releases/latest), download -`messaging--linux-amd64` and `messagingctl--linux-amd64`, and authenticate both with +Each release publishes `messaging` and `messagingctl` for Linux amd64, Linux arm64, and macOS +arm64, with an installer. Choose a tag, normally the +[latest release](https://github.com/registrystack/registry-stack/releases/latest), and +authenticate the assets with [Verify a release](https://github.com/registrystack/registry-stack/blob/main/release/VERIFY.md). -Install the pair from one tag: +Linux assets are executables named `--linux-`. macOS assets are `.tar.gz` +bundles that carry the executable, its AWS-LC-FIPS libraries, and notices. +Install the pair from one tag with the release-pinned installer: ```sh -tag="${TAG:?set TAG to the release you verified}" -mkdir -p ~/.local/bin -for binary in messaging messagingctl; do - install -m 0755 "${binary}-${tag}-linux-amd64" "$HOME/.local/bin/${binary}" -done -export PATH="$HOME/.local/bin:$PATH" +bash messaging--install.sh messaging --version messagingctl --version ``` -For another platform, build both from a checkout with -`cargo build --release --locked -p registry-messaging -p registry-messagingctl`. +The installer puts both binaries in `~/.local/bin`. Set `MESSAGING_INSTALL_DIR` to change that. +Neither path needs a Rust toolchain. + +{/* Evidence: release/scripts/release_roster.py ADDITIONAL_PLATFORM_BUILDS and ADDITIONAL_INSTALLERS; + crates/registry-messaging/install.sh MESSAGING_INSTALL_DIR. */} The image `ghcr.io/registrystack/messaging:` carries both binaries and runs `messaging --runtime-config /etc/registry-messaging/runtime.yaml serve`. Mount the package, runtime file, and secrets read-only, give the audit path writable storage, and deploy by digest. -{/* Evidence: release/docker/Dockerfile.messaging; release v0.41.0 assets. */} +{/* Evidence: release/docker/Dockerfile.messaging; release/scripts/build-release-image.sh. */} -Each release publishes the `messaging` and `messagingctl` binaries for Linux amd64 only, checked -against the release `SHA256SUMS`, and the container image for linux/amd64 only. There is no -Messaging installer and no Linux arm64 or macOS build of either binary. The unified clients carry +The container image is published for linux/amd64 only. The unified clients carry a `messaging` namespace: `@registrystack/client` on npm (Linux x64 and arm64 with glibc, macOS arm64) and `registry-stack-client` on PyPI (manylinux x86_64 and aarch64, macOS arm64). diff --git a/docs/site/src/content/docs/operate/registry-render.mdx b/docs/site/src/content/docs/operate/registry-render.mdx index aa17122b93..c657e88910 100644 --- a/docs/site/src/content/docs/operate/registry-render.mdx +++ b/docs/site/src/content/docs/operate/registry-render.mdx @@ -48,8 +48,11 @@ compatibility promise. ## Install the binary -Releases from v0.38.0 attach a Linux amd64 binary, `registry-render--linux-amd64`. Choose -`` from the [latest release](https://github.com/registrystack/registry-stack/releases/latest), +Releases from v0.44.0 attach `registry-render` for Linux amd64, Linux arm64, and macOS arm64. +Linux assets are named `registry-render--linux-`. macOS assets are `.tar.gz` bundles. +Releases from v0.38.0 to v0.43.0 attach the Linux amd64 binary only. This section installs the +Linux amd64 binary. Choose `` from the +[latest release](https://github.com/registrystack/registry-stack/releases/latest), verify the asset with that release's `release/VERIFY.md`, then install it. This replaces any existing `~/.local/bin/registry-render`, so keep a copy first when you need a rollback: diff --git a/docs/site/src/content/docs/tutorials/first-render-document.mdx b/docs/site/src/content/docs/tutorials/first-render-document.mdx index e4b834d096..6d436731e0 100644 --- a/docs/site/src/content/docs/tutorials/first-render-document.mdx +++ b/docs/site/src/content/docs/tutorials/first-render-document.mdx @@ -27,9 +27,9 @@ prove the two PDFs are the same bytes. ## Build registry-render -Releases publish a Linux amd64 binary, which +Releases publish binaries for Linux amd64, Linux arm64, and macOS arm64, which [Deploy Registry Render](../../operate/registry-render/#install-the-binary) installs. This -tutorial builds from the checkout so it also works on macOS. From the checkout's root: +tutorial builds from the checkout so it needs no release tag. From the checkout's root: ```sh test-skip="builds from source; the gate puts the binary under test on PATH" . scripts/cargo-runtime-library-path.sh From 9352fbbaedaa3a0288f2f871cf3372ad970ff0ac Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:43:18 +0100 Subject: [PATCH 070/136] docs(casework): scope the current-source read sentences to their path The configuration reference and the security page each say which credential Casework forwards for a current-source human read today: the caller's bearer on the default path, and only the source credential under humanSourceAuthentication. Signed-off-by: Jeremi Joslin --- .../src/content/docs/reference/casework-configuration.mdx | 8 ++++++-- docs/site/src/content/docs/security/casework.mdx | 4 +++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/site/src/content/docs/reference/casework-configuration.mdx b/docs/site/src/content/docs/reference/casework-configuration.mdx index 92c22d1768..2089c74396 100644 --- a/docs/site/src/content/docs/reference/casework-configuration.mdx +++ b/docs/site/src/content/docs/reference/casework-configuration.mdx @@ -367,7 +367,9 @@ It does not supply fields shown to a human reviewer. ### Current-source reads For a current-source review, the human request selects a BReg source profile with the `Registry-Source-Profile` header. -Casework forwards that human's bearer to BReg for the current display read. +Today, unless the provider declares `humanSourceAuthentication`, Casework forwards that human's Casework bearer to BReg for the current display read. +BReg must therefore accept that token's audience. +A provider that declares `humanSourceAuthentication` uses a [separate source credential](#separate-source-credential) instead. BReg authorises the profile, subject and disclosure. The compiled Casework policy pins the producer's context contract and vendored schema; the verified package also includes the provider's exported description. @@ -376,7 +378,9 @@ Rotate transport credentials by updating their secret references without changin A changed BReg context contract needs a new export, schema pin and Casework package. {/* Evidence: crates/registry-caseworkctl/src/lib.rs against_breg_package; - crates/registry-casework-core/src/http.rs registry-source-profile */} + crates/registry-casework-core/src/http.rs registry-source-profile; + crates/registry-casework/src/http/source_credentials.rs boundary; + crates/registry-casework-breg/src/lib.rs human_display */} ### Separate source credential diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index caf1958168..c046134eaf 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -152,7 +152,9 @@ grants in [Registry Casework task grants](../../reference/casework-task-grants/) mode is observable to an authenticated staff caller. This is accepted: the caller is authenticated staff, ids are random UUIDs, and the response reveals the context mode only. - Only the source bearer is forwarded, never the Casework or unattended status credential. + On this separate-credential path, only the source bearer is forwarded, never the Casework or + unattended status credential. + Without the pair, Casework forwards the human's Casework bearer to BReg for the current display read. Credentials are redacted, zeroised and dropped with the request, with no cross-call cache or durable recovery capture. This is two independently authorised credentials for one existing human, not delegation, From 1da44cc42a3a46f67e9e184df9e3e6c4aed02ca9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:46:56 +0100 Subject: [PATCH 071/136] docs: add discovery and discoveryctl to the CLI reference as drafts The CLI catalog now covers the Discovery runtime and its tool. Both expose a public command tree, discoveryctl package documents every argument, and discoveryctl check --runtime-config uses the shared help wording. Both pages stay unreviewed drafts until someone reviews them. Signed-off-by: Jeremi Joslin --- Cargo.lock | 2 + crates/registry-cli-docs/Cargo.toml | 2 + crates/registry-cli-docs/catalog.json | 903 +++++++++++++++++++ crates/registry-cli-docs/src/lib.rs | 4 + crates/registry-discovery/src/cli.rs | 26 + crates/registry-discovery/src/lib.rs | 2 + crates/registry-discovery/src/main.rs | 15 +- crates/registry-discoveryctl/src/lib.rs | 18 +- docs/site/scripts/generate-cli-reference.mjs | 3 + docs/site/src/data/cli-reference.yaml | 2 +- docs/site/src/lib/cli-reference-sidebar.mjs | 2 + 11 files changed, 960 insertions(+), 19 deletions(-) create mode 100644 crates/registry-discovery/src/cli.rs diff --git a/Cargo.lock b/Cargo.lock index 782729f702..cd8a5009f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6679,6 +6679,8 @@ dependencies = [ "registry-caseworkctl", "registry-cli-reference", "registry-coordinator", + "registry-discovery", + "registry-discoveryctl", "registry-documents", "registry-documentsctl", "registry-evidence", diff --git a/crates/registry-cli-docs/Cargo.toml b/crates/registry-cli-docs/Cargo.toml index 0eaf0f333e..e9f397280b 100644 --- a/crates/registry-cli-docs/Cargo.toml +++ b/crates/registry-cli-docs/Cargo.toml @@ -34,6 +34,8 @@ registry-schedulingctl.workspace = true registry-messaging.workspace = true registry-messagingctl.workspace = true registry-mcp.workspace = true +registry-discovery = { workspace = true, features = ["server"] } +registry-discoveryctl.workspace = true registry-documents.workspace = true registry-documentsctl.workspace = true registry-manifest-cli.workspace = true diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 11c94f6978..8c07a8f4f7 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -14013,6 +14013,909 @@ } ] }, + { + "name": "discovery", + "invocation": "discovery", + "about": "Serve one immutable Registry Discovery index", + "long_about": null, + "usage": "discovery --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-V, --version", + "description": "Print version", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "discoveryctl", + "invocation": "discoveryctl", + "about": "Check and package one immutable Registry Discovery index", + "long_about": null, + "usage": "discoveryctl ", + "arguments": [], + "options": [ + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-V, --version", + "description": "Print version", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [ + { + "name": "api", + "invocation": "discoveryctl api", + "about": "Send one raw HTTP request to a Discovery endpoint", + "long_about": null, + "usage": "discoveryctl api [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Relative API path. A leading slash is accepted without discarding a deployment prefix", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--project ", + "description": "Project directory, or a descendant from which the exact product root is found", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--connection ", + "description": "Named saved remote connection", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--url ", + "description": "Explicit service base URL for an advanced one-off request", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--token-file ", + "description": "Bearer credential file used only with `--url`", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--ca-file ", + "description": "PEM certificate authority bundle for an explicit private-institution endpoint", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--method ", + "description": "HTTP method. Defaults to GET, or POST when `--input` is present", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--input ", + "description": "Request body file, or `-` for standard input", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--header
", + "description": "Request header as `NAME: VALUE`; use `NAME: @FILE` for a value or `@FILE` for complete lines", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--accept ", + "description": "Value of the HTTP Accept header", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--output ", + "description": "Write response bytes to this file instead of standard output", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--include", + "description": "Include the HTTP status and response headers before the response body", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--idempotency-key ", + "description": "Value of the Idempotency-Key header", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--if-match ", + "description": "Literal HTTP If-Match value, including quotes when the endpoint requires them", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "requires-all", + "when": "--token-file ", + "arguments": [ + "--url " + ] + }, + { + "kind": "requires-all", + "when": "--ca-file ", + "arguments": [ + "--url " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--connection ", + "--url " + ] + } + ], + "subcommands": [] + }, + { + "name": "connection", + "invocation": "discoveryctl connection", + "about": "Manage named Discovery API connections", + "long_about": null, + "usage": "discoveryctl connection [OPTIONS] ", + "arguments": [], + "options": [ + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [ + { + "name": "add", + "invocation": "discoveryctl connection add", + "about": "Save one product-scoped remote connection", + "long_about": null, + "usage": "discoveryctl connection add [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Local connection name used by `--connection` and project selections", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--url ", + "description": "API service base URL. Prompted when omitted in an interactive terminal", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--ca-file ", + "description": "PEM certificate authority bundle for a private-institution endpoint", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--access-profile ", + "description": "Casework only: stable caller access profile applied to its profile headers", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--anonymous", + "description": "Save a connection that sends no Authorization header", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--token-file ", + "description": "File holding a bearer token. The configuration stores only a secret reference", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--token-env ", + "description": "Environment variable holding a bearer token. The configuration stores only a secret reference", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--private-key-jwt", + "description": "Acquire renewable bearer tokens with OAuth private_key_jwt", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--token-endpoint ", + "description": "OAuth token endpoint used for private_key_jwt authentication", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--client-id ", + "description": "OAuth client identifier registered at the token endpoint", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--private-key-file ", + "description": "Owner-only file containing the private client JWK", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--scope ", + "description": "OAuth scope to request; repeat the option for multiple scopes", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--resource ", + "description": "Optional RFC 8707 resource indicator for the requested token", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--assertion-audience ", + "description": "Client assertion audience: the authorization server's issuer identifier", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "requires-all", + "when": "--token-endpoint ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--client-id ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--private-key-file ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--scope ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--resource ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--assertion-audience ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--anonymous", + "--private-key-jwt" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--anonymous", + "--token-env " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--anonymous", + "--token-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--private-key-jwt", + "--token-env " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--private-key-jwt", + "--token-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--token-env ", + "--token-file " + ] + } + ], + "subcommands": [] + }, + { + "name": "list", + "invocation": "discoveryctl connection list", + "about": "List saved connections for this product", + "long_about": null, + "usage": "discoveryctl connection list [OPTIONS]", + "arguments": [], + "options": [ + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "show", + "invocation": "discoveryctl connection show", + "about": "Show one saved connection without resolving its credential", + "long_about": null, + "usage": "discoveryctl connection show [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Local name of the connection to show", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "use", + "invocation": "discoveryctl connection use", + "about": "Select a saved connection for one exact product project", + "long_about": null, + "usage": "discoveryctl connection use [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Local name of the connection to select for the project", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--project ", + "description": "Project directory, or a descendant from which the exact product root is found", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "check", + "invocation": "discoveryctl connection check", + "about": "Check one saved-connections file without resolving credentials or contacting endpoints", + "long_about": null, + "usage": "discoveryctl connection check [OPTIONS] --file ", + "arguments": [], + "options": [ + { + "display": "--file ", + "description": "Saved-connections YAML file to validate offline", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--deny-warnings", + "description": "Exit 1 when the check reports a warning", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + } + ] + }, + { + "name": "serve", + "invocation": "discoveryctl serve", + "about": "Run the production Discovery service with the selected runtime", + "long_about": null, + "usage": "discoveryctl serve --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file passed unchanged to the Discovery runtime", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "check", + "invocation": "discoveryctl check", + "about": "Check an authoring project, a runtime file, or an index without network I/O", + "long_about": null, + "usage": "discoveryctl check [OPTIONS] <--project |--runtime-config |--index >", + "arguments": [], + "options": [ + { + "display": "--project ", + "description": "The authoring project directory: origins.yaml, the mappings directory, and every runtime file beside them", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--runtime-config ", + "description": "Runtime configuration file, checked on its own", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--index ", + "description": "One index file, as `discoveryctl package` wrote it, checked on its own exactly as `discovery --runtime-config` parses it at startup", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--allow-loopback", + "description": "Accept an http loopback catalog URL, for development", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--environment", + "description": "Fill the runtime file's ${NAME} expressions from this process's environment and check the values they produce", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "--deny-warnings", + "description": "Exit 1 when the check reports a warning", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "required-one-or-more", + "when": null, + "arguments": [ + "--project ", + "--runtime-config ", + "--index " + ] + } + ], + "subcommands": [] + }, + { + "name": "package", + "invocation": "discoveryctl package", + "about": "Fetch every enabled approved origin once and write one immutable package", + "long_about": null, + "usage": "discoveryctl package [OPTIONS] --project --output ", + "arguments": [], + "options": [ + { + "display": "--project ", + "description": "The authoring project directory: origins.yaml, the mappings directory, and every runtime file beside them", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--output ", + "description": "The new directory the package is written to", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--allow-loopback", + "description": "Accept an http loopback catalog URL, for development", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--revision ", + "description": "Optional operator revision recorded in the package envelope", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + } + ] + }, { "name": "documents", "invocation": "documents", diff --git a/crates/registry-cli-docs/src/lib.rs b/crates/registry-cli-docs/src/lib.rs index 17ac1065bd..1c8cb68938 100644 --- a/crates/registry-cli-docs/src/lib.rs +++ b/crates/registry-cli-docs/src/lib.rs @@ -27,6 +27,8 @@ pub fn catalog() -> Catalog { command_reference(registry_messaging::runtime::command(), None, None), command_reference(registry_messagingctl::command(), None, None), command_reference(registry_mcp::command(), None, None), + command_reference(registry_discovery::cli::command(), None, None), + command_reference(registry_discoveryctl::command(), None, None), command_reference(registry_documents::runtime::command(), None, None), command_reference(registry_documentsctl::command(), None, None), command_reference(registry_manifest_cli::command(), None, None), @@ -166,6 +168,8 @@ mod tests { "caseworkctl", "coordinator", "coordinatorctl", + "discovery", + "discoveryctl", "documents", "documentsctl", "evidence", diff --git a/crates/registry-discovery/src/cli.rs b/crates/registry-discovery/src/cli.rs new file mode 100644 index 0000000000..947723f471 --- /dev/null +++ b/crates/registry-discovery/src/cli.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The `discovery` command line, shared by the process entry point and the +//! generated CLI reference. + +use std::path::PathBuf; + +use clap::{CommandFactory, Parser}; + +/// Arguments of the `discovery` process. +#[derive(Debug, Parser)] +#[command( + name = "discovery", + about = "Serve one immutable Registry Discovery index", + version = crate::build_info::DISPLAY_VERSION +)] +pub struct Arguments { + /// Runtime configuration file. + #[arg(long = "runtime-config", value_name = "ABSOLUTE_FILE")] + pub runtime_config: PathBuf, +} + +/// The clap command tree, for the generated CLI reference. +#[must_use] +pub fn command() -> clap::Command { + Arguments::command() +} diff --git a/crates/registry-discovery/src/lib.rs b/crates/registry-discovery/src/lib.rs index 20daccd56d..2fce0fd7e5 100644 --- a/crates/registry-discovery/src/lib.rs +++ b/crates/registry-discovery/src/lib.rs @@ -17,6 +17,8 @@ pub mod build_info { include!(concat!(env!("OUT_DIR"), "/product_build_info.rs")); } +#[cfg(feature = "server")] +pub mod cli; pub mod model; pub mod openapi; #[cfg(feature = "server")] diff --git a/crates/registry-discovery/src/main.rs b/crates/registry-discovery/src/main.rs index 94febc44a6..4c3836b36c 100644 --- a/crates/registry-discovery/src/main.rs +++ b/crates/registry-discovery/src/main.rs @@ -1,25 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 //! Registry Discovery process entry point. -use std::path::PathBuf; - use clap::Parser; +use registry_discovery::cli::Arguments; use registry_discovery::{load_runtime, serve, LogLevel}; use tracing_subscriber::filter::{LevelFilter, Targets}; use tracing_subscriber::prelude::*; -#[derive(Debug, Parser)] -#[command( - name = "discovery", - about = "Serve one immutable Registry Discovery index", - version = registry_discovery::build_info::DISPLAY_VERSION -)] -struct Arguments { - /// Runtime configuration file. - #[arg(long = "runtime-config", value_name = "ABSOLUTE_FILE")] - runtime_config: PathBuf, -} - #[tokio::main] async fn main() { let arguments = Arguments::parse(); diff --git a/crates/registry-discoveryctl/src/lib.rs b/crates/registry-discoveryctl/src/lib.rs index cce03ba7bd..1da0b33cc9 100644 --- a/crates/registry-discoveryctl/src/lib.rs +++ b/crates/registry-discoveryctl/src/lib.rs @@ -6,7 +6,7 @@ use std::io; use std::path::PathBuf; use std::process::{Command as ProcessCommand, ExitCode}; -use clap::{ArgGroup, Args, Parser, Subcommand, ValueEnum}; +use clap::{ArgGroup, Args, CommandFactory, Parser, Subcommand, ValueEnum}; use registry_platform_yaml::{Diagnostic, Report}; use serde_json::{json, Value}; @@ -49,6 +49,12 @@ struct Arguments { command: Command, } +/// The clap command tree, for the generated CLI reference. +#[must_use] +pub fn command() -> clap::Command { + Arguments::command() +} + #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)] enum OutputFormat { /// Diagnostics with their position first, then a summary line. @@ -85,7 +91,7 @@ enum Command { /// directory, and every runtime file beside them. #[arg(long, value_name = "DIRECTORY")] project: Option, - /// One runtime file, checked on its own. + /// Runtime configuration file, checked on its own. #[arg(long, value_name = "FILE")] runtime_config: Option, /// One index file, as `discoveryctl package` wrote it, checked on @@ -108,10 +114,14 @@ enum Command { }, /// Fetch every enabled approved origin once and write one immutable package. Package { - #[arg(long)] + /// The authoring project directory: origins.yaml, the mappings + /// directory, and every runtime file beside them. + #[arg(long, value_name = "DIRECTORY")] project: PathBuf, - #[arg(long)] + /// The new directory the package is written to. + #[arg(long, value_name = "DIRECTORY")] output: PathBuf, + /// Accept an http loopback catalog URL, for development. #[arg(long)] allow_loopback: bool, /// Optional operator revision recorded in the package envelope. diff --git a/docs/site/scripts/generate-cli-reference.mjs b/docs/site/scripts/generate-cli-reference.mjs index 971ab2fe3d..418000cc2b 100644 --- a/docs/site/scripts/generate-cli-reference.mjs +++ b/docs/site/scripts/generate-cli-reference.mjs @@ -33,6 +33,8 @@ export const expectedBinaries = [ 'caseworkctl', 'coordinator', 'coordinatorctl', + 'discovery', + 'discoveryctl', 'documents', 'documentsctl', 'evidence', @@ -77,6 +79,7 @@ const groups = [ { title: 'Registry Casework', binaries: ['casework', 'caseworkctl'] }, { title: 'Registry Scheduling', binaries: ['scheduling', 'schedulingctl'] }, { title: 'Registry Messaging', binaries: ['messaging', 'messagingctl'], product: 'registry-messaging' }, + { title: 'Registry Discovery', binaries: ['discovery', 'discoveryctl'] }, { title: 'Document Store', binaries: ['documents', 'documentsctl'], product: 'registry-documents' }, { title: 'Registry Evidence', binaries: ['evidence', 'evidencectl'] }, { title: 'Evidence credential delivery', binaries: ['evidence-oid4vci'] }, diff --git a/docs/site/src/data/cli-reference.yaml b/docs/site/src/data/cli-reference.yaml index 6a2d4c80d5..b0ae921101 100644 --- a/docs/site/src/data/cli-reference.yaml +++ b/docs/site/src/data/cli-reference.yaml @@ -11,5 +11,5 @@ status: current last_reviewed: 2026-11-24 unreviewed_binaries: - [adapter, adapter-job, adapterctl, coordinator, coordinatorctl, documents, documentsctl, evidence-oid4vp, manifest, registry-mcp, rstack] + [adapter, adapter-job, adapterctl, coordinator, coordinatorctl, documents, documentsctl, evidence-oid4vp, manifest, registry-mcp, rstack, discovery, discoveryctl] source_build_only_binaries: [adapter-job, evidence-oid4vp, registry-mcp] diff --git a/docs/site/src/lib/cli-reference-sidebar.mjs b/docs/site/src/lib/cli-reference-sidebar.mjs index 6492bfb762..15f768c212 100644 --- a/docs/site/src/lib/cli-reference-sidebar.mjs +++ b/docs/site/src/lib/cli-reference-sidebar.mjs @@ -25,6 +25,8 @@ const binaries = [ 'documentsctl', 'evidence', 'evidencectl', + 'discovery', + 'discoveryctl', 'mint', 'evidence-oid4vci', 'evidence-oid4vp', From 3d22665a2b4857d83c2232ea1d7a93be2938364e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 10:47:37 +0100 Subject: [PATCH 072/136] docs(discovery): state the platforms and installer the release ships The install section names the Linux amd64, Linux arm64 and macOS arm64 builds and the release-pinned installer, and says the image is linux/amd64. Signed-off-by: Jeremi Joslin --- .../src/content/docs/configure/discovery.mdx | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/docs/site/src/content/docs/configure/discovery.mdx b/docs/site/src/content/docs/configure/discovery.mdx index c9f2c5da69..adff8b404b 100644 --- a/docs/site/src/content/docs/configure/discovery.mdx +++ b/docs/site/src/content/docs/configure/discovery.mdx @@ -30,28 +30,31 @@ checkout root for the commands that run beside it. ## Install the binaries -Releases from v0.38.0 publish Linux amd64 assets `discovery--linux-amd64` and -`discoveryctl--linux-amd64`, with `` from the -[latest release](https://github.com/registrystack/registry-stack/releases/latest). Authenticate -them through the release's `SHA256SUMS` as the -[verification guide](https://github.com/registrystack/registry-stack/blob/main/release/VERIFY.md) -describes, then install them under their plain names: +Each release publishes `discovery` and `discoveryctl` for Linux amd64, Linux arm64, and macOS +arm64, with an installer. Choose a tag, normally the +[latest release](https://github.com/registrystack/registry-stack/releases/latest), and +authenticate the assets with the +[verification guide](https://github.com/registrystack/registry-stack/blob/main/release/VERIFY.md). +Linux assets are executables named `--linux-`. macOS assets are `.tar.gz` +bundles that carry the executable, its AWS-LC-FIPS libraries, and notices. +Install the pair from one tag with the release-pinned installer: ```sh test-skip="installs release assets; the runner serves the binaries under test" -tag="${TAG:?set TAG to the published release tag}" -mkdir -p ~/.local/bin -for binary in discovery discoveryctl; do - install -m 0755 "${binary}-${tag}-linux-amd64" "$HOME/.local/bin/${binary}" -done +bash discovery--install.sh +discovery --version +discoveryctl --version ``` -On another platform, build them from a checkout as the tutorial does. The release also publishes -the image `ghcr.io/registrystack/discovery:`; deploy it by the digest the release manifest -records, not by the tag. It runs `discovery` as a nonroot user and reads -`/etc/registry-discovery/runtime.yaml`. Mount that file and the package directory read-only; -Discovery writes nothing. +The installer puts both binaries in `~/.local/bin`. Set `DISCOVERY_INSTALL_DIR` to change that. +Neither path needs a Rust toolchain. -{/* Evidence: release/scripts/release_roster.py, DISCOVERYCTL_FIRST_RELEASE; +The release also publishes the image `ghcr.io/registrystack/discovery:` for linux/amd64. +Deploy it by the digest the release manifest records, not by the tag. It runs `discovery` as a +nonroot user and reads `/etc/registry-discovery/runtime.yaml`. Mount that file and the package +directory read-only. Discovery writes nothing. + +{/* Evidence: release/scripts/release_roster.py, ADDITIONAL_PLATFORM_BUILDS and ADDITIONAL_INSTALLERS; + crates/registry-discovery/install.sh, DISCOVERY_INSTALL_DIR; release/docker/Dockerfile.discovery, ENTRYPOINT, CMD, and "writes nothing"; release/VERIFY.md. */} ## Approve HTTPS origins From d8299d605d92154a457c0b2686309bebfe09829d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 11:01:06 +0100 Subject: [PATCH 073/136] ci: run the adapterctl provisioning journey in the TLS PostgreSQL lane The classifier now lists registry-adapterctl among the provisioning journeys, selects the lane when the Adapter's serve grants change, and the journey step runs and checks its log. The Adapter migrates and grants inside adapter serve, so the journey name check also admits provision_then_serve. The adapterctl provisioning tests use a readable synthetic cursor key, as the other Adapter tests do. Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 3 +++ .github/scripts/test_ci_changes.py | 2 +- .github/workflows/ci.yml | 8 +++++--- crates/registry-adapterctl/tests/provision_cli.rs | 3 ++- crates/registry-adapterctl/tests/provision_postgres.rs | 4 +++- 5 files changed, 14 insertions(+), 6 deletions(-) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index d69f47fd9e..de310f7a32 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -610,6 +610,7 @@ # The packages whose provisioning journey runs against the contracts-journeys # lane's TLS-only PostgreSQL service, and the inputs that select that lane. PROVISION_JOURNEY_PACKAGES = ( + "registry-adapterctl", "registry-bregctl", "registry-caseworkctl", "registry-coordinator", @@ -631,6 +632,8 @@ "crates/registry-messaging/migrations/**", "crates/registry-scheduling/migrations/**", # What `apply` grants and what the start check reads, per product. + # The Adapter migrates and grants when it serves, not in a separate apply. + "crates/registry-adapter/src/serve.rs", "crates/registry-casework/src/activation.rs", "crates/registry-documents/src/activation.rs", "crates/registry-messaging/src/activation.rs", diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 5e4848741d..44661ebdf2 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -4544,7 +4544,7 @@ def test_contracts_journeys_lane_runs_each_product_provisioning_journey( command, ) self.assertIn( - "grep -Eq '^test ([a-z_]+::)?provision_then_apply_then_serve_with_[a-z_]+ " + "grep -Eq '^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ " "\\.\\.\\. ok$' \"${log}\"", command, ) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 84c2fc4fa5..97dcc63f81 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2016,9 +2016,11 @@ jobs: fi # Each journey provisions its product's database and roles on the # TLS-only service, applies as the owner role and serves as the - # runtime role. + # runtime role. The Adapter applies inside `adapter serve`. export PROVISION_TEST_DATABASE_URL="postgresql://breg:breg_test@localhost:${DATABASE_PORT}/postgres?sslmode=verify-full" export PROVISION_TEST_DATABASE_CA="${BREG_TEST_TLS_CA_PEM_PATH}" + cargo test --locked -p registry-adapterctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-adapterctl.log" cargo test --locked -p registry-bregctl --features postgres-test --test provision_postgres \ | tee "${RUNNER_TEMP}/provision-journey-registry-bregctl.log" cargo test --locked -p registry-caseworkctl --features postgres-test --test provision \ @@ -2033,10 +2035,10 @@ jobs: | tee "${RUNNER_TEMP}/provision-journey-registry-schedulingctl.log" # A run that selected no test still exits 0, so every log needs a # pass count, no ignored test, and the journey's own line. - for package in registry-bregctl registry-caseworkctl registry-coordinator registry-documentsctl registry-messagingctl registry-schedulingctl; do + for package in registry-adapterctl registry-bregctl registry-caseworkctl registry-coordinator registry-documentsctl registry-messagingctl registry-schedulingctl; do log="${RUNNER_TEMP}/provision-journey-${package}.log" grep -Eq '^test result: ok\. [1-9][0-9]* passed; 0 failed; 0 ignored' "${log}" || { echo "::error::expected the ${package} provisioning journey tests to pass with no test ignored"; exit 1; } - grep -Eq '^test ([a-z_]+::)?provision_then_apply_then_serve_with_[a-z_]+ \.\.\. ok$' "${log}" || { echo "::error::expected the ${package} provisioning journey to run and pass"; exit 1; } + grep -Eq '^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ \.\.\. ok$' "${log}" || { echo "::error::expected the ${package} provisioning journey to run and pass"; exit 1; } done - name: Stop PostgreSQL 16 for the provisioning floor test diff --git a/crates/registry-adapterctl/tests/provision_cli.rs b/crates/registry-adapterctl/tests/provision_cli.rs index 0f62a2cc73..58d817126c 100644 --- a/crates/registry-adapterctl/tests/provision_cli.rs +++ b/crates/registry-adapterctl/tests/provision_cli.rs @@ -11,6 +11,7 @@ use std::process::{Command, Output}; const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; +const CURSOR_KEY: &str = "synthetic-cursor-key-0123456789!"; /// A runtime file whose secret files name a migration and a runtime login on /// one server that does not exist, so a connection attempt could only fail. @@ -31,7 +32,7 @@ fn write_runtime(directory: &Path) -> String { "jwks.json", r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), ), - ("cursor-key", "0123456789abcdef0123456789abcdef".to_owned()), + ("cursor-key", CURSOR_KEY.to_owned()), ] { let path = secrets.join(name); std::fs::write(&path, value).unwrap(); diff --git a/crates/registry-adapterctl/tests/provision_postgres.rs b/crates/registry-adapterctl/tests/provision_postgres.rs index 70fbaba022..031e68ae79 100644 --- a/crates/registry-adapterctl/tests/provision_postgres.rs +++ b/crates/registry-adapterctl/tests/provision_postgres.rs @@ -23,6 +23,8 @@ use serde_json::Value; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; use uuid::Uuid; +const CURSOR_KEY: &str = "synthetic-cursor-key-0123456789!"; + fn repository(relative: &str) -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")) .join("../..") @@ -81,7 +83,7 @@ async fn provision_then_serve_with_split_roles() { std::fs::write(&path, value).unwrap(); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); }; - secret("cursor-key", "0123456789abcdef0123456789abcdef"); + secret("cursor-key", CURSOR_KEY); secret("upstream-user", "upstream-user"); secret("upstream-password", "upstream-password"); // The runtime verifies tokens against a static key set, so it starts From 67bc4e0989f68152c4d9da39905859f87b9e9c47 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 11:11:39 +0100 Subject: [PATCH 074/136] feat(platform): let httputil refuse a development peer and name one loopback rule validate_response_headers takes a peer policy and refuses a response whose Registry-Posture field is development under RefuseDevelopmentPeer. Clients with no runtime policy yet call the production-behaving validate_response_headers_without_peer_policy. is_loopback_host is the one plain-http host rule, FetchUrlPolicy::dev becomes https_or_loopback, LoopbackDevelopmentHttp becomes LoopbackHttp, and the private development destination profile exists only in test builds. Call sites across the workspace follow the renames. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + .../src/coordinator_event.rs | 4 +- crates/registry-adapter-engine/Cargo.toml | 1 + crates/registry-adapter-engine/src/egress.rs | 12 +- .../src/runtime_destination.rs | 4 +- .../src/signed_coordinator_event.rs | 2 +- .../tests/signed_coordinator_event_native.rs | 13 +- .../signed_coordinator_event_postgres.rs | 12 +- .../src/payments/g2p_service.rs | 9 +- .../registry-adapter/src/payments/service.rs | 8 +- crates/registry-adapterctl/src/verify/mod.rs | 2 +- crates/registry-breg-client/src/transport.rs | 4 +- .../src/api/tests/immediate_action_tests.rs | 14 +- crates/registry-breg/src/event_destination.rs | 2 +- .../tests/authentication_refusals.rs | 4 +- .../tests/concealment_refusals.rs | 2 +- crates/registry-breg/tests/consent_access.rs | 4 +- crates/registry-breg/tests/http_auth.rs | 4 +- .../tests/postgres_access_log.rs | 6 +- .../tests/postgres_action_task_grants.rs | 4 +- .../tests/postgres_consent_access.rs | 2 +- .../tests/postgres_data_export.rs | 2 +- .../tests/postgres_membership_access.rs | 2 +- ...stgres_multi_reference_action_authority.rs | 2 +- .../registry-breg/tests/postgres_proposal.rs | 2 +- .../tests/postgres_proposal_security.rs | 2 +- .../tests/postgres_proposal_task_authority.rs | 2 +- .../tests/postgres_registry_extensibility.rs | 2 +- .../tests/postgres_required_filters.rs | 2 +- .../registry-breg/tests/postgres_startup.rs | 4 +- .../tests/support/pilot_acceptance_harness.rs | 2 +- crates/registry-bregctl/src/data_lifecycle.rs | 4 +- crates/registry-casework-client/src/client.rs | 4 +- .../tests/breg_review_journey.rs | 8 +- .../tests/human_identity_auth.rs | 2 +- .../registry-casework/tests/refusal_golden.rs | 2 +- crates/registry-casework/tests/review_http.rs | 4 +- .../tests/review_payment_fixture_postgres.rs | 2 +- .../registry-coordinator-client/src/client.rs | 4 +- crates/registry-coordinator/src/adapters.rs | 2 +- crates/registry-coordinator/src/decision.rs | 2 +- .../registry-coordinator/src/external_http.rs | 2 +- .../tests/deployment_surface.rs | 6 +- .../registry-discovery-client/src/client.rs | 4 +- crates/registry-discoveryctl/src/build.rs | 9 +- .../registry-documents-client/src/client.rs | 7 +- crates/registry-evidence-client/src/client.rs | 20 +-- crates/registry-evidence/src/runtime_tests.rs | 2 +- .../src/compatibility_tests/inbound.rs | 8 +- .../src/compatibility_tests/server.rs | 2 +- .../src/inbound/refusal_tests.rs | 2 +- crates/registry-mcp/src/adapter.rs | 3 +- .../registry-messaging-client/src/client.rs | 5 +- crates/registry-messaging/src/auth.rs | 2 +- crates/registry-messaging/src/http.rs | 6 +- .../src/http_provider/mod.rs | 4 +- crates/registry-payment-client/src/client.rs | 5 +- .../src/delivery/destination.rs | 6 +- crates/registry-platform-httputil/Cargo.toml | 1 + crates/registry-platform-httputil/README.md | 13 +- .../src/client/exchange_authorization.rs | 4 +- .../src/client/mod.rs | 4 +- .../src/client/outbound.rs | 50 +++++- .../src/client/private_key_jwt.rs | 14 +- .../src/destination.rs | 58 ++++--- crates/registry-platform-httputil/src/lib.rs | 163 +++++++++++++++--- .../registry-platform-objectstore/src/s3.rs | 6 +- .../src/verifier.rs | 7 +- crates/registry-platform-oidc/src/lib.rs | 77 +++++---- .../registry-platform-oidc/src/task_grant.rs | 4 +- crates/registry-platform-testing/src/lib.rs | 4 +- .../tests/cross_crate_integration.rs | 4 +- .../tests/test_authorization_server.rs | 2 +- crates/registry-render-client/src/lib.rs | 5 +- crates/registry-review-client/src/client.rs | 4 +- .../registry-scheduling-client/src/client.rs | 4 +- crates/registry-scheduling/src/auth.rs | 2 +- crates/registry-scheduling/src/runtime.rs | 2 +- .../registry-thunderid-tooling/src/grant.rs | 2 +- products/platform/CHANGELOG.md | 18 ++ 80 files changed, 458 insertions(+), 253 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cd8a5009f5..b1dfc7958d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7990,6 +7990,7 @@ dependencies = [ "registry-platform-canonical-json", "registry-platform-crypto", "registry-platform-loopback", + "registry-platform-posture", "reqwest 0.12.28", "rustls-native-certs", "serde", diff --git a/crates/registry-adapter-connectors/src/coordinator_event.rs b/crates/registry-adapter-connectors/src/coordinator_event.rs index 2f22dc009a..a1393dcfac 100644 --- a/crates/registry-adapter-connectors/src/coordinator_event.rs +++ b/crates/registry-adapter-connectors/src/coordinator_event.rs @@ -604,7 +604,7 @@ mod tests { let policy = EventDestinationPolicy::new( "coordinator-test", &fixture.origin, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the fixture origin is permitted"); @@ -637,7 +637,7 @@ mod tests { let policy = EventDestinationPolicy::new( "coordinator-test", "http://127.0.0.1:9/", - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the loopback origin is permitted"); diff --git a/crates/registry-adapter-engine/Cargo.toml b/crates/registry-adapter-engine/Cargo.toml index fc26469fb2..a17bd766b8 100644 --- a/crates/registry-adapter-engine/Cargo.toml +++ b/crates/registry-adapter-engine/Cargo.toml @@ -58,6 +58,7 @@ registry-platform-script.workspace = true registry-platform-yaml.workspace = true [dev-dependencies] +registry-platform-httputil = { workspace = true, features = ["test-support"] } registry-platform-sqlite = { workspace = true, features = ["fixture"] } serde_norway.workspace = true tempfile.workspace = true diff --git a/crates/registry-adapter-engine/src/egress.rs b/crates/registry-adapter-engine/src/egress.rs index 8545d5e78b..30e94b6a1b 100644 --- a/crates/registry-adapter-engine/src/egress.rs +++ b/crates/registry-adapter-engine/src/egress.rs @@ -2137,7 +2137,7 @@ pub(crate) fn destination_profile(parsed_base: &url::Url) -> DestinationProfile } match parsed_base.scheme() { "https" => DestinationProfile::ProductionHttps, - _ if denotes_loopback(parsed_base) => DestinationProfile::LoopbackDevelopmentHttp, + _ if denotes_loopback(parsed_base) => DestinationProfile::LoopbackHttp, _ => DestinationProfile::PrivateServiceHttp, } } @@ -2161,7 +2161,7 @@ pub(crate) fn denotes_loopback(origin: &url::Url) -> bool { /// is admitted only under the feature that enables it. pub(crate) fn profile_admits_token_endpoints(profile: DestinationProfile) -> bool { match profile { - DestinationProfile::ProductionHttps | DestinationProfile::LoopbackDevelopmentHttp => true, + DestinationProfile::ProductionHttps | DestinationProfile::LoopbackHttp => true, #[cfg(feature = "postgres-test")] DestinationProfile::PinnedLoopbackHttpsTest => true, _ => false, @@ -3700,11 +3700,11 @@ mod tests { ); assert_eq!( destination_profile(&loopback), - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp ); assert_eq!( destination_profile(&localhost), - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp ); assert_eq!( destination_profile(&private), @@ -3722,7 +3722,7 @@ mod tests { let origin = url::Url::parse(spelled).expect("parsed"); assert_eq!( destination_profile(&origin), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, "{spelled}" ); } @@ -3769,7 +3769,7 @@ mod tests { DestinationProfile::ProductionHttps )); assert!(profile_admits_token_endpoints( - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp )); assert!(!profile_admits_token_endpoints( DestinationProfile::PrivateServiceHttp diff --git a/crates/registry-adapter-job/src/runtime_destination.rs b/crates/registry-adapter-job/src/runtime_destination.rs index c365f2b07d..430f99b320 100644 --- a/crates/registry-adapter-job/src/runtime_destination.rs +++ b/crates/registry-adapter-job/src/runtime_destination.rs @@ -245,7 +245,7 @@ async fn activate_direct<'a>( .with_fetch_url_policy(if token_endpoint.is_https() { FetchUrlPolicy::strict() } else { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() }); if let Some(profile) = token_tls_trust_profile { let roots = registry_adapter_engine::auth::capture_ca_bundle(core, profile.as_str()) @@ -418,7 +418,7 @@ fn activate_signed<'a>( let profile = if base_url.is_https() { DestinationProfile::ProductionHttps } else { - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp }; let private_cidrs = core .allowed_private_cidrs diff --git a/crates/registry-adapter-job/src/signed_coordinator_event.rs b/crates/registry-adapter-job/src/signed_coordinator_event.rs index 08bf9edaa1..71d335a54b 100644 --- a/crates/registry-adapter-job/src/signed_coordinator_event.rs +++ b/crates/registry-adapter-job/src/signed_coordinator_event.rs @@ -341,7 +341,7 @@ mod tests { registry_platform_httputil::destination::EventDestinationPolicy::new( "coordinator-test", "http://127.0.0.1:9/", - registry_platform_httputil::destination::DestinationProfile::LoopbackDevelopmentHttp, + registry_platform_httputil::destination::DestinationProfile::LoopbackHttp, &[], ) .expect("the inert destination policy freezes"), diff --git a/crates/registry-adapter-job/tests/signed_coordinator_event_native.rs b/crates/registry-adapter-job/tests/signed_coordinator_event_native.rs index d3bca6242b..925602b9bd 100644 --- a/crates/registry-adapter-job/tests/signed_coordinator_event_native.rs +++ b/crates/registry-adapter-job/tests/signed_coordinator_event_native.rs @@ -746,13 +746,8 @@ async fn assert_revised_run_used_unresolved_review( fn maintained_destination(base_url: &str, policy_name: &str) -> SignedCoordinatorEventDestination { let policy = Arc::new( - EventDestinationPolicy::new( - policy_name, - base_url, - DestinationProfile::LoopbackDevelopmentHttp, - &[], - ) - .expect("the maintained event policy freezes"), + EventDestinationPolicy::new(policy_name, base_url, DestinationProfile::LoopbackHttp, &[]) + .expect("the maintained event policy freezes"), ); let connector = Arc::new( CoordinatorEventConnector::new(policy, SOURCE, KEY.to_vec(), Duration::from_secs(3)) @@ -885,7 +880,7 @@ async fn a_lost_native_event_answer_recovers_the_same_coordinator_run() { EventDestinationPolicy::new( "adapter-native-coordinator", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the native event policy freezes"), @@ -1193,7 +1188,7 @@ async fn postgres_source_reaches_native_coordinator_and_reviews_a_revised_row() EventDestinationPolicy::new( "adapter-native-coordinator-postgres", &coordinator.origin, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the native PostgreSQL event policy freezes"), diff --git a/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs b/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs index 503c362f01..57a03dc43a 100644 --- a/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs +++ b/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs @@ -250,7 +250,7 @@ async fn a_lost_signed_event_answer_recovers_one_run_through_the_job_store() { EventDestinationPolicy::new( "adapter-coordinator-events", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the loopback event policy freezes"), @@ -343,7 +343,7 @@ async fn pending_job_version_drift_stops_before_wire_and_restore_recovers() { EventDestinationPolicy::new( "adapter-coordinator-body-drift", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the event policy freezes"), @@ -475,7 +475,7 @@ async fn a_submicrosecond_event_time_keeps_identical_retry_bytes_after_store_rou EventDestinationPolicy::new( "adapter-coordinator-submicrosecond", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the event policy freezes"), @@ -678,7 +678,7 @@ async fn coordinator_item_and_deployment_failures_never_fall_back() { EventDestinationPolicy::new( "adapter-coordinator-problems", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the problem event policy freezes"), @@ -847,7 +847,7 @@ async fn scripted_destination( EventDestinationPolicy::new( "adapter-coordinator-refused-retry", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the event policy freezes"), @@ -1487,7 +1487,7 @@ fn revision_destination(base_url: &str, revised: &str) -> SignedCoordinatorEvent EventDestinationPolicy::new( REVISION_BINDING, base_url, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the event policy freezes"), diff --git a/crates/registry-adapter/src/payments/g2p_service.rs b/crates/registry-adapter/src/payments/g2p_service.rs index e1530d4e7b..9eb40dc398 100644 --- a/crates/registry-adapter/src/payments/g2p_service.rs +++ b/crates/registry-adapter/src/payments/g2p_service.rs @@ -22,7 +22,9 @@ 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 registry_platform_httputil::{ + read_bounded, validate_response_headers_without_peer_policy, ServiceBaseUrl, +}; use serde::Serialize; use serde_json::Value; use std::{collections::BTreeMap, future::Future, pin::Pin, sync::Arc, time::Duration}; @@ -322,7 +324,8 @@ impl HttpG2pProvider { .send() .await .map_err(|_| G2pProviderError::Unavailable)?; - validate_response_headers(response.headers()).map_err(|_| G2pProviderError::Unavailable)?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| G2pProviderError::Unavailable)?; let status = response.status().as_u16(); let body = read_bounded(response, 131_072) .await @@ -417,7 +420,7 @@ impl G2pProviderPort for HttpG2pProvider { .execute(prepared) .await .map_err(|_| G2pProviderError::OutcomeUnknown)?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| G2pProviderError::OutcomeUnknown)?; let status = response.status().as_u16(); let signature = match &response_trust { diff --git a/crates/registry-adapter/src/payments/service.rs b/crates/registry-adapter/src/payments/service.rs index e7c364a5af..456892aee7 100644 --- a/crates/registry-adapter/src/payments/service.rs +++ b/crates/registry-adapter/src/payments/service.rs @@ -28,7 +28,9 @@ use registry_payment_simulator_connector::{ConnectorError, Observation, Simulato use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_config::SecretResolver; use registry_platform_httputil::client::BearerToken; -use registry_platform_httputil::{read_bounded, validate_response_headers, ServiceBaseUrl}; +use registry_platform_httputil::{ + read_bounded, validate_response_headers_without_peer_policy, ServiceBaseUrl, +}; use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; use tokio::sync::Semaphore; use uuid::Uuid; @@ -237,7 +239,7 @@ impl ProviderPort for SyntheticProvider { .execute(request) .await .map_err(|_| ConnectorError::Unknown)?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| ConnectorError::Unknown)?; let status = response.status().as_u16(); let body = read_bounded(response, 131_072) @@ -489,7 +491,7 @@ impl SyntheticProvider { ConnectorError::Unavailable } })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { if prepared.method == PaymentHttpMethod::Post { ConnectorError::Unknown } else { diff --git a/crates/registry-adapterctl/src/verify/mod.rs b/crates/registry-adapterctl/src/verify/mod.rs index d759ce7f80..e38b5eae2f 100644 --- a/crates/registry-adapterctl/src/verify/mod.rs +++ b/crates/registry-adapterctl/src/verify/mod.rs @@ -872,7 +872,7 @@ fn destination_profile(base: &Url) -> DestinationProfile { } match parsed.scheme() { "https" => DestinationProfile::ProductionHttps, - _ if denotes_loopback(base) => DestinationProfile::LoopbackDevelopmentHttp, + _ if denotes_loopback(base) => DestinationProfile::LoopbackHttp, _ => DestinationProfile::PrivateServiceHttp, } } diff --git a/crates/registry-breg-client/src/transport.rs b/crates/registry-breg-client/src/transport.rs index b158bda52f..a18ce14525 100644 --- a/crates/registry-breg-client/src/transport.rs +++ b/crates/registry-breg-client/src/transport.rs @@ -2,7 +2,7 @@ use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use reqwest::header::{HeaderMap, CONTENT_TYPE}; use reqwest::{Response, Url}; @@ -52,7 +52,7 @@ impl Transport { .send() .await .map_err(|error| BaseRegistryClientError::transport(send_failure_kind(&error)))?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { BaseRegistryClientError::protocol( response.status().as_u16(), BRegProtocolFailure::HeaderBounds, diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index 97870cf08d..0eb719aef4 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -135,7 +135,7 @@ async fn task_granted_invoke_uses_exact_action_scope_and_frozen_subjects() { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -329,7 +329,7 @@ async fn proposal_task_scopes_and_standing_agent_draft_and_context_permissions_a Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -677,7 +677,7 @@ async fn signed_task_token_cannot_discover_or_invoke_an_ordinary_immediate_actio Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())), ) @@ -1132,7 +1132,7 @@ async fn human_identity_is_the_principal_claim_and_a_human_token_without_it_is_r Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())), ) @@ -1188,7 +1188,7 @@ async fn delegated_token_is_refused_at_immediate_action_admission() { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())) .with_contextual_claims( @@ -1708,7 +1708,7 @@ async fn task_record_reads_intersect_profile_with_composed_proposal_scope() { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -1849,7 +1849,7 @@ impl BoundGrantFixture { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("request_purpose".into())), ) diff --git a/crates/registry-breg/src/event_destination.rs b/crates/registry-breg/src/event_destination.rs index 979bcb9b58..17740cb52e 100644 --- a/crates/registry-breg/src/event_destination.rs +++ b/crates/registry-breg/src/event_destination.rs @@ -464,7 +464,7 @@ impl EventDestinationNetworkProfile { fn platform(self) -> DestinationProfile { match self { Self::ProductionHttps => DestinationProfile::ProductionHttps, - Self::LoopbackDevelopmentHttp => DestinationProfile::LoopbackDevelopmentHttp, + Self::LoopbackDevelopmentHttp => DestinationProfile::LoopbackHttp, #[cfg(feature = "postgres-test")] Self::PinnedLoopbackHttpsTest => DestinationProfile::PinnedLoopbackHttpsTest, } diff --git a/crates/registry-breg/tests/authentication_refusals.rs b/crates/registry-breg/tests/authentication_refusals.rs index 653a850519..87ecf66351 100644 --- a/crates/registry-breg/tests/authentication_refusals.rs +++ b/crates/registry-breg/tests/authentication_refusals.rs @@ -194,7 +194,7 @@ fn key_source(idp: &MockIdp) -> Arc { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )) } @@ -226,7 +226,7 @@ impl Harness { let unreachable = Arc::new(JwksFetcher::new_with_fetch_url_policy( "http://127.0.0.1:9/jwks.json".to_owned(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = RegistryAuthenticator::new( ®istry, diff --git a/crates/registry-breg/tests/concealment_refusals.rs b/crates/registry-breg/tests/concealment_refusals.rs index fc25e9cb53..ac86c35725 100644 --- a/crates/registry-breg/tests/concealment_refusals.rs +++ b/crates/registry-breg/tests/concealment_refusals.rs @@ -186,7 +186,7 @@ fn key_source(idp: &MockIdp) -> Arc { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )) } diff --git a/crates/registry-breg/tests/consent_access.rs b/crates/registry-breg/tests/consent_access.rs index 84140a9d9e..c40725d2d6 100644 --- a/crates/registry-breg/tests/consent_access.rs +++ b/crates/registry-breg/tests/consent_access.rs @@ -885,7 +885,7 @@ mod startup { let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); RegistryAuthenticator::new( registry, @@ -940,7 +940,7 @@ mod startup { let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let claims = AuthorityClaimConfig::new("principal", Some("purpose".to_owned())) .with_contextual_claims( diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index baac93a793..5aefc44b80 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -2427,7 +2427,7 @@ fn authenticator_with_verifier( let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); RegistryAuthenticator::new(registry, verifier, key_source, claims) } @@ -2440,7 +2440,7 @@ fn key_source(idp: &MockIdp) -> Arc { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )) } diff --git a/crates/registry-breg/tests/postgres_access_log.rs b/crates/registry-breg/tests/postgres_access_log.rs index 628c81e912..b18e048867 100644 --- a/crates/registry-breg/tests/postgres_access_log.rs +++ b/crates/registry-breg/tests/postgres_access_log.rs @@ -230,7 +230,7 @@ async fn setup_relationships() -> (TestDatabase, Router, MockIdp) { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); verifier.allowed_clients = vec!["portal".into(), "agency".into()]; @@ -311,7 +311,7 @@ async fn setup_registry(registry: CompiledRegistry) -> (TestDatabase, Router, Mo let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); verifier.allowed_clients = vec!["portal".into(), "agency".into(), "evidence-service".into()]; @@ -1025,7 +1025,7 @@ async fn setup_with_mutations( let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); verifier.allowed_clients = vec!["portal".into(), "agency".into()]; diff --git a/crates/registry-breg/tests/postgres_action_task_grants.rs b/crates/registry-breg/tests/postgres_action_task_grants.rs index d9ea24f579..08f0e78f46 100644 --- a/crates/registry-breg/tests/postgres_action_task_grants.rs +++ b/crates/registry-breg/tests/postgres_action_task_grants.rs @@ -107,7 +107,7 @@ async fn task_action_scope_subjects_replay_and_fresh_revocation_are_enforced() { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())) .with_contextual_claims( @@ -471,7 +471,7 @@ async fn task_record_read_is_bound_to_the_grant_identity_by_the_profile_row_boun Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())) .with_contextual_claims( diff --git a/crates/registry-breg/tests/postgres_consent_access.rs b/crates/registry-breg/tests/postgres_consent_access.rs index df5632237b..244a938405 100644 --- a/crates/registry-breg/tests/postgres_consent_access.rs +++ b/crates/registry-breg/tests/postgres_consent_access.rs @@ -154,7 +154,7 @@ impl Harness { let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.into()]); verifier.allowed_clients = vec![ diff --git a/crates/registry-breg/tests/postgres_data_export.rs b/crates/registry-breg/tests/postgres_data_export.rs index 3a02799a91..b24634123d 100644 --- a/crates/registry-breg/tests/postgres_data_export.rs +++ b/crates/registry-breg/tests/postgres_data_export.rs @@ -449,7 +449,7 @@ fn authenticated_app( let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = Arc::new( RegistryAuthenticator::new( diff --git a/crates/registry-breg/tests/postgres_membership_access.rs b/crates/registry-breg/tests/postgres_membership_access.rs index 2af4beccdf..38ff7fe3a6 100644 --- a/crates/registry-breg/tests/postgres_membership_access.rs +++ b/crates/registry-breg/tests/postgres_membership_access.rs @@ -121,7 +121,7 @@ async fn real_postgres_membership_reads_recheck_live_membership_and_hide_process let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = Arc::new( RegistryAuthenticator::new( diff --git a/crates/registry-breg/tests/postgres_multi_reference_action_authority.rs b/crates/registry-breg/tests/postgres_multi_reference_action_authority.rs index 0238a6017b..53d964dc42 100644 --- a/crates/registry-breg/tests/postgres_multi_reference_action_authority.rs +++ b/crates/registry-breg/tests/postgres_multi_reference_action_authority.rs @@ -300,7 +300,7 @@ fn authenticator( Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())), ) diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index 18868d63c6..b05edc889a 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -6919,7 +6919,7 @@ async fn apply_receipt_replay_refuses_a_task_grant_expiring_at_the_idempotency_l Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("sub", Some("registry_purpose".into())), ) diff --git a/crates/registry-breg/tests/postgres_proposal_security.rs b/crates/registry-breg/tests/postgres_proposal_security.rs index 8a0b1185d5..5d7df42e49 100644 --- a/crates/registry-breg/tests/postgres_proposal_security.rs +++ b/crates/registry-breg/tests/postgres_proposal_security.rs @@ -139,7 +139,7 @@ async fn authenticator( Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) diff --git a/crates/registry-breg/tests/postgres_proposal_task_authority.rs b/crates/registry-breg/tests/postgres_proposal_task_authority.rs index f454c4c941..514edd685e 100644 --- a/crates/registry-breg/tests/postgres_proposal_task_authority.rs +++ b/crates/registry-breg/tests/postgres_proposal_task_authority.rs @@ -330,7 +330,7 @@ async fn authenticator( Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) diff --git a/crates/registry-breg/tests/postgres_registry_extensibility.rs b/crates/registry-breg/tests/postgres_registry_extensibility.rs index cf5f031974..adbe037db8 100644 --- a/crates/registry-breg/tests/postgres_registry_extensibility.rs +++ b/crates/registry-breg/tests/postgres_registry_extensibility.rs @@ -510,7 +510,7 @@ fn build_app( let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = Arc::new( RegistryAuthenticator::new( diff --git a/crates/registry-breg/tests/postgres_required_filters.rs b/crates/registry-breg/tests/postgres_required_filters.rs index f1e1bcb177..6a57d1b78f 100644 --- a/crates/registry-breg/tests/postgres_required_filters.rs +++ b/crates/registry-breg/tests/postgres_required_filters.rs @@ -107,7 +107,7 @@ async fn setup() -> (TestDatabase, Router, MockIdp) { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); verifier.allowed_clients = vec!["portal".into()]; diff --git a/crates/registry-breg/tests/postgres_startup.rs b/crates/registry-breg/tests/postgres_startup.rs index 73e7075d7d..33910d0b13 100644 --- a/crates/registry-breg/tests/postgres_startup.rs +++ b/crates/registry-breg/tests/postgres_startup.rs @@ -2965,7 +2965,7 @@ async fn mock_idp_key_source(idp: &MockIdp) -> Arc { discovery_timeout: Duration::from_secs(5), max_doc_bytes: 16 * 1024, }, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("MockIdp discovery fetch succeeds"); @@ -2979,7 +2979,7 @@ async fn mock_idp_key_source(idp: &MockIdp) -> Arc { request_timeout: Duration::from_secs(5), outage_tolerance: Duration::ZERO, }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )) } diff --git a/crates/registry-breg/tests/support/pilot_acceptance_harness.rs b/crates/registry-breg/tests/support/pilot_acceptance_harness.rs index 9bd0c2fa0e..d26583d06b 100644 --- a/crates/registry-breg/tests/support/pilot_acceptance_harness.rs +++ b/crates/registry-breg/tests/support/pilot_acceptance_harness.rs @@ -188,7 +188,7 @@ impl PilotHarness { request_timeout: Duration::from_secs(5), outage_tolerance: Duration::ZERO, }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let prepared = prepare_with_connection_and_key_source_for_test( &config_path, diff --git a/crates/registry-bregctl/src/data_lifecycle.rs b/crates/registry-bregctl/src/data_lifecycle.rs index 67fdb9ea25..1f429c508c 100644 --- a/crates/registry-bregctl/src/data_lifecycle.rs +++ b/crates/registry-bregctl/src/data_lifecycle.rs @@ -32,7 +32,7 @@ use registry_platform_canonical_json::{canonicalize_json, parse_json_strict}; use registry_platform_httputil::client::{ build_client, OutboundOptions, ServiceBaseUrl, DEFAULT_CONNECT_TIMEOUT, DEFAULT_REQUEST_TIMEOUT, }; -use registry_platform_httputil::{read_bounded, validate_response_headers}; +use registry_platform_httputil::{read_bounded, validate_response_headers_without_peer_policy}; use registry_platform_yaml::{ ApiVersion, Diagnostic, Document, EnvelopeRule, Expect, FormatSpec, Reader, Report, RetiredApiVersion, @@ -1166,7 +1166,7 @@ async fn dispatch_http( .await .map_err(|_| ())?; let status = response.status().as_u16(); - validate_response_headers(response.headers()).map_err(|_| ())?; + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| ())?; let content_type = response .headers() .get(CONTENT_TYPE) diff --git a/crates/registry-casework-client/src/client.rs b/crates/registry-casework-client/src/client.rs index b7e2a47924..152882b688 100644 --- a/crates/registry-casework-client/src/client.rs +++ b/crates/registry-casework-client/src/client.rs @@ -25,7 +25,7 @@ use registry_platform_httputil::client::{ send_failure_kind, KeyedMutationAttempt, OutboundOptions, RetryAfter, ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use registry_review_client::{ ReviewAuth as ProducerReviewAuth, ReviewClient as ProducerReviewClient, @@ -1750,7 +1750,7 @@ impl CaseworkClient { .map_err(|error| CaseworkClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), CaseworkProtocolFailure::HeaderBounds, diff --git a/crates/registry-casework/tests/breg_review_journey.rs b/crates/registry-casework/tests/breg_review_journey.rs index fe989a321a..00317ea55a 100644 --- a/crates/registry-casework/tests/breg_review_journey.rs +++ b/crates/registry-casework/tests/breg_review_journey.rs @@ -740,7 +740,7 @@ async fn native_current_source_approval_pattern(pattern: ApprovalPattern, index: Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - registry_platform_httputil::FetchUrlPolicy::dev(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -805,7 +805,7 @@ async fn native_current_source_approval_pattern(pattern: ApprovalPattern, index: Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - registry_platform_httputil::FetchUrlPolicy::dev(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), )), HumanIdentityConfig::default(), ); @@ -1195,7 +1195,7 @@ async fn native_proposal_journey(producer_id: &'static str) { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - registry_platform_httputil::FetchUrlPolicy::dev(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -1278,7 +1278,7 @@ async fn native_proposal_journey(producer_id: &'static str) { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - registry_platform_httputil::FetchUrlPolicy::dev(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), )), HumanIdentityConfig::default(), ); diff --git a/crates/registry-casework/tests/human_identity_auth.rs b/crates/registry-casework/tests/human_identity_auth.rs index f8d15638ac..c8605cec64 100644 --- a/crates/registry-casework/tests/human_identity_auth.rs +++ b/crates/registry-casework/tests/human_identity_auth.rs @@ -359,7 +359,7 @@ fn authenticator_for_project_with_human_identity( let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); CaseworkAuthenticator::new( project, diff --git a/crates/registry-casework/tests/refusal_golden.rs b/crates/registry-casework/tests/refusal_golden.rs index 4d6423b7f8..16b5f01820 100644 --- a/crates/registry-casework/tests/refusal_golden.rs +++ b/crates/registry-casework/tests/refusal_golden.rs @@ -425,7 +425,7 @@ fn app(idp: &MockIdp, root: &std::path::Path, recorder: Arc) -> let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = CaseworkAuthenticator::new( &project, diff --git a/crates/registry-casework/tests/review_http.rs b/crates/registry-casework/tests/review_http.rs index 750a21d73f..777208804d 100644 --- a/crates/registry-casework/tests/review_http.rs +++ b/crates/registry-casework/tests/review_http.rs @@ -552,7 +552,7 @@ async fn app_with_project_options( Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), HumanIdentityConfig::default(), ) @@ -5854,7 +5854,7 @@ async fn separate_human_source_credentials_bind_before_empty_inbox_and_guard_mut let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = CaseworkAuthenticator::new( &project, diff --git a/crates/registry-casework/tests/review_payment_fixture_postgres.rs b/crates/registry-casework/tests/review_payment_fixture_postgres.rs index c1668890a0..74a091aea1 100644 --- a/crates/registry-casework/tests/review_payment_fixture_postgres.rs +++ b/crates/registry-casework/tests/review_payment_fixture_postgres.rs @@ -587,7 +587,7 @@ async fn payment_http_push_and_feed_recovery_preserve_receiver_and_release_bound Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), HumanIdentityConfig::default(), ); diff --git a/crates/registry-coordinator-client/src/client.rs b/crates/registry-coordinator-client/src/client.rs index 9cb76c43f0..1eb94b69b7 100644 --- a/crates/registry-coordinator-client/src/client.rs +++ b/crates/registry-coordinator-client/src/client.rs @@ -7,7 +7,7 @@ use registry_platform_httputil::client::{ build_client, classify_keyed_attempt, read_failure_kind, retry_keyed_mutation, send_failure_kind, KeyedMutationAttempt, OutboundOptions, RetryAfter, ServiceBaseUrl, }; -use registry_platform_httputil::{read_bounded, validate_response_headers}; +use registry_platform_httputil::{read_bounded, validate_response_headers_without_peer_policy}; use reqwest::{ header::{HeaderMap, ACCEPT, AUTHORIZATION, CONTENT_TYPE}, Method, RequestBuilder, Response, StatusCode, @@ -398,7 +398,7 @@ impl CoordinatorClient { let response = request.send().await.map_err(|e| Error::Transport { kind: send_failure_kind(&e), })?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| protocol(response.status().as_u16(), Failure::HeaderBounds))?; Ok(response) } diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index a22bc778a8..2f5b380197 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -106,7 +106,7 @@ fn config_error() -> CoordinatorError { // reject metadata addresses. Cleartext remains numeric loopback only. fn configured_endpoint_policy(endpoint: &Url) -> FetchUrlPolicy { if endpoint.scheme() == "http" { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() } else { FetchUrlPolicy { allowed_schemes: vec!["https".into()], diff --git a/crates/registry-coordinator/src/decision.rs b/crates/registry-coordinator/src/decision.rs index aef7386bd6..b097f20325 100644 --- a/crates/registry-coordinator/src/decision.rs +++ b/crates/registry-coordinator/src/decision.rs @@ -315,7 +315,7 @@ impl DecisionConnection { timeout: Duration, ) -> std::result::Result { let policy = if self.endpoint.scheme() == "http" { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() } else { FetchUrlPolicy { allowed_schemes: vec!["https".into()], diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index a7c34b1f37..0bc397e345 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -418,7 +418,7 @@ impl ExternalHttpConnection { // peers may be private, but metadata and non-loopback cleartext remain // denied. Each request connects to only the addresses validated here. let policy = if url.scheme() == "http" { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() } else { FetchUrlPolicy { allowed_schemes: vec!["https".into()], diff --git a/crates/registry-coordinator/tests/deployment_surface.rs b/crates/registry-coordinator/tests/deployment_surface.rs index a419dcbc59..5153f7938a 100644 --- a/crates/registry-coordinator/tests/deployment_surface.rs +++ b/crates/registry-coordinator/tests/deployment_surface.rs @@ -137,7 +137,7 @@ async fn verified_subject_owns_runs_and_exact_policy_restricts_flow_action() { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( issuer.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = TokenVerifierConfig::access_token_profile( issuer.issuer(), @@ -212,7 +212,7 @@ async fn a_policy_admits_only_the_subjects_it_lists() { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( issuer.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = TokenVerifierConfig::access_token_profile( issuer.issuer(), @@ -364,7 +364,7 @@ async fn a_token_carrying_act_is_refused_and_an_exchange_without_one_is_not() { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( issuer.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = TokenVerifierConfig::access_token_profile( issuer.issuer(), diff --git a/crates/registry-discovery-client/src/client.rs b/crates/registry-discovery-client/src/client.rs index 174214164d..42431c4c49 100644 --- a/crates/registry-discovery-client/src/client.rs +++ b/crates/registry-discovery-client/src/client.rs @@ -14,7 +14,7 @@ use registry_platform_canonical_json::parse_json_strict; use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; -use registry_platform_httputil::{read_bounded, validate_response_headers}; +use registry_platform_httputil::{read_bounded, validate_response_headers_without_peer_policy}; use reqwest::header::{ACCEPT, CONTENT_TYPE}; use reqwest::{Method, StatusCode}; use serde::de::DeserializeOwned; @@ -257,7 +257,7 @@ impl DiscoveryClient { .send() .await .map_err(|error| DiscoveryClientError::transport(send_failure_kind(&error)))?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| DiscoveryClientError::Protocol)?; let status = response.status(); if status.is_success() && status != StatusCode::OK { diff --git a/crates/registry-discoveryctl/src/build.rs b/crates/registry-discoveryctl/src/build.rs index 04902f2236..67a85630d2 100644 --- a/crates/registry-discoveryctl/src/build.rs +++ b/crates/registry-discoveryctl/src/build.rs @@ -11,7 +11,9 @@ use registry_discovery::{ MAXIMUM_PACKAGE_DEPTH, MAXIMUM_PACKAGE_FILES, PACKAGE_COMMAND, }; use registry_platform_config::{write_package, PackageError, PackageLimits, VerifiedPackage}; -use registry_platform_httputil::{read_bounded, validate_response_headers, FetchUrlPolicy}; +use registry_platform_httputil::{ + read_bounded, validate_response_headers_without_peer_policy, FetchUrlPolicy, +}; use reqwest::header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE}; use sha2::{Digest as _, Sha256}; use thiserror::Error; @@ -162,7 +164,7 @@ async fn fetch_origins( fetch_timeout: Duration, ) -> Result<(Vec, Vec), BuildError> { let policy = if allow_loopback { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() } else { FetchUrlPolicy::strict() }; @@ -183,7 +185,8 @@ async fn fetch_origins( .send() .await .map_err(|_| BuildError::Fetch)?; - validate_response_headers(response.headers()).map_err(|_| BuildError::Fetch)?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| BuildError::Fetch)?; if response.status() != reqwest::StatusCode::OK || !exact_profile_media_type(response.headers()) || response diff --git a/crates/registry-documents-client/src/client.rs b/crates/registry-documents-client/src/client.rs index ada3adc05f..34ed862761 100644 --- a/crates/registry-documents-client/src/client.rs +++ b/crates/registry-documents-client/src/client.rs @@ -17,7 +17,8 @@ use registry_platform_httputil::client::{ MAXIMUM_TRUSTED_ROOT_CERTIFICATE_BUNDLE_BYTES, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, BoundedReadError, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, + BoundedReadError, }; use registry_platform_yaml::Digest; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE}; @@ -285,7 +286,7 @@ impl DocumentsClient { kind: send_failure_kind(&error), })?; let status = response.status(); - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| protocol(status, DocumentsProtocolFailure::HeaderBounds, None))?; if status != StatusCode::OK { return Err(problem_or_status(response).await); @@ -696,7 +697,7 @@ impl DocumentsClient { .map_err(|error| DocumentsClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), DocumentsProtocolFailure::HeaderBounds, diff --git a/crates/registry-evidence-client/src/client.rs b/crates/registry-evidence-client/src/client.rs index 5c0023043a..a1ab5cec5d 100644 --- a/crates/registry-evidence-client/src/client.rs +++ b/crates/registry-evidence-client/src/client.rs @@ -16,8 +16,8 @@ use registry_evidence_verifier::{ EVIDENCE_REQUEST_BATCH_MEDIA_TYPE, EVIDENCE_REQUEST_BATCH_SCHEMA_V1, }; use registry_platform_httputil::{ - read_bounded, retry_after_seconds, validate_response_headers, ExchangeAuthorization, - FetchUrlPolicy, + read_bounded, retry_after_seconds, validate_response_headers_without_peer_policy, + ExchangeAuthorization, FetchUrlPolicy, }; use reqwest::{ header::{ @@ -859,7 +859,7 @@ impl EvidenceClient { .await .map_err(|error| EvidenceClientError::transport(outbound::send_failure_kind(&error)))?; let response_status = response.status(); - if validate_response_headers(response.headers()).is_err() { + if validate_response_headers_without_peer_policy(response.headers()).is_err() { return Err(metadata_protocol_failure_with_status(response_status)); } let response_etag = metadata_etag(response.headers()) @@ -1382,7 +1382,7 @@ impl EvidenceClient { max_bytes: u64, ) -> Result { let status = response.status().as_u16(); - if validate_response_headers(response.headers()).is_err() { + if validate_response_headers_without_peer_policy(response.headers()).is_err() { return Err(EvidenceClientError::Protocol { status, code: None, @@ -1673,7 +1673,7 @@ fn metadata_cache_seconds( fn metadata_fetch_policy(trust: &TrustProfile) -> FetchUrlPolicy { match trust { - TrustProfile::LocalLoopbackDiscovery => FetchUrlPolicy::dev(), + TrustProfile::LocalLoopbackDiscovery => FetchUrlPolicy::https_or_loopback(), TrustProfile::HttpsDiscovery | TrustProfile::PinnedJwks { .. } => FetchUrlPolicy::strict(), } } @@ -4262,7 +4262,7 @@ mod tests { validate_metadata_url(&url, &TrustProfile::LocalLoopbackDiscovery).is_ok(), "{target} was rejected" ); - assert!(FetchUrlPolicy::dev() + assert!(FetchUrlPolicy::https_or_loopback() .validate_dns_pinned_for_immediate_fetch(&url) .is_ok()); } @@ -4442,7 +4442,7 @@ mod tests { JSON_MEDIA_TYPE, None, 600, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("first metadata response"); @@ -4452,7 +4452,7 @@ mod tests { JSON_MEDIA_TYPE, Some((&first.value, first.etag.as_ref(), first.cache_seconds)), 600, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("conditional metadata response"); @@ -4480,7 +4480,7 @@ mod tests { JSON_MEDIA_TYPE, None, 600, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await; let Err(error) = result else { @@ -4532,7 +4532,7 @@ mod tests { JSON_MEDIA_TYPE, None, 600, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .is_err()); diff --git a/crates/registry-evidence/src/runtime_tests.rs b/crates/registry-evidence/src/runtime_tests.rs index fc714d6573..f0de73decb 100644 --- a/crates/registry-evidence/src/runtime_tests.rs +++ b/crates/registry-evidence/src/runtime_tests.rs @@ -12632,7 +12632,7 @@ fn fetching_authenticator(jwks_uri: &str) -> Authenticator { Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri.to_owned(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), )); Authenticator::new( diff --git a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs index 57c8aff95e..4a677391fc 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs @@ -117,7 +117,7 @@ fn resource_server_for( let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( authorization.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); Arc::new( ResourceServer::new( @@ -190,7 +190,7 @@ async fn the_authored_resource_is_the_exact_audience_and_metadata_identifier() { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( auth.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = token_verifier(&options, fetcher); @@ -540,7 +540,7 @@ async fn an_unreachable_key_set_is_the_operators_failure() { Arc::new(JwksFetcher::new_with_fetch_url_policy( closed, JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), ), hasher(), @@ -650,7 +650,7 @@ async fn a_token_that_already_names_an_actor_is_refused() { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( auth.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let server = ResourceServer::new( &options, diff --git a/crates/registry-mcp-edge/src/compatibility_tests/server.rs b/crates/registry-mcp-edge/src/compatibility_tests/server.rs index 73b78e7f60..2938e25147 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/server.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/server.rs @@ -101,7 +101,7 @@ async fn application(resource: &str) -> Router { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( authorization.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let profile = AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![8; 32])).expect("profile"); diff --git a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs index 0943dc52a8..2b2e8acb62 100644 --- a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs +++ b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs @@ -130,7 +130,7 @@ pub(super) fn application( let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let profile = AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![8; 32])).expect("profile"); diff --git a/crates/registry-mcp/src/adapter.rs b/crates/registry-mcp/src/adapter.rs index 427f8d6289..8038d02f28 100644 --- a/crates/registry-mcp/src/adapter.rs +++ b/crates/registry-mcp/src/adapter.rs @@ -1256,7 +1256,8 @@ async fn response_bytes( } else { "application/problem+json" }; - if registry_platform_httputil::validate_response_headers(response.headers()).is_err() + if registry_platform_httputil::validate_response_headers_without_peer_policy(response.headers()) + .is_err() || response .headers() .get("content-type") diff --git a/crates/registry-messaging-client/src/client.rs b/crates/registry-messaging-client/src/client.rs index 61fe339e79..3c174e5d45 100644 --- a/crates/registry-messaging-client/src/client.rs +++ b/crates/registry-messaging-client/src/client.rs @@ -15,7 +15,8 @@ use registry_platform_httputil::client::{ ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, retry_after_seconds, url::append_path_segments, validate_response_headers, + read_bounded, retry_after_seconds, url::append_path_segments, + validate_response_headers_without_peer_policy, }; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use reqwest::{Response, StatusCode, Url}; @@ -389,7 +390,7 @@ impl MessagingClient { .map_err(|error| MessagingClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), MessagingProtocolFailure::HeaderBounds, diff --git a/crates/registry-messaging/src/auth.rs b/crates/registry-messaging/src/auth.rs index 36c7d45598..ba63caea1f 100644 --- a/crates/registry-messaging/src/auth.rs +++ b/crates/registry-messaging/src/auth.rs @@ -588,7 +588,7 @@ pub(crate) mod tests { let during_outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( format!("{}/jwks.json", issuer_keys.uri()), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ))); assert_eq!( during_outage diff --git a/crates/registry-messaging/src/http.rs b/crates/registry-messaging/src/http.rs index 190dfaedc0..f7f68674cf 100644 --- a/crates/registry-messaging/src/http.rs +++ b/crates/registry-messaging/src/http.rs @@ -1580,7 +1580,7 @@ mod tests { let during_outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( format!("{}/jwks.json", issuer_keys.uri()), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ))); let app = router(state_with(during_outage, true)); let headers = expect_problem( @@ -2929,7 +2929,7 @@ mod tests { let outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( format!("{}/jwks.json", issuer_keys.uri()), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ))); let app = router(state_with(outage, true)); snapshots.push( @@ -3242,7 +3242,7 @@ mod tests { let outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( format!("{}/jwks.json", issuer_keys.uri()), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ))); let state = state_with(outage, true); let metrics = Arc::clone(&state.metrics); diff --git a/crates/registry-messaging/src/http_provider/mod.rs b/crates/registry-messaging/src/http_provider/mod.rs index 18d1aac3d1..ea1819c540 100644 --- a/crates/registry-messaging/src/http_provider/mod.rs +++ b/crates/registry-messaging/src/http_provider/mod.rs @@ -377,7 +377,7 @@ impl HttpProviderSettings { let resolved = self.resolve_authentication(package, connection.development, secrets)?; let origin_id = destination_origin_id(provider_id)?; let profile = if connection.development { - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp } else { DestinationProfile::ProductionHttps }; @@ -649,7 +649,7 @@ fn freeze_oauth( trust_bundle_pem: Option<&[u8]>, ) -> Result { let profile = if oauth.development { - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp } else { DestinationProfile::ProductionHttps }; diff --git a/crates/registry-payment-client/src/client.rs b/crates/registry-payment-client/src/client.rs index 37c2303fe0..a3a24934cc 100644 --- a/crates/registry-payment-client/src/client.rs +++ b/crates/registry-payment-client/src/client.rs @@ -14,7 +14,8 @@ use registry_platform_httputil::client::{ ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, retry_after_seconds, url::append_path_segments, validate_response_headers, + read_bounded, retry_after_seconds, url::append_path_segments, + validate_response_headers_without_peer_policy, }; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use reqwest::{Response, StatusCode, Url}; @@ -382,7 +383,7 @@ impl PaymentClient { .map_err(|error| PaymentClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), PaymentProtocolFailure::HeaderBounds, diff --git a/crates/registry-platform-hooks/src/delivery/destination.rs b/crates/registry-platform-hooks/src/delivery/destination.rs index b18f6b86b5..6d90228329 100644 --- a/crates/registry-platform-hooks/src/delivery/destination.rs +++ b/crates/registry-platform-hooks/src/delivery/destination.rs @@ -307,7 +307,7 @@ pub fn url_destination_address( let profile = match parsed.scheme() { "https" => DestinationProfile::ProductionHttps, "http" if parsed.host_str().and_then(loopback_host).is_some() => { - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp } _ => return Err(UrlDestinationError::InvalidBinding), }; @@ -455,7 +455,7 @@ mod tests { assert_eq!(address.profile, DestinationProfile::ProductionHttps); let address = url_destination_address("http://127.0.0.1:9000/in").expect("loopback"); assert_eq!(address.request_target, "/in"); - assert_eq!(address.profile, DestinationProfile::LoopbackDevelopmentHttp); + assert_eq!(address.profile, DestinationProfile::LoopbackHttp); for refused in [ "http://hooks.example/in", "https://user@hooks.example/in", @@ -485,7 +485,7 @@ mod tests { let address = url_destination_address(admitted).expect(admitted); assert_eq!( address.profile, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, "{admitted}" ); } diff --git a/crates/registry-platform-httputil/Cargo.toml b/crates/registry-platform-httputil/Cargo.toml index 2f9776a85f..272e9ea4a9 100644 --- a/crates/registry-platform-httputil/Cargo.toml +++ b/crates/registry-platform-httputil/Cargo.toml @@ -28,6 +28,7 @@ registry-platform-authcommon.workspace = true registry-platform-canonical-json.workspace = true registry-platform-crypto.workspace = true registry-platform-loopback.workspace = true +registry-platform-posture.workspace = true reqwest.workspace = true rustls-native-certs.workspace = true serde.workspace = true diff --git a/crates/registry-platform-httputil/README.md b/crates/registry-platform-httputil/README.md index f93d29e747..33276890eb 100644 --- a/crates/registry-platform-httputil/README.md +++ b/crates/registry-platform-httputil/README.md @@ -13,6 +13,13 @@ Outbound HTTP utilities for registry services. `FetchUrlPolicy` for user-controlled destinations. - `read_bounded` for response bodies with content-length and streaming byte limits. +- `validate_response_headers(headers, PeerPolicy)` for response header bounds + and the peer posture check: `PeerPolicy::RefuseDevelopmentPeer` returns + `ResponseHeaderError::DevelopmentPeer` for a response whose + `Registry-Posture` field is exactly `development`. Every client construction + site chooses the policy. `is_loopback_host` is the one loopback host rule + (a loopback address literal or the exact name `localhost`), valid in every + posture. - `ServiceBaseUrl`, bearer token providers, and `PrivateKeyJwt` for hardened credential-bearing clients without product semantics. The private-key-JWT provider uses a closed `client_credentials` request shape. Its `exchange` @@ -133,13 +140,13 @@ async fn fetch_document() -> Result, Box> { `DestinationProfile::PrivateServiceHttp` refuse `localhost` and every `*.localhost` name when the binding is constructed, including trailing-dot absolute names and regardless of allowed private CIDRs. Local receivers - require `DestinationProfile::LoopbackDevelopmentHttp`. + require `DestinationProfile::LoopbackHttp`. - `FetchUrlPolicy::strict` allows HTTPS only and denies localhost, private ranges, link-local ranges, and cloud metadata endpoints. - Known metadata endpoints include link-local metadata services and public-IP metadata services such as `100.100.100.200`; IPv4-mapped IPv6 literals are normalized before classification. -- `FetchUrlPolicy::dev` allows HTTP and HTTPS, but plain HTTP is allowed only +- `FetchUrlPolicy::https_or_loopback` allows HTTP and HTTPS, but plain HTTP is allowed only for loopback hosts. Non-loopback private ranges stay denied. - `FetchUrlPolicy::validate` is deprecated compatibility. It resolves the host but discards DNS evidence, so it is not sufficient protection for a later @@ -167,6 +174,8 @@ async fn fetch_document() -> Result, Box> { ## Features - Default: `rustls`. +- `test-support`: test-only profiles such as `DestinationProfile::PinnedLoopbackHttpsTest` + and `DestinationProfile::LocalPrivateDevelopmentHttp`. ## Testing diff --git a/crates/registry-platform-httputil/src/client/exchange_authorization.rs b/crates/registry-platform-httputil/src/client/exchange_authorization.rs index e84a9a1f07..4553be278f 100644 --- a/crates/registry-platform-httputil/src/client/exchange_authorization.rs +++ b/crates/registry-platform-httputil/src/client/exchange_authorization.rs @@ -323,7 +323,7 @@ impl ExchangeAssertionSource for RemoteAssertionSource { kind: send_failure_kind(&error), })?; let status = response.status().as_u16(); - if crate::validate_response_headers(response.headers()).is_err() { + if crate::validate_response_headers_without_peer_policy(response.headers()).is_err() { return Err(TokenError::Protocol { status }); } if status != 200 { @@ -1374,7 +1374,7 @@ mod tests { ) .unwrap(); provider.bearer_token().await.unwrap(); - let provider = provider.with_fetch_url_policy(crate::FetchUrlPolicy::dev()); + let provider = provider.with_fetch_url_policy(crate::FetchUrlPolicy::https_or_loopback()); provider.bearer_token().await.unwrap(); assert_eq!(server.received_requests().await.unwrap().len(), 2); } diff --git a/crates/registry-platform-httputil/src/client/mod.rs b/crates/registry-platform-httputil/src/client/mod.rs index fabfee825c..22516844b7 100644 --- a/crates/registry-platform-httputil/src/client/mod.rs +++ b/crates/registry-platform-httputil/src/client/mod.rs @@ -20,8 +20,8 @@ pub use exchange_authorization::{ }; pub use exchange_config::exchange_authorization_from_json; pub use outbound::{ - base_url_without_userinfo, build_client, read_failure_kind, send_failure_kind, - transport_protects_the_credential, OutboundOptions, + base_url_without_userinfo, build_client, is_loopback_host, read_failure_kind, + send_failure_kind, transport_protects_the_credential, OutboundOptions, }; pub use private_key_jwt::{ valid_resource_uri, valid_scope_token, validate_requested_scopes, PrivateKeyJwt, diff --git a/crates/registry-platform-httputil/src/client/outbound.rs b/crates/registry-platform-httputil/src/client/outbound.rs index 7952b00c8c..b957e872c8 100644 --- a/crates/registry-platform-httputil/src/client/outbound.rs +++ b/crates/registry-platform-httputil/src/client/outbound.rs @@ -39,21 +39,26 @@ pub fn build_client(options: OutboundOptions<'_>) -> Result) -> bool { + crate::loopback::loopback_host(&host.to_string()).is_some() +} + /// Whether this URL's transport keeps a secret sent to it away from the network. /// -/// A secret in cleartext is only acceptable when it cannot leave the host, which -/// is the local development and tutorial case. The accepted forms are the ones an -/// adopter types: a loopback address literal, or the reserved name `localhost`. -/// Any other name is refused, because a name that happens to resolve to a -/// loopback address is still resolved off-host, and the answer can change. The +/// A secret in cleartext is only acceptable when it cannot leave the host: https, +/// or http to a host on the loopback transport class ([`is_loopback_host`]). The /// client built by [`build_client`] is pinned to the loopback addresses for -/// `localhost`, so the name is never resolved off-host. +/// `localhost`, so that name is never resolved off-host. pub fn transport_protects_the_credential(url: &Url) -> bool { match url.scheme() { "https" => true, - "http" => url - .host() - .is_some_and(|host| crate::loopback::loopback_host(&host.to_string()).is_some()), + "http" => url.host().is_some_and(|host| is_loopback_host(&host)), _ => false, } } @@ -183,6 +188,33 @@ mod tests { } } + #[test] + fn the_loopback_host_rule_accepts_numeric_loopback_and_the_exact_name_localhost() { + for raw in [ + "http://127.0.0.1/", + "http://127.9.9.9/", + "http://[::1]/", + "http://[::ffff:127.0.0.1]/", + "http://localhost/", + "http://LOCALHOST/", + ] { + let url = Url::parse(raw).expect("url"); + assert!(is_loopback_host(&url.host().expect("host")), "{raw}"); + } + for raw in [ + "http://a.localhost/", + "http://localhost./", + "http://10.0.0.1/", + "http://[::ffff:10.0.0.1]/", + "http://0.0.0.0/", + "http://[fe80::1]/", + "http://example.org/", + ] { + let url = Url::parse(raw).expect("url"); + assert!(!is_loopback_host(&url.host().expect("host")), "{raw}"); + } + } + #[tokio::test] async fn a_connect_timeout_is_a_connection_failure() { let (address, _listener, _held) = unanswered_address().await; diff --git a/crates/registry-platform-httputil/src/client/private_key_jwt.rs b/crates/registry-platform-httputil/src/client/private_key_jwt.rs index a646681ec0..6a4760e264 100644 --- a/crates/registry-platform-httputil/src/client/private_key_jwt.rs +++ b/crates/registry-platform-httputil/src/client/private_key_jwt.rs @@ -35,7 +35,9 @@ use std::{ time::{Duration, Instant}, }; -use crate::{read_bounded, validate_response_headers, FetchUrlError, FetchUrlPolicy}; +use crate::{ + read_bounded, validate_response_headers_without_peer_policy, FetchUrlError, FetchUrlPolicy, +}; use async_trait::async_trait; use chrono::Utc; use registry_platform_authcommon::client_assertion::{ @@ -557,8 +559,8 @@ impl PrivateKeyJwtConfig { /// /// Existing consumers retain their configured-endpoint behavior unless /// they opt in. Discovery-driven clients should always opt in, using - /// [`FetchUrlPolicy::strict`] in production and [`FetchUrlPolicy::dev`] - /// only for an explicitly selected local development profile. + /// [`FetchUrlPolicy::strict`] unless the endpoint may be on loopback, where + /// [`FetchUrlPolicy::https_or_loopback`] admits plain HTTP to the loopback class. #[must_use] pub fn with_fetch_url_policy(mut self, policy: FetchUrlPolicy) -> Self { self.fetch_url_policy = Some(policy); @@ -1067,7 +1069,7 @@ impl PrivateKeyJwt { })?; let status = response.status().as_u16(); - if validate_response_headers(response.headers()).is_err() { + if validate_response_headers_without_peer_policy(response.headers()).is_err() { return Err(TokenError::Protocol { status }); } let media_type = exact_content_type(response.headers()).map(str::to_owned); @@ -1639,7 +1641,7 @@ mod tests { let clock = Arc::new(TestClock::new(NOW)); let provider = PrivateKeyJwt::with_clock( config(endpoint(&server.uri()), client_key(Some(KEY_ID))) - .with_fetch_url_policy(FetchUrlPolicy::dev()), + .with_fetch_url_policy(FetchUrlPolicy::https_or_loopback()), clock, ) .expect("the DNS-pinned provider is usable"); @@ -1683,7 +1685,7 @@ mod tests { let clock = Arc::new(TestClock::new(NOW)); let provider = PrivateKeyJwt::with_clock( config(endpoint(&server.uri()), client_key(Some(KEY_ID))) - .with_fetch_url_policy(FetchUrlPolicy::dev()), + .with_fetch_url_policy(FetchUrlPolicy::https_or_loopback()), clock, ) .expect("the DNS-pinned provider is usable"); diff --git a/crates/registry-platform-httputil/src/destination.rs b/crates/registry-platform-httputil/src/destination.rs index cca6736819..6d7cc1bec7 100644 --- a/crates/registry-platform-httputil/src/destination.rs +++ b/crates/registry-platform-httputil/src/destination.rs @@ -267,9 +267,11 @@ pub enum DestinationProfile { ProductionHttps, /// Plain HTTP for one signed service hop confined to private addresses. PrivateServiceHttp, - /// Plain HTTP to an explicitly configured loopback host for development. - LoopbackDevelopmentHttp, - /// Plain HTTP to one exact, explicitly allowed private IP for local development. + /// Plain HTTP to an explicit loopback host: a loopback address literal or the + /// exact name `localhost`. Valid in every posture. + LoopbackHttp, + /// Test-only plain HTTP to one exact, explicitly allowed private IP. + #[cfg(any(test, feature = "test-support"))] LocalPrivateDevelopmentHttp, /// Test-only HTTPS profile that remains confined to loopback addresses. #[cfg(any(test, feature = "test-support"))] @@ -515,7 +517,7 @@ impl FixedDestinationPolicy { DestinationProfile::PrivateServiceHttp if origin.scheme() != "http" => { return Err(DestinationPolicyError::PrivateServiceRequiresHttp); } - DestinationProfile::LoopbackDevelopmentHttp => { + DestinationProfile::LoopbackHttp => { if origin.scheme() != "http" { return Err(DestinationPolicyError::DevelopmentRequiresHttp); } @@ -523,6 +525,7 @@ impl FixedDestinationPolicy { return Err(DestinationPolicyError::DevelopmentRequiresLoopbackHost); } } + #[cfg(any(test, feature = "test-support"))] DestinationProfile::LocalPrivateDevelopmentHttp => { if origin.scheme() != "http" { return Err(DestinationPolicyError::LocalPrivateDevelopmentRequiresHttp); @@ -943,13 +946,14 @@ impl FixedDestinationPolicy { Err(DestinationSendError::PrivateAddressNotAllowed) } } - DestinationProfile::LoopbackDevelopmentHttp => { + DestinationProfile::LoopbackHttp => { if is_loopback(ip) { Ok(()) } else { Err(DestinationSendError::DevelopmentAddressDenied) } } + #[cfg(any(test, feature = "test-support"))] DestinationProfile::LocalPrivateDevelopmentHttp => { if is_cloud_metadata_ip(ip) { return Err(DestinationSendError::CloudMetadataDenied); @@ -4664,14 +4668,19 @@ fn is_valid_header_value(value: &[u8]) -> bool { } fn validate_response_headers(headers: &HeaderMap) -> Result<(), DestinationSendError> { - match crate::validate_response_headers(headers) { + // The delivering process's peer policy is not threaded to destinations yet, so + // this check keeps to the bounds and accepts every peer posture. + match crate::validate_response_headers(headers, crate::PeerPolicy::AcceptDevelopmentPeer) { Ok(()) => Ok(()), - Err(crate::ResponseHeaderBoundError::TooManyFields) => { + Err(crate::ResponseHeaderError::TooManyFields) => { Err(DestinationSendError::TooManyResponseHeaders) } - Err(crate::ResponseHeaderBoundError::HeadersTooLarge) => { + Err(crate::ResponseHeaderError::HeadersTooLarge) => { Err(DestinationSendError::ResponseHeaderBytesExceeded) } + Err(crate::ResponseHeaderError::DevelopmentPeer) => { + unreachable!("a policy that accepts development peers never refuses one") + } } } @@ -4695,6 +4704,7 @@ fn origin_uses_localhost_namespace(origin: &Url) -> bool { } } +#[cfg(any(test, feature = "test-support"))] fn origin_explicit_private_ip(origin: &Url) -> Option { match origin.host() { Some(::url::Host::Ipv4(ip)) => Some(IpAddr::V4(ip)), @@ -4703,6 +4713,7 @@ fn origin_explicit_private_ip(origin: &Url) -> Option { } } +#[cfg(any(test, feature = "test-support"))] fn private_cidr_is_exact_host(cidr: IpNet, address: IpAddr) -> bool { match (cidr, address) { (IpNet::V4(cidr), IpAddr::V4(address)) => { @@ -5239,7 +5250,7 @@ mod tests { let policy = DataDestinationPolicy::new( "private-data", "http://127.0.0.1:9443/", - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("loopback policy") @@ -5567,19 +5578,14 @@ mod tests { "http://[::1]:8080/", "http://[::ffff:127.0.0.1]:8080/", ] { - DataDestinationPolicy::new( - "dev-data", - raw, - DestinationProfile::LoopbackDevelopmentHttp, - &[], - ) - .unwrap_or_else(|error| panic!("{raw} should validate: {error}")); + DataDestinationPolicy::new("dev-data", raw, DestinationProfile::LoopbackHttp, &[]) + .unwrap_or_else(|error| panic!("{raw} should validate: {error}")); } assert_eq!( DataDestinationPolicy::new( "dev-data", "http://service.test:8080/", - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .unwrap_err(), @@ -5690,7 +5696,7 @@ mod tests { assert!(error.to_string().contains("private CIDR"), "{error}"); for profile in [ DestinationProfile::ProductionHttps, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, ] { let origin = match profile { DestinationProfile::ProductionHttps => "https://registry.example/", @@ -7036,7 +7042,7 @@ mod tests { let strict = DataDestinationPolicy::new( "strict-data", &origin, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("legacy constructor remains valid"); @@ -7060,7 +7066,7 @@ mod tests { let ipv4_only = DataDestinationPolicy::new_with_dns_family( "ipv4-data", &origin, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], DestinationDnsFamily::Ipv4Only, ) @@ -7123,7 +7129,7 @@ mod tests { let policy = DataDestinationPolicy::new( "dev-data", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development policy validates"); @@ -7198,7 +7204,7 @@ mod tests { let policy = CredentialDestinationPolicy::new( "dev-oauth", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development credential policy validates"); @@ -7275,7 +7281,7 @@ mod tests { let policy = CredentialDestinationPolicy::new( "dev-oauth-basic", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development credential policy validates"); @@ -7697,7 +7703,7 @@ mod tests { let policy = EventDestinationPolicy::new( "dev-events", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development event policy"); @@ -7801,7 +7807,7 @@ mod tests { let policy = EventDestinationPolicy::new( "dev-event-bounds", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development event policy"); @@ -8384,7 +8390,7 @@ mod tests { DataDestinationPolicy::new( "message-provider", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("loopback send policy validates") diff --git a/crates/registry-platform-httputil/src/lib.rs b/crates/registry-platform-httputil/src/lib.rs index 912c39b4e3..d3adef3298 100644 --- a/crates/registry-platform-httputil/src/lib.rs +++ b/crates/registry-platform-httputil/src/lib.rs @@ -32,42 +32,83 @@ pub const MAXIMUM_TRUSTED_ROOT_CERTIFICATE_BUNDLE_BYTES: usize = 1024 * 1024; /// Maximum certificates accepted in one outbound client's pinned CA bundle. pub const MAXIMUM_TRUSTED_ROOT_CERTIFICATES: usize = 32; -/// Value-free reason a response's headers exceeded the shared client bounds. +/// Whether a runtime refuses a response whose peer declares the development posture. +/// +/// There is no default: every client construction site chooses. A production runtime +/// passes [`PeerPolicy::RefuseDevelopmentPeer`], a development runtime passes +/// [`PeerPolicy::AcceptDevelopmentPeer`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PeerPolicy { + /// Refuse a response that declares the development posture. + RefuseDevelopmentPeer, + /// Accept a response whatever posture it declares. + AcceptDevelopmentPeer, +} + +/// Value-free reason a response's headers were refused by the shared client checks. #[derive(Debug, Error, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] -pub enum ResponseHeaderBoundError { +pub enum ResponseHeaderError { #[error("the response carries too many header fields")] TooManyFields, #[error("the response headers exceed the configured maximum")] HeadersTooLarge, + #[error( + "the peer declared the development posture; a production runtime refuses its responses" + )] + DevelopmentPeer, } -/// Enforce strict field-count and aggregate-byte bounds before inspecting response headers. -pub fn validate_response_headers(headers: &HeaderMap) -> Result<(), ResponseHeaderBoundError> { +/// Enforce strict field-count and aggregate-byte bounds before inspecting response headers, +/// then refuse a development-marked peer when `peer` says to. +/// +/// The peer's posture field is the exact value `development`. An absent field, +/// `production`, or any other value passes. +pub fn validate_response_headers( + headers: &HeaderMap, + peer: PeerPolicy, +) -> Result<(), ResponseHeaderError> { let mut count = 0usize; let mut total = 0usize; for (name, value) in headers { count = count .checked_add(1) - .ok_or(ResponseHeaderBoundError::TooManyFields)?; + .ok_or(ResponseHeaderError::TooManyFields)?; if count > MAXIMUM_RESPONSE_HEADER_FIELDS { - return Err(ResponseHeaderBoundError::TooManyFields); + return Err(ResponseHeaderError::TooManyFields); } let field_bytes = name .as_str() .len() .checked_add(value.as_bytes().len()) - .ok_or(ResponseHeaderBoundError::HeadersTooLarge)?; + .ok_or(ResponseHeaderError::HeadersTooLarge)?; total = total .checked_add(field_bytes) - .ok_or(ResponseHeaderBoundError::HeadersTooLarge)?; + .ok_or(ResponseHeaderError::HeadersTooLarge)?; if total > MAXIMUM_RESPONSE_HEADER_BYTES { - return Err(ResponseHeaderBoundError::HeadersTooLarge); + return Err(ResponseHeaderError::HeadersTooLarge); } } + if peer == PeerPolicy::RefuseDevelopmentPeer + && headers + .get_all(registry_platform_posture::POSTURE_HEADER) + .iter() + .any(|value| value.as_bytes() == registry_platform_posture::DEVELOPMENT.as_bytes()) + { + return Err(ResponseHeaderError::DevelopmentPeer); + } Ok(()) } +/// [`validate_response_headers`] with [`PeerPolicy::RefuseDevelopmentPeer`], for call +/// sites that have not yet received their runtime's policy. Removed once every client +/// takes a required [`PeerPolicy`]. +pub fn validate_response_headers_without_peer_policy( + headers: &HeaderMap, +) -> Result<(), ResponseHeaderError> { + validate_response_headers(headers, PeerPolicy::RefuseDevelopmentPeer) +} + /// Parse exactly one RFC 9110 delta-seconds `Retry-After` field within a caller bound. /// /// HTTP-date values, duplicate field lines, non-ASCII values, zero, and waits above @@ -408,11 +449,10 @@ impl FetchUrlPolicy { } } - /// Development preset: HTTP and HTTPS are allowed, but plain HTTP only - /// for loopback hosts. Non-loopback private ranges and cloud metadata - /// endpoints stay denied. + /// HTTPS, or plain HTTP to a loopback host. Valid in every posture. + /// Non-loopback private ranges and cloud metadata endpoints stay denied. #[must_use] - pub fn dev() -> Self { + pub fn https_or_loopback() -> Self { Self { allowed_schemes: vec!["http".to_string(), "https".to_string()], allow_localhost: true, @@ -984,7 +1024,7 @@ mod tests { async fn a_pinned_get_trusts_a_private_ca_only_when_it_is_named() { let (addr, authority, _) = serve_under_private_ca().await; let url = reqwest::Url::parse(&format!("https://{addr}/keys")).expect("target URL"); - let validated = FetchUrlPolicy::dev() + let validated = FetchUrlPolicy::https_or_loopback() .validate_dns_pinned_for_immediate_fetch(&url) .expect("loopback HTTPS target"); @@ -1034,7 +1074,7 @@ mod tests { std::env::set_var("SSL_CERT_FILE", &bundle); let url = reqwest::Url::parse(&format!("https://{addr}/keys")).expect("target URL"); - let response = FetchUrlPolicy::dev() + let response = FetchUrlPolicy::https_or_loopback() .validate_dns_pinned_for_immediate_fetch(&url) .expect("loopback HTTPS target") .immediate_get_with_timeout(Duration::from_secs(5)) @@ -1173,7 +1213,7 @@ mod tests { #[test] fn an_ipv4_mapped_loopback_literal_is_loopback_for_a_dev_fetch_only() { let url = reqwest::Url::parse("http://[::ffff:127.0.0.1]:8080/jwks").expect("url parses"); - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() .validate(&url) .expect("a mapped loopback literal is loopback"); assert!(FetchUrlPolicy::strict().validate(&url).is_err()); @@ -1218,7 +1258,7 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let url = reqwest::Url::parse(&format!("{base}/target")).expect("target URL"); - let response = FetchUrlPolicy::dev() + let response = FetchUrlPolicy::https_or_loopback() .validate_dns_pinned_for_immediate_fetch(&url) .expect("development loopback target") .immediate_get() @@ -1628,7 +1668,7 @@ mod tests { "https://[fd00:ec2::254]/latest/meta-data/", ] { let url = reqwest::Url::parse(raw).expect("url parses"); - let err = FetchUrlPolicy::dev() + let err = FetchUrlPolicy::https_or_loopback() .validate(&url) .expect_err("metadata target rejected"); assert!( @@ -1648,9 +1688,11 @@ mod tests { "http://[::ffff:127.0.0.1]/jwks", ] { let url = reqwest::Url::parse(raw).expect("url parses"); - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() .validate(&url) - .unwrap_or_else(|err| panic!("dev policy should accept {raw}: {err}")); + .unwrap_or_else(|err| { + panic!("https-or-loopback policy should accept {raw}: {err}") + }); } for raw in [ @@ -1663,8 +1705,8 @@ mod tests { ] { let url = reqwest::Url::parse(raw).expect("url parses"); assert!( - FetchUrlPolicy::dev().validate(&url).is_err(), - "dev policy must reject {raw}" + FetchUrlPolicy::https_or_loopback().validate(&url).is_err(), + "https-or-loopback policy must reject {raw}" ); } } @@ -1678,8 +1720,8 @@ mod tests { ] { let url = reqwest::Url::parse(raw).expect("url parses"); assert!( - FetchUrlPolicy::dev().validate(&url).is_err(), - "dev policy must reject {raw}" + FetchUrlPolicy::https_or_loopback().validate(&url).is_err(), + "https-or-loopback policy must reject {raw}" ); } } @@ -1721,8 +1763,8 @@ mod tests { too_many.append("x-test", HeaderValue::from_str(&index.to_string()).unwrap()); } assert_eq!( - validate_response_headers(&too_many), - Err(ResponseHeaderBoundError::TooManyFields) + validate_response_headers(&too_many, PeerPolicy::AcceptDevelopmentPeer), + Err(ResponseHeaderError::TooManyFields) ); let mut too_large = HeaderMap::new(); @@ -1730,11 +1772,76 @@ mod tests { "x-canary", HeaderValue::from_bytes(&vec![b'a'; MAXIMUM_RESPONSE_HEADER_BYTES]).unwrap(), ); - let error = validate_response_headers(&too_large).unwrap_err(); - assert_eq!(error, ResponseHeaderBoundError::HeadersTooLarge); + let error = + validate_response_headers(&too_large, PeerPolicy::AcceptDevelopmentPeer).unwrap_err(); + assert_eq!(error, ResponseHeaderError::HeadersTooLarge); assert!(!error.to_string().contains("canary")); } + #[test] + fn peer_policy_table_covers_four_field_states_under_both_policies() { + let header_with = |value: Option<&str>| { + let mut headers = HeaderMap::new(); + if let Some(value) = value { + headers.insert( + registry_platform_posture::POSTURE_HEADER, + HeaderValue::from_str(value).unwrap(), + ); + } + headers + }; + let cases: [(Option<&str>, bool); 5] = [ + (None, false), + (Some("production"), false), + (Some("development"), true), + (Some("Development"), false), + (Some("staging"), false), + ]; + for (value, is_development) in cases { + let headers = header_with(value); + assert_eq!( + validate_response_headers(&headers, PeerPolicy::RefuseDevelopmentPeer), + if is_development { + Err(ResponseHeaderError::DevelopmentPeer) + } else { + Ok(()) + }, + "refuse, {value:?}" + ); + assert_eq!( + validate_response_headers(&headers, PeerPolicy::AcceptDevelopmentPeer), + Ok(()), + "accept, {value:?}" + ); + assert_eq!( + validate_response_headers_without_peer_policy(&headers), + validate_response_headers(&headers, PeerPolicy::RefuseDevelopmentPeer), + "transitional entry point behaves as production, {value:?}" + ); + } + } + + #[test] + fn bounds_are_checked_before_the_peer_posture_under_either_policy() { + let mut too_many = HeaderMap::new(); + for index in 0..=MAXIMUM_RESPONSE_HEADER_FIELDS { + too_many.append("x-test", HeaderValue::from_str(&index.to_string()).unwrap()); + } + too_many.insert( + registry_platform_posture::POSTURE_HEADER, + HeaderValue::from_static("development"), + ); + for policy in [ + PeerPolicy::RefuseDevelopmentPeer, + PeerPolicy::AcceptDevelopmentPeer, + ] { + assert_eq!( + validate_response_headers(&too_many, policy), + Err(ResponseHeaderError::TooManyFields) + ); + } + } + proptest! { #[test] fn append_path_segments_keeps_each_input_as_one_segment( diff --git a/crates/registry-platform-objectstore/src/s3.rs b/crates/registry-platform-objectstore/src/s3.rs index 1ac14a7f9e..e7ef28493a 100644 --- a/crates/registry-platform-objectstore/src/s3.rs +++ b/crates/registry-platform-objectstore/src/s3.rs @@ -11,7 +11,8 @@ use registry_platform_config::{ ObjectStorageConfig, ProtectedSecret, SecretReference, SecretResolver, }; use registry_platform_httputil::{ - read_bounded, validate_response_headers, BoundedReadError, OutboundClientBuilder, + read_bounded, validate_response_headers_without_peer_policy, BoundedReadError, + OutboundClientBuilder, }; use reqwest::{ header::{HeaderMap, HeaderValue}, @@ -405,7 +406,8 @@ impl S3ObjectStore { .send() .await .map_err(|_| ObjectStoreError::Unavailable)?; - validate_response_headers(response.headers()).map_err(|_| ObjectStoreError::Unavailable)?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| ObjectStoreError::Unavailable)?; Ok(response) } diff --git a/crates/registry-platform-objectstore/src/verifier.rs b/crates/registry-platform-objectstore/src/verifier.rs index e4b52dc079..3f0a9e694d 100644 --- a/crates/registry-platform-objectstore/src/verifier.rs +++ b/crates/registry-platform-objectstore/src/verifier.rs @@ -18,7 +18,9 @@ use std::{fmt, time::Duration}; use registry_platform_config::{ AttachmentVerifierConfig, ProtectedSecret, SecretReference, SecretResolver, }; -use registry_platform_httputil::{read_bounded, validate_response_headers, OutboundClientBuilder}; +use registry_platform_httputil::{ + read_bounded, validate_response_headers_without_peer_policy, OutboundClientBuilder, +}; use reqwest::{ header::{HeaderMap, HeaderValue}, StatusCode, Url, @@ -225,7 +227,8 @@ impl HttpVerifier { .send() .await .map_err(|_| VerifierError::Unavailable)?; - validate_response_headers(response.headers()).map_err(|_| VerifierError::Unavailable)?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| VerifierError::Unavailable)?; if response.status() != StatusCode::OK { return Err(VerifierError::Unavailable); } diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index 641c783321..d663eba17f 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -2480,7 +2480,7 @@ mod tests { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); TokenVerifier::new( TokenVerifierConfig { @@ -3573,7 +3573,7 @@ mod tests { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = TokenVerifier::new( TokenVerifierConfig::access_token_profile( @@ -4216,7 +4216,7 @@ mod tests { OidcError::FetchUrl(FetchUrlError::SchemeDenied { .. }) )); - let document = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::dev()) + let document = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::https_or_loopback()) .await .expect("dev policy accepts loopback override"); assert_eq!(document.issuer, cfg.issuer); @@ -4240,7 +4240,7 @@ mod tests { OidcError::FetchUrl(FetchUrlError::SchemeDenied { .. }) )); - let err = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::dev()) + let err = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::https_or_loopback()) .await .expect_err("dev policy rejects returned private jwks_uri"); assert!(matches!( @@ -4260,17 +4260,22 @@ mod tests { max_doc_bytes: DEFAULT_DOC_BYTES, }; - let document = fetch_discovery_at_with_policy(&cfg, &transport, &FetchUrlPolicy::dev()) - .await - .expect("distinct discovery transport accepts exact issuer metadata"); + let document = + fetch_discovery_at_with_policy(&cfg, &transport, &FetchUrlPolicy::https_or_loopback()) + .await + .expect("distinct discovery transport accepts exact issuer metadata"); assert_eq!(document.issuer, canonical_issuer); assert_eq!(document.jwks_uri, jwks_uri); let (mismatched_transport, _) = serve_discovery_document("https://other-issuer.example").await; assert!(matches!( - fetch_discovery_at_with_policy(&cfg, &mismatched_transport, &FetchUrlPolicy::dev()) - .await, + fetch_discovery_at_with_policy( + &cfg, + &mismatched_transport, + &FetchUrlPolicy::https_or_loopback() + ) + .await, Err(OidcError::IssuerMismatch { .. }) )); } @@ -4287,7 +4292,7 @@ mod tests { fetch_discovery_at_with_policy( &cfg, "http://127.0.0.1/metadata", - &FetchUrlPolicy::dev() + &FetchUrlPolicy::https_or_loopback() ) .await, Err(OidcError::ConflictingEndpointConfiguration) @@ -4303,7 +4308,7 @@ mod tests { fetch_discovery_at_with_policy( &empty_issuer, "http://127.0.0.1/metadata", - &FetchUrlPolicy::dev() + &FetchUrlPolicy::https_or_loopback() ) .await, Err(OidcError::MissingIssuer) @@ -4316,7 +4321,8 @@ mod tests { max_doc_bytes: DEFAULT_DOC_BYTES, }; assert!(matches!( - fetch_discovery_at_with_policy(&cfg, "not a URL", &FetchUrlPolicy::dev()).await, + fetch_discovery_at_with_policy(&cfg, "not a URL", &FetchUrlPolicy::https_or_loopback()) + .await, Err(OidcError::InvalidUrl) )); } @@ -4372,7 +4378,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); // A readiness probe repeated every few seconds must not become an @@ -4393,7 +4399,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( "http://127.0.0.1:1/jwks".to_owned(), jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); let error = fetcher @@ -4413,7 +4419,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); let error = fetcher @@ -4452,8 +4458,11 @@ mod tests { let mut config = jwks_test_config(); config.cache_ttl = Duration::from_millis(50); config.outage_tolerance = Duration::from_secs(3600); - let fetcher = - JwksFetcher::new_with_fetch_url_policy(jwks_uri, config, FetchUrlPolicy::dev()); + let fetcher = JwksFetcher::new_with_fetch_url_policy( + jwks_uri, + config, + FetchUrlPolicy::https_or_loopback(), + ); fetcher .key_for_kid("held-kid") @@ -4504,8 +4513,11 @@ mod tests { let mut config = jwks_test_config(); config.cache_ttl = Duration::from_millis(20); config.outage_tolerance = Duration::from_millis(30); - let fetcher = - JwksFetcher::new_with_fetch_url_policy(jwks_uri, config, FetchUrlPolicy::dev()); + let fetcher = JwksFetcher::new_with_fetch_url_policy( + jwks_uri, + config, + FetchUrlPolicy::https_or_loopback(), + ); fetcher .key_for_kid("expiring-kid") @@ -4534,7 +4546,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); fetcher @@ -4559,7 +4571,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); fetcher @@ -4591,7 +4603,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); fetcher @@ -4623,7 +4635,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); let overlong_kid = "x".repeat(DEFAULT_MAX_KID_BYTES + 1); @@ -4671,7 +4683,7 @@ mod tests { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut tasks = Vec::new(); @@ -4701,7 +4713,7 @@ mod tests { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, config, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); fetcher @@ -4736,7 +4748,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); fetcher @@ -4761,8 +4773,11 @@ mod tests { let mut config = jwks_test_config(); config.refresh_cooldown = Duration::from_millis(50); config.negative_cache_ttl = Duration::from_secs(3600); - let fetcher = - JwksFetcher::new_with_fetch_url_policy(jwks_uri, config, FetchUrlPolicy::dev()); + let fetcher = JwksFetcher::new_with_fetch_url_policy( + jwks_uri, + config, + FetchUrlPolicy::https_or_loopback(), + ); fetcher .key_for_kid("old-kid") @@ -4798,7 +4813,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( "http://10.0.0.1/jwks".to_string(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); let err = fetcher @@ -4822,7 +4837,7 @@ mod tests { discovery_timeout: Duration::from_secs(1), max_doc_bytes: DEFAULT_DOC_BYTES, }; - let err = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::dev()) + let err = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::https_or_loopback()) .await .expect_err("empty issuer with override must be rejected"); assert!( @@ -4842,7 +4857,7 @@ mod tests { discovery_timeout: Duration::from_secs(1), max_doc_bytes: DEFAULT_DOC_BYTES, }; - let document = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::dev()) + let document = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::https_or_loopback()) .await .expect("non-empty issuer with override succeeds under dev policy"); assert_eq!(document.issuer, "https://issuer.example"); diff --git a/crates/registry-platform-oidc/src/task_grant.rs b/crates/registry-platform-oidc/src/task_grant.rs index 0a79fc7746..8fcd3a67fe 100644 --- a/crates/registry-platform-oidc/src/task_grant.rs +++ b/crates/registry-platform-oidc/src/task_grant.rs @@ -3,7 +3,7 @@ use crate::{GrantBounds, GrantClaims}; use registry_platform_httputil::{ client::{build_client, OutboundOptions, PrivateKeyJwt, ServiceBaseUrl, TokenProvider}, - read_bounded, validate_response_headers, + read_bounded, validate_response_headers_without_peer_policy, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -236,7 +236,7 @@ impl TaskGrantStatusClient { .send() .await .map_err(|_| TaskGrantError::Unavailable)?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| TaskGrantError::Unavailable)?; // A concealed or absent grant is a refusal. Rejected status-service // credentials do not establish inactive authority and remain unavailable. diff --git a/crates/registry-platform-testing/src/lib.rs b/crates/registry-platform-testing/src/lib.rs index 9de04636a4..f5d814b7a6 100644 --- a/crates/registry-platform-testing/src/lib.rs +++ b/crates/registry-platform-testing/src/lib.rs @@ -528,7 +528,7 @@ mod tests { discovery_timeout: Duration::from_secs(5), max_doc_bytes: 16 * 1024, }, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("discovery fetch succeeds"); @@ -544,7 +544,7 @@ mod tests { request_timeout: Duration::from_secs(5), outage_tolerance: Duration::from_secs(900), }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut config = oidc_verifier_config(idp.issuer(), vec!["registry-api".to_string()]); config.allowed_clients = vec!["client-a".to_string()]; diff --git a/crates/registry-platform-testing/tests/cross_crate_integration.rs b/crates/registry-platform-testing/tests/cross_crate_integration.rs index 9cb613a386..f76790b2b0 100644 --- a/crates/registry-platform-testing/tests/cross_crate_integration.rs +++ b/crates/registry-platform-testing/tests/cross_crate_integration.rs @@ -127,7 +127,7 @@ async fn sample_axum_app_wires_middleware_oidc_and_audit_writer() { discovery_timeout: Duration::from_secs(5), max_doc_bytes: 16 * 1024, }, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("discovery fetch succeeds"); @@ -141,7 +141,7 @@ async fn sample_axum_app_wires_middleware_oidc_and_audit_writer() { request_timeout: Duration::from_secs(5), outage_tolerance: Duration::from_secs(900), }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier_config = oidc_verifier_config(idp.issuer(), vec!["registry-api".to_string()]); verifier_config.allowed_clients = vec!["client-a".to_string()]; diff --git a/crates/registry-platform-testing/tests/test_authorization_server.rs b/crates/registry-platform-testing/tests/test_authorization_server.rs index f886b7485f..33d19a12b6 100644 --- a/crates/registry-platform-testing/tests/test_authorization_server.rs +++ b/crates/registry-platform-testing/tests/test_authorization_server.rs @@ -323,7 +323,7 @@ async fn verifier(server: &TestAuthorizationServer, audience: &str) -> TokenVeri request_timeout: Duration::from_secs(5), outage_tolerance: Duration::from_secs(900), }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut config = server.verifier_config(vec![audience.to_owned()]); config.allowed_clients = vec![CHAT_HOST.to_owned(), GATEWAY.to_owned()]; diff --git a/crates/registry-render-client/src/lib.rs b/crates/registry-render-client/src/lib.rs index ee6c8a6f0c..cb91024b6e 100644 --- a/crates/registry-render-client/src/lib.rs +++ b/crates/registry-render-client/src/lib.rs @@ -8,7 +8,7 @@ use registry_platform_httpsec::{response_trace_id, ProblemDocument}; use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; -use registry_platform_httputil::{read_bounded, validate_response_headers}; +use registry_platform_httputil::{read_bounded, validate_response_headers_without_peer_policy}; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -500,7 +500,8 @@ impl RenderClient { .send() .await .map_err(|error| transport_error(send_failure_kind(&error)))?; - validate_response_headers(response.headers()).map_err(|_| error("protocol"))?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| error("protocol"))?; let trace = response_trace_id(response.headers()) .map_err(|_| error("protocol"))? .to_owned(); diff --git a/crates/registry-review-client/src/client.rs b/crates/registry-review-client/src/client.rs index 724e56993e..45d3ffa523 100644 --- a/crates/registry-review-client/src/client.rs +++ b/crates/registry-review-client/src/client.rs @@ -6,7 +6,7 @@ use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use registry_review_protocol::{ review_cancel_path, review_request_path, review_result_path, ReviewCancelRequest, @@ -732,7 +732,7 @@ impl ReviewClient { .map_err(|error| ReviewClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| protocol(response.status(), ReviewProtocolFailure::HeaderBounds, None))?; Ok(response) } diff --git a/crates/registry-scheduling-client/src/client.rs b/crates/registry-scheduling-client/src/client.rs index 241f0346bd..1d7a54c3b7 100644 --- a/crates/registry-scheduling-client/src/client.rs +++ b/crates/registry-scheduling-client/src/client.rs @@ -9,7 +9,7 @@ use registry_platform_httputil::client::{ send_failure_kind, KeyedMutationAttempt, OutboundOptions, RetryAfter, ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use registry_scheduling_core::{ type_uri, valid_identifier, valid_reference, AdmissionRequest, AppointmentDocument, @@ -775,7 +775,7 @@ impl SchedulingClient { .map_err(|error| SchedulingClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), SchedulingProtocolFailure::HeaderBounds, diff --git a/crates/registry-scheduling/src/auth.rs b/crates/registry-scheduling/src/auth.rs index 79f3481b80..80e79d9d6b 100644 --- a/crates/registry-scheduling/src/auth.rs +++ b/crates/registry-scheduling/src/auth.rs @@ -968,7 +968,7 @@ mod tests { Arc::new(JwksFetcher::new_with_fetch_url_policy( format!("{}/jwks.json", issuer_keys.uri()), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), ); assert!( diff --git a/crates/registry-scheduling/src/runtime.rs b/crates/registry-scheduling/src/runtime.rs index a6ddf19600..996115d9c8 100644 --- a/crates/registry-scheduling/src/runtime.rs +++ b/crates/registry-scheduling/src/runtime.rs @@ -708,7 +708,7 @@ pub fn reminder_transport( // the transport pins the same rule into the frozen policy. let profile = match scheme.as_str() { "https" => DestinationProfile::ProductionHttps, - "http" => DestinationProfile::LoopbackDevelopmentHttp, + "http" => DestinationProfile::LoopbackHttp, _ => return Err("the destination URL scheme is not http(s)".to_owned()), }; let policy = FixedDestinationPolicy::new("scheduling-reminders", &origin, profile, &[]) diff --git a/crates/registry-thunderid-tooling/src/grant.rs b/crates/registry-thunderid-tooling/src/grant.rs index 47282e13be..009eb26948 100644 --- a/crates/registry-thunderid-tooling/src/grant.rs +++ b/crates/registry-thunderid-tooling/src/grant.rs @@ -149,7 +149,7 @@ pub async fn acquire( "Casework refused the grant; check its approval, client, expiry and revocation", )); } - registry_platform_httputil::validate_response_headers(response.headers()) + registry_platform_httputil::validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| refused("the Casework assertion headers exceed their bounds"))?; if response .headers() diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 73991b2494..415b263b99 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -155,6 +155,24 @@ `[127.0.0.1]` are never loopback. Sites that use it accept more literal spellings than before, for example `127.0.0.2` and `[::ffff:127.0.0.1]`. +- BREAKING (Rust API): `registry-platform-httputil` can refuse a response + from a peer that declares the development posture. + `validate_response_headers` takes a `PeerPolicy`: under + `RefuseDevelopmentPeer` a response whose `Registry-Posture` field is exactly + `development` is refused with `ResponseHeaderError::DevelopmentPeer`, and + `AcceptDevelopmentPeer` checks only the header bounds. + `ResponseHeaderBoundError` is now `ResponseHeaderError`. `is_loopback_host` + is the one host rule for plain http: a loopback address literal or the + exact name `localhost`, valid in every posture. + `FetchUrlPolicy::dev` is now `FetchUrlPolicy::https_or_loopback`, + `DestinationProfile::LoopbackDevelopmentHttp` is now + `DestinationProfile::LoopbackHttp`, and + `DestinationProfile::LocalPrivateDevelopmentHttp` exists only in test builds + and under the `test-support` feature. Migration: a client with no runtime + policy yet calls `validate_response_headers_without_peer_policy`, which + behaves as production and refuses a development peer, and the two renamed + names change at their call sites. + - `registry-thunderid-tooling` reads development identity files and task connections with the same loopback rule. A development issuer or local app origin may be any `127.0.0.0/8` address, `[::1]` or the IPv4-mapped form, From cd8d2ccab7aa9c2a26486ab66c08ef9a00f44302 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 11:28:16 +0100 Subject: [PATCH 075/136] feat(platform): read secret files under one rule and name the failed check Every runtime judges a secret file with the same function: links that stay below the secret root are followed, a root-owned 0440 or 0640 file loads for a non-root runtime, and every refusal names a platform.secret-file.* check with its fix. A development process loads a file whose bits are too loose and warns once per check. Product doctors and refusal messages use the shared result, evidence doctor judges files with the runtime's rule, and the hardening checklist and error reference describe it. Signed-off-by: Jeremi Joslin --- crates/registry-adapter-engine/src/load.rs | 12 +- .../registry-adapter-job/src/hook_ingress.rs | 4 +- crates/registry-breg/src/runtime_config.rs | 18 +- crates/registry-bregctl/src/dev/config.rs | 4 +- crates/registry-bregctl/src/doctor.rs | 7 + .../schema/connections.schema.json | 2 +- crates/registry-evidence/src/secrets.rs | 3 +- crates/registry-evidencectl/src/doctor.rs | 55 +- crates/registry-evidencectl/tests/doctor.rs | 3 +- crates/registry-platform-config/README.md | 17 +- crates/registry-platform-config/src/blocks.rs | 21 +- .../src/blocks_tests.rs | 2 +- crates/registry-platform-config/src/lib.rs | 3 +- .../registry-platform-config/src/secrets.rs | 475 +++++++++++++++--- .../src/secrets_tests.rs | 455 +++++++++++++++++ crates/registry-render/src/seal.rs | 5 +- .../src/grant_file.rs | 5 +- deploy/helm/registry-stack/README.md | 5 + .../content/docs/configure/adapter-jobs.mdx | 2 +- .../docs/configure/api-connections.mdx | 3 +- .../docs/configure/evidence-oid4vci.mdx | 6 +- .../advanced/rotate-credentials-and-trust.mdx | 2 +- .../src/content/docs/operate/breg-monitor.mdx | 4 +- .../content/docs/operate/breg-webhooks.mdx | 2 +- docs/site/src/content/docs/operate/breg.mdx | 16 +- .../src/content/docs/operate/casework.mdx | 6 +- .../src/content/docs/operate/coordinator.mdx | 2 +- .../src/content/docs/operate/messaging.mdx | 4 +- .../content/docs/operate/registry-render.mdx | 5 +- .../src/content/docs/operate/scheduling.mdx | 5 +- .../content/docs/reference/bregctl-dev.mdx | 2 +- .../docs/reference/casework-configuration.mdx | 2 +- .../docs/reference/environment-variables.mdx | 3 +- .../src/content/docs/reference/errors.mdx | 22 + .../docs/reference/render-configuration.mdx | 4 +- .../reference/scheduling-configuration.mdx | 5 +- .../src/content/docs/security/evidence.mdx | 5 +- .../docs/security/hardening-checklist.mdx | 56 ++- products/adapter/CHANGELOG.md | 4 + .../schemas/job-runtime.v1alpha1.schema.json | 2 +- .../schemas/runtime.v1alpha1.schema.json | 2 +- products/breg/CHANGELOG.md | 3 + .../mcp-runtime/mcp-runtime.schema.json | 2 +- .../review-runtime/review-runtime.schema.json | 2 +- .../generated/runtime/runtime.schema.json | 2 +- .../tools/dev-clients.v1alpha1.schema.json | 2 +- .../generated/runtime/runtime.schema.json | 2 +- .../generated/runtime/runtime.schema.json | 2 +- .../generated/runtime/runtime.schema.json | 2 +- products/evidence/CHANGELOG.md | 5 + products/evidence/OPERATOR-CONTRACT.md | 4 +- .../evidence/contracts/bundle.schema.yaml | 6 +- .../contracts/security-invariant-matrix.yaml | 2 +- .../oid4vci-runtime.schema.json | 2 +- .../oid4vp-runtime/oid4vp-runtime.schema.json | 2 +- .../identifiers/generated/catalog.v1.json | 38 +- .../generated/runtime/runtime.schema.json | 2 +- products/platform/CHANGELOG.md | 13 + .../mcp-runtime/mcp-runtime.schema.json | 2 +- .../runtime-config-blocks.schema.json | 2 +- .../schemas/task-connection.schema.json | 2 +- products/render/CHANGELOG.md | 2 + products/render/schemas/runtime.schema.json | 2 +- .../generated/runtime/runtime.schema.json | 2 +- 64 files changed, 1154 insertions(+), 209 deletions(-) create mode 100644 crates/registry-platform-config/src/secrets_tests.rs diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index 30312b003a..05fd656b94 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -510,11 +510,9 @@ fn secret_refusal_fix(error: &SecretError) -> &'static str { "declare at least one provider under secretProviders and give file.root an absolute path" } SecretError::Unavailable => { - "create the file under secretProviders.file.root or set the variable; a symlink reads as missing" - } - SecretError::UnsafeFile => { - "make it a regular file owned by the service user, mode 0600 or 0400, with one hard link" + "create the file under secretProviders.file.root or set the variable" } + SecretError::UnsafeFile(check) => check.suggested_action(), SecretError::Read => "check that the service user can read the secret file", SecretError::InvalidValue => { "store a non-empty value with no NUL byte, within the secret size limit" @@ -2050,10 +2048,10 @@ mod tests { } assert_ne!(unsafe_file, missing, "the two causes must read differently"); assert!(unsafe_file.contains("unsafe"), "{unsafe_file}"); - assert!(unsafe_file.contains("0600 or 0400"), "{unsafe_file}"); - assert!(unsafe_file.contains("owned by"), "{unsafe_file}"); + assert!(unsafe_file.contains("0400 or 0600"), "{unsafe_file}"); + assert!(unsafe_file.contains("runtime user"), "{unsafe_file}"); assert!(missing.contains("unavailable"), "{missing}"); - assert!(missing.contains("symlink"), "{missing}"); + assert!(missing.contains("secretProviders.file.root"), "{missing}"); assert!(disabled.contains("disabled provider"), "{disabled}"); assert!(disabled.contains("secretProviders"), "{disabled}"); } diff --git a/crates/registry-adapter-job/src/hook_ingress.rs b/crates/registry-adapter-job/src/hook_ingress.rs index 845d2ce49a..0ead8853d8 100644 --- a/crates/registry-adapter-job/src/hook_ingress.rs +++ b/crates/registry-adapter-job/src/hook_ingress.rs @@ -265,9 +265,7 @@ fn resolve_member( "the environment variable is not set" } SecretError::Unavailable => "the secret file is missing", - SecretError::UnsafeFile => { - "the secret file must be a regular file with mode 0400 or 0600" - } + SecretError::UnsafeFile(check) => check.suggested_action(), SecretError::Read => "the secret file could not be read", SecretError::InvalidValue => "the secret is empty or contains a NUL byte", SecretError::ProviderDisabled => { diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 9b858900be..312874cbe2 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -17,8 +17,8 @@ use registry_platform_audit::{AuditDestination, AuditDestinationKind, AuditProfi use registry_platform_config::{ check_metrics_bind_address, check_metrics_bind_apart, AuditKeyConfig, JwksSource, MetricsBindError, OidcIssuerConfig, PackageConfig as SharedPackageConfig, RemovedKey, - RuntimeConfigLoader, RuntimeEnvelope, SecretError, SecretReference, SecretResolver, - TaskGrantStatusConfig, REMOVED_OIDC_JWKS_SOURCE_KIND, + RuntimeConfigLoader, RuntimeEnvelope, SecretError, SecretFileCheck, SecretReference, + SecretResolver, TaskGrantStatusConfig, REMOVED_OIDC_JWKS_SOURCE_KIND, }; use registry_platform_crypto::{PublicJwk, SigningAlgorithm}; #[cfg(feature = "schema")] @@ -412,6 +412,8 @@ pub enum RuntimeConfigError { InvalidWasmExecution, #[error("runtime configuration secret resolution failed")] Secret, + #[error("runtime configuration secret file refused: {} ({})", .0.message(), .0.code())] + SecretFile(SecretFileCheck), } /// The config path of the exposure key a wildcard metrics refusal names. @@ -457,7 +459,7 @@ impl RuntimeConfigError { Self::InvalidBounds => "breg.runtime.invalid-bounds", Self::PoolBudgetExceeded => "breg.runtime.pool-budget-exceeded", Self::InvalidWasmExecution => "breg.runtime.invalid-wasm-execution", - Self::Secret => "breg.runtime.secret", + Self::Secret | Self::SecretFile(_) => "breg.runtime.secret", } } @@ -466,7 +468,7 @@ impl RuntimeConfigError { fn path(&self) -> &str { match self { Self::Reader(refusal) => &refusal.deciding_diagnostic().path, - Self::InvalidBinding | Self::Secret => "", + Self::InvalidBinding | Self::Secret | Self::SecretFile(_) => "", Self::InvalidExternalSource { path, .. } => path, Self::InvalidTaskGrantStatus => "/taskGrantStatus", Self::InvalidInstanceId => "/identity/instanceId", @@ -597,6 +599,7 @@ impl RuntimeConfigError { Self::Secret => { "Make every secret reference resolve through the declared secret providers." } + Self::SecretFile(check) => check.suggested_action(), } } @@ -633,8 +636,11 @@ impl RuntimeConfigError { } impl From for RuntimeConfigError { - fn from(_error: SecretError) -> Self { - Self::Secret + fn from(error: SecretError) -> Self { + match error { + SecretError::UnsafeFile(check) => Self::SecretFile(check), + _ => Self::Secret, + } } } diff --git a/crates/registry-bregctl/src/dev/config.rs b/crates/registry-bregctl/src/dev/config.rs index 38e0d7cad0..de79a3881e 100644 --- a/crates/registry-bregctl/src/dev/config.rs +++ b/crates/registry-bregctl/src/dev/config.rs @@ -735,9 +735,7 @@ fn resolve_secret( registry_platform_config::SecretError::Unavailable => { "create the file under secretProviders.file.root, or set the environment variable the reference names" } - registry_platform_config::SecretError::UnsafeFile => { - "make it a regular file you own, with mode 0400 or 0600 and a single link" - } + registry_platform_config::SecretError::UnsafeFile(check) => check.suggested_action(), registry_platform_config::SecretError::InvalidValue => { "store a non-empty value without NUL bytes, at most 64 KiB" } diff --git a/crates/registry-bregctl/src/doctor.rs b/crates/registry-bregctl/src/doctor.rs index dcf42d1c59..1f73f4af9f 100644 --- a/crates/registry-bregctl/src/doctor.rs +++ b/crates/registry-bregctl/src/doctor.rs @@ -996,6 +996,13 @@ mod tests { "/operationalTimeouts", ), (RuntimeConfigError::Secret, "breg.runtime.secret", ""), + ( + RuntimeConfigError::SecretFile( + registry_platform_config::SecretFileCheck::HardLinked, + ), + "breg.runtime.secret", + "", + ), ]; for (cause, expected_code, expected_path) in cases { diff --git a/crates/registry-cli-api/schema/connections.schema.json b/crates/registry-cli-api/schema/connections.schema.json index 85a76ded9f..8f995f848a 100644 --- a/crates/registry-cli-api/schema/connections.schema.json +++ b/crates/registry-cli-api/schema/connections.schema.json @@ -17,7 +17,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/crates/registry-evidence/src/secrets.rs b/crates/registry-evidence/src/secrets.rs index e806b932a8..7957afa2f1 100644 --- a/crates/registry-evidence/src/secrets.rs +++ b/crates/registry-evidence/src/secrets.rs @@ -1,7 +1,8 @@ //! Shared bounded secret resolution used by Evidence. //! //! The implementation lives in `registry-platform-config` so Evidence applies -//! the shared anchored, no-follow, owner-only file policy. +//! the shared anchored secret-file rule: relative links below the root only, +//! one hard link, and the owner and mode checks of `SecretFileCheck`. pub use registry_platform_config::{ ProtectedSecret, SecretError, SecretProvider, SecretResolver, MAX_SECRET_BYTES, diff --git a/crates/registry-evidencectl/src/doctor.rs b/crates/registry-evidencectl/src/doctor.rs index 2f8880bdbd..5ff52b66b2 100644 --- a/crates/registry-evidencectl/src/doctor.rs +++ b/crates/registry-evidencectl/src/doctor.rs @@ -38,6 +38,7 @@ use std::{ use anyhow::{anyhow, Context, Result}; use clap::Args; use registry_platform_audit::{AuditDestination, AuditDestinationKind}; +use registry_platform_config::{SecretError, SecretProvider, SecretReference, SecretResolver}; use serde::{Deserialize, Serialize}; use serde_norway::Value as YamlValue; @@ -306,40 +307,52 @@ fn check_secrets( } else if !metadata.is_dir() { root_run.refuse(&root, "is not a directory".to_owned()); } else if metadata.permissions().mode() & 0o077 != 0 { + // Evidence's own startup refuses a root group or other can reach, + // whatever the secret-file rule accepts below it. root_run.refuse(&root, group_or_other(&metadata, 0o700)); } } + // The runtime's own resolver judges each file, so this check gives the + // verdict the runtime would give. A secret file's rule is the shared one, + // stated by `SecretFileCheck`. + // The runtime requires an absolute root. A relative one in the file is + // read from the directory this check runs in, as the other files are. + let absolute_root = std::path::absolute(&root).unwrap_or_else(|_| root.clone()); + let resolver = match SecretResolver::new([SecretProvider::File], &absolute_root) { + Ok(resolver) => resolver, + Err(error) => { + root_run.refuse(&root, describe_secret_refusal(&error)); + return vec![root_run.finish()]; + } + }; let mut secret_run = CheckRun::new("secrets", project); for name in references { let path = root.join(&name); - let Some(metadata) = secret_run.stat(&path) else { - continue; - }; - if metadata.file_type().is_symlink() || !metadata.is_file() { - secret_run.refuse( - &path, - "is not a regular file reached without traversing a symbolic link".to_owned(), - ); - continue; + secret_run.inspected += 1; + let verdict = SecretReference::parse(format!("secret:file/{name}")) + .and_then(|reference| resolver.inspect_reference(&reference)); + if let Err(error) = verdict { + secret_run.refuse(&path, describe_secret_refusal(&error)); } - // Secrets are the one artifact the runtime pins to an exact mode - // rather than to a bound, so report the exact mode back. - let mode = metadata.permissions().mode() & 0o7777; - if !matches!(mode, 0o400 | 0o600) { - secret_run.refuse( - &path, - format!( - "has mode {mode:04o}; the runtime requires exactly 0400 or 0600 (chmod 400 or 600)" - ), - ); - } - require_sole_owner(&mut secret_run, &path, &metadata); } vec![root_run.finish(), secret_run.finish()] } +/// What a secret file's refusal says: the check, its code, and the fix. +fn describe_secret_refusal(error: &SecretError) -> String { + match error { + SecretError::UnsafeFile(check) => format!( + "{} ({}); {}", + check.message(), + check.code(), + check.suggested_action() + ), + other => format!("cannot be resolved: {other}; {}", other.suggested_action()), + } +} + /// The signer this deployment declares, and what settling it needs beyond this /// walk. /// diff --git a/crates/registry-evidencectl/tests/doctor.rs b/crates/registry-evidencectl/tests/doctor.rs index da1030de28..f16c013e5c 100644 --- a/crates/registry-evidencectl/tests/doctor.rs +++ b/crates/registry-evidencectl/tests/doctor.rs @@ -272,7 +272,8 @@ fn doctor_accepts_only_the_runtime_owner_only_secret_modes() { ); assert!( diagnostics.contains("secrets/audit-hmac-key") - && diagnostics.contains("requires exactly 0400 or 0600"), + && diagnostics.contains("platform.secret-file.") + && diagnostics.contains("0400 or 0600"), "doctor did not report unsupported secret mode {mode:04o}:\n{diagnostics}" ); } diff --git a/crates/registry-platform-config/README.md b/crates/registry-platform-config/README.md index b477d3dc9f..468590483e 100644 --- a/crates/registry-platform-config/README.md +++ b/crates/registry-platform-config/README.md @@ -8,10 +8,23 @@ owns and validates the rest of its configuration contract. Secret consumers use `SecretResolver::resolve_reference` for bounded values without NUL bytes. Cryptographic consumers use `resolve_binary_reference` for opaque key files, which preserves every byte, including zero bytes. Both paths -apply the same provider allowlist, owner-only regular-file checks, size bounds, -redacted diagnostics, and zeroization. The consumer validates its key format and +apply the same provider allowlist, regular-file checks, size bounds, redacted +diagnostics, and zeroization. The consumer validates its key format and length; the resolver does not decode, trim, or reinterpret file contents. +A secret file is read through one rule. The name may be a relative link that +stays below `secretProviders.file.root` (downward steps only, at most 8 links, +no `..`, no absolute target). The file it reaches must be a regular file with +one hard link and no write access for others, and either owned by the runtime +user with mode 0400 or 0600, or owned by root with no bit outside 0640 when the +runtime is not root. A process that declared development loads a file whose +read or mode bits are too loose and logs one warning per check. Every other +refusal holds in both postures. A refusal is a `SecretError::UnsafeFile` +carrying a `SecretFileCheck`, whose `code()` is `platform.secret-file.`, +and `SecretError::suggested_action()` gives the fix for any failure. +`SecretResolver::inspect_reference` runs the same checks without reading the +bytes. + ## Loader `RuntimeConfigLoader` reads one runtime configuration file named by an diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 31e5631664..022957c6a3 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -131,9 +131,13 @@ pub struct SecretProvidersConfig { #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FileSecretProviderConfig { - /// Absolute directory holding one file per secret. Each file must be a - /// regular file owned by the runtime user, mode 0400 or 0600, with exactly - /// one hard link. + /// Absolute directory holding one file per secret. A name may be a + /// relative link that stays below this directory, through at most 8 links. + /// The file it reaches must be a regular file with one hard link, owned by + /// the runtime user with mode 0400 or 0600, or owned by root with no + /// access beyond group read (0440 or 0640) when the runtime is not root. + /// A process that declared development loads a file with looser read or + /// mode bits and logs a warning. #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^/")))] pub root: PathBuf, } @@ -230,11 +234,12 @@ pub fn describe_secret_failure(field: &str, _reference: &str, error: &SecretErro SecretError::Unavailable => { "no readable secret of that name exists under the configured provider".to_owned() } - SecretError::UnsafeFile => concat!( - "the secret file must be a regular file owned by the runtime user, ", - "with mode 0400 or 0600, and exactly one hard link" - ) - .to_owned(), + SecretError::UnsafeFile(check) => format!( + "{} ({}). {}", + check.message(), + check.code(), + check.suggested_action() + ), SecretError::Read => "the secret could not be read".to_owned(), SecretError::InvalidValue => format!( "the secret value must be non-empty text of at most {MAX_SECRET_BYTES} bytes \ diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 06da2d29d2..c60705b3a2 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -961,7 +961,7 @@ fn a_secret_failure_names_the_member_and_never_the_reference() { SecretError::ProviderDisabled, SecretError::InvalidProviderConfiguration, SecretError::Unavailable, - SecretError::UnsafeFile, + SecretError::UnsafeFile(crate::SecretFileCheck::WorldReadable), SecretError::Read, SecretError::InvalidValue, ] { diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index ca3d3b110f..0b1d4923f8 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -65,7 +65,8 @@ pub use posture::{ FoundSetting, Gated, Posture, PostureReport, PostureSource, SettingOrigin, }; pub use secrets::{ - ProtectedSecret, SecretError, SecretProvider, SecretReference, SecretResolver, MAX_SECRET_BYTES, + ProtectedSecret, SecretError, SecretFileCheck, SecretProvider, SecretReference, SecretResolver, + MAX_SECRET_BYTES, MAX_SECRET_LINKS, }; fn resolve_config_env_expression( diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index 150e7339d0..c1e9a89107 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -7,11 +7,14 @@ use std::{ fs::File, io::Read, path::{Path, PathBuf}, + sync::atomic::{AtomicU16, Ordering}, }; use thiserror::Error; use zeroize::Zeroizing; +use crate::DevelopmentWitness; + /// Maximum accepted size of one resolved secret value. pub const MAX_SECRET_BYTES: usize = 64 * 1024; @@ -88,13 +91,168 @@ pub enum SecretError { #[error("the referenced secret is unavailable")] Unavailable, #[error("the referenced secret file is unsafe")] - UnsafeFile, + UnsafeFile(SecretFileCheck), #[error("the referenced secret could not be read")] Read, #[error("the referenced secret value is invalid")] InvalidValue, } +impl SecretError { + /// What the operator does about this failure. It states the same fix + /// wherever the failure surfaces, so a product does not restate the rule. + #[must_use] + pub fn suggested_action(&self) -> &'static str { + match self { + Self::InvalidReference => { + "Write the reference as an exact secret:env/NAME or secret:file/name." + } + Self::ProviderDisabled => { + "Enable the reference's provider under secretProviders in the runtime file." + } + Self::InvalidProviderConfiguration => { + "Enable at least one secret provider, and give the file provider an absolute root." + } + Self::Unavailable => { + "Create the secret under the configured provider, or correct the name." + } + Self::UnsafeFile(check) => check.suggested_action(), + Self::Read => "Check that the secret can be read by the runtime user.", + Self::InvalidValue => { + "Store a non-empty value of at most 64 KiB, without NUL bytes unless the secret is a binary key." + } + } + } +} + +/// The check a refused secret file failed. Each has its own code, text and +/// fix, none of which names a path, a reference or a value. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SecretFileCheck { + /// A link target is absolute, empty, or holds a `..` component. + LinkLeavesRoot, + /// More than [`MAX_SECRET_LINKS`] links were followed. + TooManyLinks, + /// The runtime user cannot open the file. + CannotOpen, + /// The name does not lead to a regular file. + NotRegular, + /// The file has more than one hard link. + HardLinked, + /// The owner is neither the runtime user nor root. + Owner, + /// Users outside the owner and group can write the file. + WorldWritable, + /// Users outside the owner and group can read the file. + WorldReadable, + /// The group has access the rule does not allow. + GroupAccess, + /// An execute, setuid, setgid or sticky bit, or an owner that cannot read. + ModeBits, +} + +impl SecretFileCheck { + /// The diagnostic code, `platform.secret-file.`. + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::LinkLeavesRoot => "platform.secret-file.link-leaves-root", + Self::TooManyLinks => "platform.secret-file.too-many-links", + Self::CannotOpen => "platform.secret-file.cannot-open", + Self::NotRegular => "platform.secret-file.not-regular", + Self::HardLinked => "platform.secret-file.hard-linked", + Self::Owner => "platform.secret-file.owner", + Self::WorldWritable => "platform.secret-file.world-writable", + Self::WorldReadable => "platform.secret-file.world-readable", + Self::GroupAccess => "platform.secret-file.group-access", + Self::ModeBits => "platform.secret-file.mode-bits", + } + } + + /// What is wrong, without a path, a reference or a value. + #[must_use] + pub const fn message(self) -> &'static str { + match self { + Self::LinkLeavesRoot => { + "the secret file is reached through a link that leaves secretProviders.file.root" + } + Self::TooManyLinks => "the secret file is reached through more than 8 links", + Self::CannotOpen => "the runtime user cannot open the secret file", + Self::NotRegular => "the secret file is not a regular file", + Self::HardLinked => "the secret file has more than one hard link", + Self::Owner => "the secret file is owned by neither the runtime user nor root", + Self::WorldWritable => { + "users outside the file's owner and group can write the secret file" + } + Self::WorldReadable => { + "users outside the file's owner and group can read the secret file" + } + Self::GroupAccess => "the secret file's group has access the rule does not allow", + Self::ModeBits => { + "the secret file has an execute, setuid, setgid or sticky bit, or its owner cannot read it" + } + } + } + + /// The fix, one sentence per step. + #[must_use] + pub const fn suggested_action(self) -> &'static str { + match self { + Self::LinkLeavesRoot => { + "Put the file under secretProviders.file.root, or use a relative link without `..` that stays below it." + } + Self::TooManyLinks => { + "Point the name at the file, or at a chain of at most 8 links below secretProviders.file.root." + } + Self::CannotOpen => { + "Make the file readable by the runtime user: mode 0400 or 0600 owned by that user, or 0440 owned by root with the runtime user's group. On Kubernetes, set the secret volume's defaultMode to 0440 and the pod's securityContext.fsGroup to the runtime user's group." + } + Self::NotRegular => { + "Point the name at a regular file, not a directory, device, socket or pipe." + } + Self::HardLinked => "Replace it with a copy that has one link.", + Self::Owner => { + "Give it to the runtime user with mode 0400 or 0600, or to root with mode 0440 and the runtime user's group." + } + Self::WorldWritable => "Remove all access for others (chmod o-rwx).", + Self::WorldReadable => { + "Remove access for others: mode 0400 or 0600 for a file the runtime user owns, 0440 for a root-owned file. On Kubernetes, set the secret volume's defaultMode to 0440 and the pod's securityContext.fsGroup to the runtime user's group." + } + Self::GroupAccess => { + "Use mode 0400 or 0600 for a file the runtime user owns. Group read is accepted only on a root-owned file (0440 or 0640) read by a non-root runtime." + } + Self::ModeBits => "Set mode 0400 or 0600.", + } + } + + /// Whether a development process loads the file with a warning instead of + /// refusing it. Production refuses every check. + #[must_use] + pub const fn warns_in_development(self) -> bool { + matches!( + self, + Self::WorldReadable | Self::GroupAccess | Self::ModeBits + ) + } + + const fn bit(self) -> u16 { + 1 << (self as u16) + } +} + +/// Which checks have already warned in this process. +#[derive(Default)] +struct WarnedChecks(AtomicU16); + +impl WarnedChecks { + /// True the first time `check` is seen. + fn first(&self, check: SecretFileCheck) -> bool { + self.0.fetch_or(check.bit(), Ordering::Relaxed) & check.bit() == 0 + } +} + +static WARNED: WarnedChecks = WarnedChecks(AtomicU16::new(0)); + /// Secret bytes that are erased when dropped and never exposed by `Debug`. pub struct ProtectedSecret(Zeroizing>); @@ -125,13 +283,21 @@ impl fmt::Debug for ProtectedSecret { /// Resolver for exact secret references under an explicit provider allowlist. /// /// File names are single bounded path components and are opened relative to -/// the configured absolute root with `openat`. The opened file, rather than a -/// later pathname lookup, is checked for type, ownership, mode, and link count -/// before at most [`MAX_SECRET_BYTES`] are retained. +/// the configured absolute root with `openat`. A link is followed only by +/// downward relative steps from that root, at most [`MAX_SECRET_LINKS`] of +/// them. The opened file, rather than a later pathname lookup, is checked for +/// type, ownership, mode, and link count before at most [`MAX_SECRET_BYTES`] +/// are retained. +/// +/// The production rule accepts a file owned by the runtime user with mode 0400 +/// or 0600, and a root-owned file with no bit outside 0640 when the runtime is +/// not root. [`Self::in_development`] relaxes the read and mode-bit checks to a +/// warning for a process that declared development. #[derive(Debug)] pub struct SecretResolver { providers: BTreeSet, file_root: PathBuf, + development: bool, } impl SecretResolver { @@ -144,6 +310,7 @@ impl SecretResolver { Self { providers: BTreeSet::new(), file_root: PathBuf::new(), + development: false, } } @@ -162,9 +329,35 @@ impl SecretResolver { Ok(Self { providers, file_root, + development: false, }) } + /// Apply the development rule when the process holds the witness. Without + /// it the resolver keeps the production rule, so a production path cannot + /// relax the rule by mistake. + #[must_use] + pub fn in_development(mut self, witness: Option<&DevelopmentWitness>) -> Self { + self.development = witness.is_some(); + self + } + + /// Run every check a read runs, without retaining the bytes. A check tool + /// uses this to give the verdict the runtime would give. + pub fn inspect_reference(&self, reference: &SecretReference) -> Result<(), SecretError> { + if !self.providers.contains(&reference.provider()) { + return Err(SecretError::ProviderDisabled); + } + match reference.provider() { + SecretProvider::Environment => env::var_os(reference.name()) + .map(|_| ()) + .ok_or(SecretError::Unavailable), + SecretProvider::File => { + open_secret_file(&self.file_root, reference.name(), self.development).map(|_| ()) + } + } + } + /// Resolve one exact `secret:env/NAME` or `secret:file/name` reference. pub fn resolve(&self, reference: &str) -> Result { let reference = SecretReference::parse(reference)?; @@ -195,7 +388,9 @@ impl SecretResolver { let bytes = match reference.provider() { SecretProvider::Environment => read_environment(reference.name())?, - SecretProvider::File => read_secret_file(&self.file_root, reference.name())?, + SecretProvider::File => { + read_secret_file(&self.file_root, reference.name(), self.development)? + } }; validate_binary_secret(bytes) } @@ -216,53 +411,208 @@ fn read_environment(name: &str) -> Result>, SecretError> { Ok(Zeroizing::new(bytes)) } +/// The most links a secret name may pass through. Kubernetes uses two. +pub const MAX_SECRET_LINKS: usize = 8; + +#[cfg(unix)] +fn read_secret_file( + root: &Path, + name: &str, + development: bool, +) -> Result>, SecretError> { + read_bounded(open_secret_file(root, name, development)?) +} + +/// What the rule looks at in an opened file. +#[derive(Clone, Copy, Debug)] +struct Facts { + kind: FileKind, + uid: u32, + mode: u32, + nlink: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum FileKind { + Regular, + Directory, + Fifo, + Socket, + Device, +} + +/// Judge an opened file. Production refuses at the first failing check. In +/// development the shape, link-count, owner and world-write checks still +/// refuse, and the checks that [`SecretFileCheck::warns_in_development`] names +/// are returned as warnings. +fn judge( + facts: Facts, + euid: u32, + development: bool, +) -> Result, SecretFileCheck> { + use SecretFileCheck::{ + GroupAccess, HardLinked, ModeBits, NotRegular, Owner, WorldReadable, WorldWritable, + }; + + if facts.kind != FileKind::Regular { + return Err(NotRegular); + } + if facts.nlink != 1 { + return Err(HardLinked); + } + if facts.uid != euid && facts.uid != 0 { + return Err(Owner); + } + if facts.mode & 0o002 != 0 { + return Err(WorldWritable); + } + let own = facts.uid == euid; + let mut failed = Vec::new(); + if facts.mode & 0o005 != 0 { + failed.push(WorldReadable); + } + let group_bits = if own { 0o070 } else { 0o030 }; + if facts.mode & group_bits != 0 { + failed.push(GroupAccess); + } + if facts.mode & 0o7100 != 0 || (own && facts.mode & 0o400 == 0) { + failed.push(ModeBits); + } + match (development, failed.first()) { + (false, Some(check)) => Err(*check), + _ => Ok(failed), + } +} + +/// Walk `name` from the root by openat steps, following only relative +/// downward links, then judge the descriptor that will be read. #[cfg(unix)] -fn read_secret_file(root: &Path, name: &str) -> Result>, SecretError> { - use rustix::fs::{Mode, OFlags}; +fn open_secret_file(root: &Path, name: &str, development: bool) -> Result { + use rustix::{ + fs::{Mode, OFlags}, + io::Errno, + }; + use std::collections::VecDeque; - let root = rustix::fs::open( + let unsafe_file = SecretError::UnsafeFile; + let mut dir = rustix::fs::open( root, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::DIRECTORY, Mode::empty(), ) .map_err(|_| SecretError::Unavailable)?; - let secret = rustix::fs::openat( - &root, - name, - OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, - Mode::empty(), - ) - .map_err(|_| SecretError::Unavailable)?; + let mut pending: VecDeque> = VecDeque::from([name.as_bytes().to_vec()]); + let mut links = 0_usize; + let secret = loop { + let Some(component) = pending.pop_front() else { + // A link whose target names only the directory it sits in. + return Err(unsafe_file(SecretFileCheck::NotRegular)); + }; + let last = pending.is_empty(); + let mut flags = OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NOCTTY; + flags |= if last { + OFlags::NONBLOCK + } else { + OFlags::DIRECTORY + }; + match rustix::fs::openat(&dir, component.as_slice(), flags, Mode::empty()) { + Ok(fd) if last => break fd, + Ok(fd) => dir = fd, + Err(Errno::LOOP | Errno::NOTDIR) => { + let target = match rustix::fs::readlinkat(&dir, component.as_slice(), Vec::new()) { + Ok(target) => target, + // Not a link: a file where a directory was needed. + Err(Errno::INVAL) => return Err(SecretError::Unavailable), + Err(_) => return Err(SecretError::Read), + }; + links += 1; + if links > MAX_SECRET_LINKS { + return Err(unsafe_file(SecretFileCheck::TooManyLinks)); + } + let target = target.into_bytes(); + if target.is_empty() || target.starts_with(b"/") { + return Err(unsafe_file(SecretFileCheck::LinkLeavesRoot)); + } + let mut steps = Vec::new(); + for step in target.split(|byte| *byte == b'/') { + match step { + b"" | b"." => {} + b".." => return Err(unsafe_file(SecretFileCheck::LinkLeavesRoot)), + step => steps.push(step.to_vec()), + } + } + for step in steps.into_iter().rev() { + pending.push_front(step); + } + } + Err(Errno::NOENT) => return Err(SecretError::Unavailable), + Err(Errno::ACCESS) => return Err(unsafe_file(SecretFileCheck::CannotOpen)), + Err(_) => return Err(SecretError::Read), + } + }; let file = File::from(secret); - validate_file_metadata(&file)?; - read_bounded(file) + judge_file(&file, development)?; + Ok(file) } #[cfg(unix)] -fn validate_file_metadata(file: &File) -> Result<(), SecretError> { - use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _}; +fn judge_file(file: &File, development: bool) -> Result<(), SecretError> { + use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _, PermissionsExt as _}; let metadata = file.metadata().map_err(|_| SecretError::Read)?; - let mode = metadata.permissions().mode() & 0o7777; - if !metadata.is_file() - || metadata.uid() != rustix::process::geteuid().as_raw() - || !matches!(mode, 0o400 | 0o600) - || metadata.nlink() != 1 - { - return Err(SecretError::UnsafeFile); - } - Ok(()) + let file_type = metadata.file_type(); + let kind = if file_type.is_file() { + FileKind::Regular + } else if file_type.is_dir() { + FileKind::Directory + } else if file_type.is_fifo() { + FileKind::Fifo + } else if file_type.is_socket() { + FileKind::Socket + } else { + FileKind::Device + }; + let facts = Facts { + kind, + uid: metadata.uid(), + mode: metadata.permissions().mode() & 0o7777, + nlink: metadata.nlink(), + }; + match judge(facts, rustix::process::geteuid().as_raw(), development) { + Err(check) => Err(SecretError::UnsafeFile(check)), + Ok(warnings) => { + for check in warnings { + if WARNED.first(check) { + tracing::warn!( + error_code = check.code(), + "{}; production refuses it. {}", + check.message(), + check.suggested_action() + ); + } + } + Ok(()) + } + } } #[cfg(not(unix))] -fn read_secret_file(root: &Path, name: &str) -> Result>, SecretError> { +fn read_secret_file( + root: &Path, + name: &str, + development: bool, +) -> Result>, SecretError> { + read_bounded(open_secret_file(root, name, development)?) +} + +#[cfg(not(unix))] +fn open_secret_file(root: &Path, name: &str, _development: bool) -> Result { let path = root.join(name); let metadata = std::fs::symlink_metadata(&path).map_err(|_| SecretError::Unavailable)?; if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err(SecretError::UnsafeFile); + return Err(SecretError::UnsafeFile(SecretFileCheck::NotRegular)); } - let file = File::open(path).map_err(|_| SecretError::Unavailable)?; - read_bounded(file) + File::open(path).map_err(|_| SecretError::Unavailable) } /// Read at most one byte past [`MAX_SECRET_BYTES`] into one buffer allocated @@ -290,6 +640,10 @@ fn validate_binary_secret(bytes: Zeroizing>) -> Result Facts { + Facts { + kind, + uid, + mode, + nlink, + } +} + +fn observed(result: Result, SecretFileCheck>) -> Outcome { + match result { + Err(check) => Outcome::Refuse(check), + Ok(warnings) if warnings.is_empty() => Outcome::Load, + Ok(warnings) => Outcome::Warn(Box::leak(warnings.into_boxed_slice())), + } +} + +#[test] +fn the_decision_table_gives_one_answer_per_owner_mode_and_posture() { + use FileKind::{Directory, Regular}; + use Outcome::{Load, Refuse, Warn}; + const APP: u32 = 10001; + #[rustfmt::skip] + let rows: &[Row] = &[ + ("A1", APP, APP, 0o400, Regular, 1, Load, Load), + ("A2", APP, APP, 0o600, Regular, 1, Load, Load), + ("A3", APP, APP, 0o440, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A4", APP, APP, 0o640, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A5", APP, APP, 0o620, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A6", APP, APP, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("A7", APP, APP, 0o604, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("A8", APP, APP, 0o444, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("A9a", APP, APP, 0o602, Regular, 1, Refuse(WorldWritable), Refuse(WorldWritable)), + ("A9b", APP, APP, 0o666, Regular, 1, Refuse(WorldWritable), Refuse(WorldWritable)), + ("A10a", APP, APP, 0o500, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("A10b", APP, APP, 0o700, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("A10c", APP, APP, 0o4600, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("A12", APP, 0, 0o440, Regular, 1, Load, Load), + ("A13", APP, 0, 0o640, Regular, 1, Load, Load), + ("A14", APP, 0, 0o400, Regular, 1, Load, Load), + ("A15a", APP, 0, 0o460, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A15b", APP, 0, 0o450, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A16a", APP, 0, 0o444, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("A16b", APP, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("A17", APP, 0, 0o446, Regular, 1, Refuse(WorldWritable), Refuse(WorldWritable)), + ("A19", APP, 10002, 0o644, Regular, 1, Refuse(Owner), Refuse(Owner)), + ("A20a", 0, 0, 0o400, Regular, 1, Load, Load), + ("A20b", 0, 0, 0o600, Regular, 1, Load, Load), + ("A21", 0, 0, 0o440, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A22", 0, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("A23", 0, APP, 0o600, Regular, 1, Refuse(Owner), Refuse(Owner)), + ("A24", APP, APP, 0o400, Regular, 2, Refuse(HardLinked), Refuse(HardLinked)), + ("A25", APP, APP, 0o400, Directory, 1, Refuse(NotRegular), Refuse(NotRegular)), + ("A25f", APP, APP, 0o400, FileKind::Fifo, 1, Refuse(NotRegular), Refuse(NotRegular)), + ("A25s", APP, APP, 0o400, FileKind::Socket, 1, Refuse(NotRegular), Refuse(NotRegular)), + ("A25d", APP, APP, 0o400, FileKind::Device, 1, Refuse(NotRegular), Refuse(NotRegular)), + // Observed mounts (m0 secret-mounts), by their observed owner and mode. + ("C-b", APP, APP, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("C-eb", APP, 0, 0o444, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("C-el", APP, APP, 0o400, Regular, 1, Load, Load), + ("vu/root640", APP, 0, 0o640, Regular, 1, Load, Load), + ("vu/root644", APP, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("vu/app440", APP, APP, 0o440, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("K-a", 0, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("K-b", APP, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("K-d", APP, 0, 0o440, Regular, 1, Load, Load), + ("K-f", APP, 0, 0o440, Regular, 1, Load, Load), + ("K-g2", APP, 0, 0o440, Regular, 1, Load, Load), + ("K-root-0440", 0, 0, 0o440, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ]; + for (row, euid, uid, mode, kind, nlink, production, development) in rows { + let f = facts(*kind, *uid, *mode, *nlink); + assert_eq!( + observed(judge(f, *euid, false)), + *production, + "{row} in production" + ); + assert_eq!( + observed(judge(f, *euid, true)), + *development, + "{row} in development" + ); + } +} + +#[test] +fn every_check_has_a_unique_code_a_value_free_message_and_a_full_stop_fix() { + let all = [ + LinkLeavesRoot, + TooManyLinks, + CannotOpen, + NotRegular, + HardLinked, + Owner, + WorldWritable, + WorldReadable, + GroupAccess, + ModeBits, + ]; + let mut codes = std::collections::BTreeSet::new(); + for check in all { + let code = check.code(); + assert!(code.starts_with("platform.secret-file."), "{code}"); + assert!( + code["platform.secret-file.".len()..] + .bytes() + .all(|b| b.is_ascii_lowercase() || b == b'-'), + "{code}" + ); + assert!(codes.insert(code), "{code} repeats"); + assert!(check.suggested_action().ends_with('.'), "{code}"); + for text in [check.message(), check.suggested_action()] { + assert!(!text.contains("/run/") && !text.contains("/etc/"), "{text}"); + assert!(!text.contains("secret:"), "{text}"); + } + } + for check in [CannotOpen, WorldReadable] { + let action = check.suggested_action(); + assert!(action.contains("defaultMode"), "{action}"); + assert!(action.contains("fsGroup"), "{action}"); + } + for check in all { + assert!(!check.suggested_action().contains("runAsUser")); + } +} + +#[test] +fn the_development_split_lives_in_one_place() { + for check in [WorldReadable, GroupAccess, ModeBits] { + assert!(check.warns_in_development(), "{check:?}"); + } + for check in [ + LinkLeavesRoot, + TooManyLinks, + CannotOpen, + NotRegular, + HardLinked, + Owner, + WorldWritable, + ] { + assert!(!check.warns_in_development(), "{check:?}"); + } +} + +#[test] +fn a_check_warns_once_per_process_however_often_it_fires() { + let warned = WarnedChecks::default(); + assert!(warned.first(WorldReadable)); + assert!(!warned.first(WorldReadable)); + assert!(warned.first(GroupAccess)); + assert!(!warned.first(GroupAccess)); + assert!(!warned.first(WorldReadable)); +} + +#[test] +fn error_fixes_come_from_the_error() { + assert_eq!( + SecretError::UnsafeFile(HardLinked).suggested_action(), + HardLinked.suggested_action() + ); + for error in [ + SecretError::InvalidReference, + SecretError::ProviderDisabled, + SecretError::InvalidProviderConfiguration, + SecretError::Unavailable, + SecretError::Read, + SecretError::InvalidValue, + ] { + assert!(error.suggested_action().ends_with('.'), "{error:?}"); + } +} + +#[cfg(unix)] +mod filesystem { + use super::*; + use std::{ + fs, + os::unix::fs::{symlink, PermissionsExt as _}, + path::Path, + }; + + fn write(root: &Path, name: &str, mode: u32) { + let path = root.join(name); + fs::write(&path, b"file-canary").expect("write"); + fs::set_permissions(path, fs::Permissions::from_mode(mode)).expect("mode"); + } + + fn resolver(root: &Path) -> SecretResolver { + SecretResolver::new([SecretProvider::File], root).expect("resolver") + } + + fn development(root: &Path) -> SecretResolver { + resolver(root).in_development(Some(&DevelopmentWitness::issue())) + } + + fn load(resolver: &SecretResolver, name: &str) -> Result, SecretError> { + resolver + .resolve(&format!("secret:file/{name}")) + .map(|secret| secret.expose_secret().to_vec()) + } + + #[test] + fn a_relative_link_inside_the_root_loads_the_file_it_names() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "target", 0o400); + symlink("target", root.path().join("name")).expect("link"); + fs::create_dir(root.path().join("sub")).expect("dir"); + write(&root.path().join("sub"), "token", 0o400); + symlink("sub/token", root.path().join("nested")).expect("link"); + let resolver = resolver(root.path()); + assert_eq!(load(&resolver, "name").expect("loads"), b"file-canary"); + assert_eq!(load(&resolver, "nested").expect("loads"), b"file-canary"); + } + + fn kubernetes_layout(root: &Path, mode: u32) { + fs::create_dir(root.join("..ts")).expect("dir"); + write(&root.join("..ts"), "token", mode); + symlink("..ts", root.join("..data")).expect("link"); + symlink("..data/token", root.join("token")).expect("link"); + } + + #[test] + fn the_kubernetes_link_chain_loads_and_the_target_is_judged_not_the_links() { + let root = tempfile::tempdir().expect("root"); + kubernetes_layout(root.path(), 0o400); + assert_eq!( + load(&resolver(root.path()), "token").expect("loads"), + b"file-canary" + ); + + let loose = tempfile::tempdir().expect("root"); + kubernetes_layout(loose.path(), 0o644); + assert_eq!( + load(&resolver(loose.path()), "token"), + Err(SecretError::UnsafeFile(WorldReadable)) + ); + assert_eq!( + load(&development(loose.path()), "token").expect("warns and loads"), + b"file-canary" + ); + } + + #[test] + fn a_chain_of_eight_links_loads_and_nine_or_a_loop_is_refused() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "end", 0o400); + let mut previous = "end".to_owned(); + for index in 1..=9 { + let name = format!("l{index}"); + symlink(&previous, root.path().join(&name)).expect("link"); + previous = name; + } + let resolver = resolver(root.path()); + assert_eq!(load(&resolver, "l8").expect("8 links load"), b"file-canary"); + assert_eq!( + load(&resolver, "l9"), + Err(SecretError::UnsafeFile(TooManyLinks)) + ); + symlink("loop-b", root.path().join("loop-a")).expect("link"); + symlink("loop-a", root.path().join("loop-b")).expect("link"); + assert_eq!( + load(&resolver, "loop-a"), + Err(SecretError::UnsafeFile(TooManyLinks)) + ); + } + + #[test] + fn a_link_that_could_leave_the_root_is_refused_in_both_postures() { + let root = tempfile::tempdir().expect("root"); + let outside = tempfile::tempdir().expect("outside"); + write(outside.path(), "token", 0o400); + write(root.path(), "inside", 0o400); + fs::create_dir(root.path().join("sub")).expect("dir"); + write(&root.path().join("sub"), "token", 0o400); + symlink(outside.path().join("token"), root.path().join("absolute")).expect("link"); + symlink( + root.path().join("inside"), + root.path().join("absolute-inside"), + ) + .expect("link"); + symlink("../x", root.path().join("parent")).expect("link"); + symlink("sub/../inside", root.path().join("dotdot")).expect("link"); + symlink(outside.path(), root.path().join("elsewhere")).expect("link"); + symlink("elsewhere/token", root.path().join("through")).expect("link"); + for resolver in [resolver(root.path()), development(root.path())] { + for name in ["absolute", "absolute-inside", "parent", "dotdot", "through"] { + assert_eq!( + load(&resolver, name), + Err(SecretError::UnsafeFile(LinkLeavesRoot)), + "{name}" + ); + } + } + } + + #[test] + fn a_link_to_a_directory_or_a_dangling_link_is_refused() { + let root = tempfile::tempdir().expect("root"); + fs::create_dir(root.path().join("sub")).expect("dir"); + symlink("sub", root.path().join("to-dir")).expect("link"); + symlink("missing", root.path().join("dangling")).expect("link"); + let resolver = resolver(root.path()); + assert_eq!( + load(&resolver, "to-dir"), + Err(SecretError::UnsafeFile(NotRegular)) + ); + assert_eq!(load(&resolver, "dangling"), Err(SecretError::Unavailable)); + assert_eq!(load(&resolver, "absent"), Err(SecretError::Unavailable)); + } + + #[test] + fn a_link_in_the_root_path_itself_is_refused_and_its_parents_are_not_checked() { + let real = tempfile::tempdir().expect("real"); + write(real.path(), "token", 0o400); + let holder = tempfile::tempdir().expect("holder"); + let linked_root = holder.path().join("root-link"); + symlink(real.path(), &linked_root).expect("link"); + assert_eq!( + load(&resolver(&linked_root), "token"), + Err(SecretError::Unavailable) + ); + let parent_link = holder.path().join("parent-link"); + symlink(holder.path(), &parent_link).expect("link"); + fs::create_dir(holder.path().join("child")).expect("dir"); + write(&holder.path().join("child"), "token", 0o400); + assert!(load(&resolver(&parent_link.join("child")), "token").is_ok()); + } + + #[test] + fn the_roots_own_mode_is_not_checked() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "token", 0o400); + fs::set_permissions(root.path(), fs::Permissions::from_mode(0o1777)).expect("mode"); + assert!(load(&resolver(root.path()), "token").is_ok()); + } + + #[test] + fn a_fifo_is_refused_without_blocking() { + let root = tempfile::tempdir().expect("root"); + let status = std::process::Command::new("mkfifo") + .arg(root.path().join("pipe")) + .status() + .expect("mkfifo runs"); + assert!(status.success()); + assert_eq!( + load(&resolver(root.path()), "pipe"), + Err(SecretError::UnsafeFile(NotRegular)) + ); + } + + #[test] + fn a_directory_is_not_a_secret() { + let root = tempfile::tempdir().expect("root"); + fs::create_dir(root.path().join("directory")).expect("dir"); + assert_eq!( + load(&resolver(root.path()), "directory"), + Err(SecretError::UnsafeFile(NotRegular)) + ); + } + + #[test] + fn a_file_the_runtime_cannot_open_is_cannot_open_not_unavailable() { + if rustix::process::geteuid().is_root() { + return; + } + let root = tempfile::tempdir().expect("root"); + write(root.path(), "locked", 0o000); + assert_eq!( + load(&resolver(root.path()), "locked"), + Err(SecretError::UnsafeFile(CannotOpen)) + ); + assert_eq!( + load(&development(root.path()), "locked"), + Err(SecretError::UnsafeFile(CannotOpen)) + ); + } + + #[test] + fn development_warns_for_loose_modes_and_still_refuses_shape_owner_and_write() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "world-readable", 0o644); + write(root.path(), "group", 0o440); + write(root.path(), "executable", 0o500); + write(root.path(), "world-writable", 0o666); + symlink("/etc/hosts", root.path().join("absolute")).expect("link"); + let production = resolver(root.path()); + let development = development(root.path()); + for (name, check) in [ + ("world-readable", WorldReadable), + ("group", GroupAccess), + ("executable", ModeBits), + ] { + assert_eq!(load(&production, name), Err(SecretError::UnsafeFile(check))); + assert_eq!(load(&development, name).expect("warns"), b"file-canary"); + } + for (name, check) in [ + ("world-writable", WorldWritable), + ("absolute", LinkLeavesRoot), + ] { + assert_eq!(load(&production, name), Err(SecretError::UnsafeFile(check))); + assert_eq!( + load(&development, name), + Err(SecretError::UnsafeFile(check)) + ); + } + } + + #[test] + fn a_resolver_without_the_witness_applies_the_production_rule() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "token", 0o644); + let resolver = resolver(root.path()).in_development(None); + assert_eq!( + load(&resolver, "token"), + Err(SecretError::UnsafeFile(WorldReadable)) + ); + } + + #[test] + fn inspecting_a_reference_gives_the_verdict_without_the_bytes() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "good", 0o400); + write(root.path(), "loose", 0o644); + let resolver = resolver(root.path()); + let good = SecretReference::parse("secret:file/good").unwrap(); + let loose = SecretReference::parse("secret:file/loose").unwrap(); + let absent = SecretReference::parse("secret:file/absent").unwrap(); + assert_eq!(resolver.inspect_reference(&good), Ok(())); + assert_eq!( + resolver.inspect_reference(&loose), + Err(SecretError::UnsafeFile(WorldReadable)) + ); + assert_eq!( + resolver.inspect_reference(&absent), + Err(SecretError::Unavailable) + ); + } +} diff --git a/crates/registry-render/src/seal.rs b/crates/registry-render/src/seal.rs index dfe3cc7e4c..8f48208bbe 100644 --- a/crates/registry-render/src/seal.rs +++ b/crates/registry-render/src/seal.rs @@ -557,9 +557,8 @@ fn local_jwk_signer( // when it drops after parsing. let secret = crate::runtime::resolve_protected_secret(runtime, private_key_ref).map_err(|error| { - let action = if error == SecretError::UnsafeFile { - "Make the key file a regular file owned by the serving user, with mode 0600 or \ - 0400 and one link." + let action = if matches!(error, SecretError::UnsafeFile(_)) { + error.suggested_action() } else { "Provide the seal's private key under the secret provider the reference names." }; diff --git a/crates/registry-thunderid-tooling/src/grant_file.rs b/crates/registry-thunderid-tooling/src/grant_file.rs index 4effa06c8b..f7252bc2be 100644 --- a/crates/registry-thunderid-tooling/src/grant_file.rs +++ b/crates/registry-thunderid-tooling/src/grant_file.rs @@ -126,10 +126,7 @@ fn assertion_key( "no secret of the referenced name exists under its provider", "Create the key file under secretProviders.file.root, or set the environment variable the reference names.", ), - SecretError::UnsafeFile => ( - "the referenced key file is not a regular file you own with mode 0400 or 0600 and a single link", - "Make the key file a regular file you own, with mode 0400 or 0600 and a single link.", - ), + SecretError::UnsafeFile(check) => (check.message(), check.suggested_action()), SecretError::InvalidValue => ( "the referenced secret is empty, holds a NUL byte, or is larger than 64 KiB", "Store the client's private assertion key as one JWK under this reference.", diff --git a/deploy/helm/registry-stack/README.md b/deploy/helm/registry-stack/README.md index b6cc039a79..82887e1746 100644 --- a/deploy/helm/registry-stack/README.md +++ b/deploy/helm/registry-stack/README.md @@ -77,6 +77,11 @@ update. No BReg, Casework, or Evidence Pod sets `fsGroup`. Kubelet can otherwise recursively change an existing owner-only audit or authority volume root. +Because no Pod sets `fsGroup`, the chart stages each Secret into a memory-backed volume owned by +the runtime user at mode `0400`, which the runtime's secret-file rule accepts. A deployment without +owner-only volumes can mount the Secret directly with `defaultMode: 0440` and `fsGroup` instead, +which the rule also accepts. + ## BReg input contract Set these references when `breg.enabled` is true: diff --git a/docs/site/src/content/docs/configure/adapter-jobs.mdx b/docs/site/src/content/docs/configure/adapter-jobs.mdx index 8f211969a4..b04ace5eef 100644 --- a/docs/site/src/content/docs/configure/adapter-jobs.mdx +++ b/docs/site/src/content/docs/configure/adapter-jobs.mdx @@ -484,7 +484,7 @@ The KoboToolbox example adds a webhook trigger with `job.hook.yaml` and `job-run Configure the KoboToolbox webhook to send `POST` requests to the public HTTPS URL whose path is `/hooks/kobo-submissions`, using HTTP Basic authentication. Each source binding has its own Basic credentials through secret references, and finite request-rate and burst bounds. -Put the exact username and password in the two files referenced by `hookIngress.sources.kobo-submissions`, with the file permissions the platform secret provider requires (mode `0400` or `0600`). +Put the exact username and password in the two files referenced by `hookIngress.sources.kobo-submissions`, with the file permissions the platform secret provider requires, in the [secret file rule](../../security/hardening-checklist/#secret-files) (for example mode `0400` or `0600` for a file the service user owns). Write them without a trailing newline, for example `printf '%s' "$PASSWORD" > hook-password`, because the host refuses a value that ends with a newline. The Adapter resolves and captures them at host startup, and `adapter-job check` resolves them too. A missing, unsafe or malformed credential is therefore refused with the runtime member and the secret reference named, instead of failing later as a `401`. diff --git a/docs/site/src/content/docs/configure/api-connections.mdx b/docs/site/src/content/docs/configure/api-connections.mdx index 55ac4570b8..51457be496 100644 --- a/docs/site/src/content/docs/configure/api-connections.mdx +++ b/docs/site/src/content/docs/configure/api-connections.mdx @@ -61,7 +61,8 @@ takes effect on the next invocation. An OAuth connection acquires its token auto A manually supplied token still needs renewal through its issuing system. Credential files must belong to the account running `rstack`, be regular files with a single -hard link, and have permissions `0400` or `0600`. Setup checks the supplied file before saving +hard link, and have permissions `0400` or `0600`. The rest of the rule is in +[Secret files](../../security/hardening-checklist/#secret-files). Setup checks the supplied file before saving the connection. For a deployment with a private certificate authority, add `--ca-file /path/to/ca.pem` during setup. diff --git a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx index 6408a7f248..9b0fb9620c 100644 --- a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx +++ b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx @@ -121,8 +121,8 @@ client; a flow where people request their own credential must not be given offer crates/registry-evidence-oid4vci/src/offer.rs, SelectorValueOrigin::Request. */} `privateKeyRef` and `audit.hashKeyRef` follow the [secret reference grammar](../../reference/environment-variables/#secret-references). -Both key files must be regular files owned by the service user, mode `0400` or `0600`, with a -single link. The audit key produces stable pseudonyms for the authenticated offer client, subject, +Both key files must meet the [secret file rule](../../security/hardening-checklist/#secret-files), +for example regular files owned by the service user, mode `0400` or `0600`, with a single link. The audit key produces stable pseudonyms for the authenticated offer client, subject, or both without storing their raw identities. Preserve it for as long as those records must remain correlatable. A file destination is the durable journal; use `stdout` only when the deployment collector durably accepts and preserves every line. Every key has the bounds and default its @@ -136,7 +136,7 @@ schema gives it, and `check` also enforces the rules a schema cannot hold: - A reference must name a provider the file enables, and `secretProviders.file.root` must be absolute. -{/* Evidence: crates/registry-platform-config/src/secrets.rs, validate_file_metadata; +{/* Evidence: crates/registry-platform-config/src/secrets.rs, judge_file; crates/registry-evidence-oid4vci/src/config.rs, evidence.oid4vci.nonce-lifetime, evidence.oid4vci.listener-port, evidence.oid4vci.metrics-address, evidence.oid4vci.metrics-shared-binding, evidence.oid4vci.secret-provider-disabled, diff --git a/docs/site/src/content/docs/operate/advanced/rotate-credentials-and-trust.mdx b/docs/site/src/content/docs/operate/advanced/rotate-credentials-and-trust.mdx index 7e830e8b7e..8571bdfe56 100644 --- a/docs/site/src/content/docs/operate/advanced/rotate-credentials-and-trust.mdx +++ b/docs/site/src/content/docs/operate/advanced/rotate-credentials-and-trust.mdx @@ -80,7 +80,7 @@ server's metadata publishes it (RFC 10070 section 4). {/* Evidence: crates/registry-adapter-engine/src/egress.rs, EndpointEgress, authorize, and maximum_cache_seconds; crates/registry-platform-config/src/secrets.rs, read_secret_file, - validate_file_metadata, and read_environment; + judge_file, and read_environment; crates/registry-evidencectl/src/runtime.rs, without_audit_lock; crates/registry-evidence/src/bundle.rs, RuntimeDocument and ca_bundles; products/evidence/reference/request-adapter/deployment-projects/SOURCE-CREDENTIAL-ROTATION.md; diff --git a/docs/site/src/content/docs/operate/breg-monitor.mdx b/docs/site/src/content/docs/operate/breg-monitor.mdx index c47b113267..c1220609be 100644 --- a/docs/site/src/content/docs/operate/breg-monitor.mdx +++ b/docs/site/src/content/docs/operate/breg-monitor.mdx @@ -462,7 +462,7 @@ Find the code the command, log, or HTTP problem printed. A `*` stands for any pa | `startup.runtime-role.grants-missing` | The runtime role lost a grant. | Apply the active package again. | | `startup.role-mode.changed` | The ledger records split roles; the file names one. | Restore the runtime role. | | `apply.successor.roles-differ` | The file names other roles than the active activation. | Apply the active package under the new roles, then the successor. | -| `startup.audit.refused` | The audit destination or hash key was refused. | Secret files are regular, owned by the running user, mode `0400` or `0600`, with one link. The audit directory and its files are owned by the running user, the directory `0700`. | +| `startup.audit.refused` | The audit destination or hash key was refused. | Secret files meet the [secret file rule](../../security/hardening-checklist/#secret-files), for example regular, owned by the running user, mode `0400` or `0600`, with one link. The audit directory and its files are owned by the running user, the directory `0700`. | | `startup.cursor.refused` | The cursor secret was refused. | As above. | | `startup.oidc.refused` | The issuer's key set could not be loaded, or a pinned static key set was refused. | Check that this host reaches and trusts the issuer. For a pinned key set refused by the shared key rules, the message names the rule and, for a rule about one key, its position: correct that key. A key set refused by BReg's own rules (`use`, `key_ops`, a denied `kid`, the algorithm, or the number of keys) gets the general OIDC message: check those members. | | `authentication.refused` | A token was refused. | Check [what a token must carry](../breg/#what-a-token-must-carry); `aud` may be a list of up to 16 that includes the audience. | @@ -550,7 +550,7 @@ Find the code the command, log, or HTTP problem printed. A `*` stands for any pa crates/registry-bregctl/src/lib.rs, data command failures, import_authority_failure(), instance_claim_failure(), apply_lifecycle_failure(); crates/registry-breg/src/migration.rs; crates/registry-breg/src/auth.rs, MAX_AUDIENCES; - crates/registry-platform-config/src/secrets.rs, validate_file_metadata(); + crates/registry-platform-config/src/secrets.rs, judge_file(); crates/registry-breg/src/startup.rs, DynamicRuntimeReadiness; crates/registry-breg/src/postgres/context.rs, begin_registry_transaction(); crates/registry-breg/tests/postgres_startup.rs, diff --git a/docs/site/src/content/docs/operate/breg-webhooks.mdx b/docs/site/src/content/docs/operate/breg-webhooks.mdx index 42016108e5..a4719f5529 100644 --- a/docs/site/src/content/docs/operate/breg-webhooks.mdx +++ b/docs/site/src/content/docs/operate/breg-webhooks.mdx @@ -267,7 +267,7 @@ The key must be at least 32 bytes, and the file a regular file owned by the user with mode `0400` or `0600`; `doctor` and startup refuse anything else. {/* Evidence: crates/registry-platform-crypto/src/delivery_signature.rs, MIN_HMAC_SHA256_KEY_BYTES; - crates/registry-platform-config/src/secrets.rs, read_secret_file() and validate_file_metadata(). */} + crates/registry-platform-config/src/secrets.rs, read_secret_file() and judge_file(). */} ## Build the receiver against a sample diff --git a/docs/site/src/content/docs/operate/breg.mdx b/docs/site/src/content/docs/operate/breg.mdx index 0578f64753..6c88e2e40e 100644 --- a/docs/site/src/content/docs/operate/breg.mdx +++ b/docs/site/src/content/docs/operate/breg.mdx @@ -230,9 +230,9 @@ the metrics listener in [Scrape metrics](../breg-monitor/#scrape-metrics). ### Create the secret files -Create the files as the user that runs `breg` and the operator commands, because the resolver -refuses a file owned by anyone else. Each must be a regular file with mode `0400` or `0600`, with -no other hard link and no symbolic link to it. A name starts with a lowercase letter and uses +Create the files as the user that runs `breg` and the operator commands. Each must meet the +[secret file rule](../../security/hardening-checklist/#secret-files): for example a regular file +you own with mode `0400` or `0600` and no other hard link. A name starts with a lowercase letter and uses lowercase letters, digits, `.`, `_`, and `-`. The bytes are used exactly as written, so write them without a trailing newline: @@ -255,7 +255,7 @@ In a container platform that injects secrets as environment variables, declare `secretProviders.environment` and write `secret:env/` instead. {/* Evidence: crates/registry-platform-config/src/secrets.rs, read_secret_file(), - validate_file_metadata(), read_environment(); crates/registry-platform-yaml/src/secret.rs, + judge_file(), read_environment(); crates/registry-platform-yaml/src/secret.rs, valid_file_name(); crates/registry-platform-audit/src/lib.rs, MIN_AUDIT_SECRET_BYTES; crates/registry-breg/src/cursor.rs, ROOT_SECRET_MIN_BYTES; crates/registry-breg/src/runtime_config.rs, database_connection_config_for(). */} @@ -856,7 +856,7 @@ docker run --restart on-failure \ restart policy's backoff bounds how often. {/* Evidence: release/docker/Dockerfile.breg; crates/registry-breg/src/runtime_config.rs, - ListenerConfig; crates/registry-platform-config/src/secrets.rs, validate_file_metadata(); + ListenerConfig; crates/registry-platform-config/src/secrets.rs, judge_file(); crates/registry-platform-config/src/loader.rs, require_trusted_runtime_path(), require_trusted_ownership(); crates/registry-platform-audit/src/writer.rs, validate_directory(), validate_active_metadata(). */} @@ -885,8 +885,10 @@ container's. `apply` writes audit entries beside `audit.path`, which is why the writable here too. Kubernetes is outside the verified deployment profile. A ConfigMap or Secret volume mounted the -default way presents each key as a symbolic link, which the runtime refuses for both the runtime -file and secret files; inject secrets through `secret:env/` instead. +default way presents each key as a symbolic link, which the runtime refuses for the runtime file. +Secret files accept the link chain Kubernetes writes under the +[secret file rule](../../security/hardening-checklist/#secret-files), which gives the volume +settings that rule needs. {/* Evidence: release/docker/Dockerfile.breg, the bregctl install line and the breg ENTRYPOINT; crates/registry-breg/src/audit.rs, RegistryAudit::open_companion(); diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index a5650e7638..37772774f9 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -122,14 +122,14 @@ explicit nulls are refused at their position; omit a key to take its default. every later apply and start refuses a database that recorded another. Each `...Ref` key names a secret, never its value: `secret:file/` resolves under -`secretProviders.file.root`. Mount each secret as a file owned by the runtime user, mode `0400` or -`0600`, with no symbolic or extra hard link. `operator-controlled-upstream` requires +`secretProviders.file.root`. Each secret file must meet the +[secret file rule](../../security/hardening-checklist/#secret-files). `operator-controlled-upstream` requires `allowedClients` to list its clients. Ship the audit journal to your archive; [Review retention and audit](../casework-retention/#keep-the-audit-file) covers its key and rotation. {/* Evidence: crates/registry-casework/src/config.rs, RuntimeConfig; - crates/registry-platform-config/src/secrets.rs, validate_file_metadata(). */} + crates/registry-platform-config/src/secrets.rs, judge_file(). */} ### Add a current-source provider diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index c3f0e56c1f..e57e3e46bc 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -173,7 +173,7 @@ A caller recovering an unknown admission must send the exact original start key, Create every secret as the user that runs `coordinator` and `coordinatorctl`. A `secret:file/NAME` reference reads the file `NAME` directly under the file provider's `root`. -That file must be a regular file owned by that user, with mode `0400` or `0600` and exactly one link. +That file must meet the [secret file rule](../../security/hardening-checklist/#secret-files), for example a regular file owned by that user, with mode `0400` or `0600` and exactly one link. A `secret:env/NAME` reference reads an environment variable when `secretProviders` declares `environment: {}`. Coordinator uses three kinds of key, each exactly 32 raw random bytes in its own file: diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index 2a475be444..c5c9be2ff0 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -178,7 +178,7 @@ unset value ``` Write `smtp-username`, `smtp-password`, `sms-gateway-token`, and `sms-gateway-callback-key` the same -way. Each must be a regular file owned by the runtime user, mode `0400` or `0600`, with one link. +way. Each must meet the [secret file rule](../../security/hardening-checklist/#secret-files), for example a regular file owned by the runtime user, mode `0400` or `0600`, with one link. `serve` never reads the migration credential; only `provision`, `apply`, and `retention erase-expired` read it. Write `migration-database-url`, the URL for @@ -539,7 +539,7 @@ first exits 2 and the others exit 1: | ``messaging: the Messaging package at package.root does not satisfy the shared package envelope: the package at does not match its SHA256SUMS; changed: messaging.yaml; rebuild the package with `messagingctl package` and deploy the whole directory`` | A package file was changed in place. Deploy the directory `messagingctl package` wrote, unchanged. A missing directory is reported the same way, as `does not exist or cannot be read` | | `messaging: package.expectedDigest does not pin the package at package.root, whose digest is sha256:; deploy the pinned package or update package.expectedDigest` | The package on disk is not the one `package.expectedDigest` names | | `messaging: the Messaging runtime database configuration failed: the Messaging database secret could not be resolved: the secret reference configured at database.runtimeUrlRef could not be resolved: no readable secret of that name exists under the configured provider` | No file of that name exists under `secretProviders.file.root`, or the runtime user cannot read it | -| `messaging: the Messaging runtime database configuration failed: the Messaging database secret could not be resolved: the secret reference configured at database.runtimeUrlRef could not be resolved: the secret file must be a regular file owned by the runtime user, with mode 0400 or 0600, and exactly one hard link` | The file exists but is a symbolic link, belongs to another user, has another mode, or has a second hard link | +| `messaging: the Messaging runtime database configuration failed: the Messaging database secret could not be resolved: the secret reference configured at database.runtimeUrlRef could not be resolved: the secret file has more than one hard link (platform.secret-file.hard-linked). Replace it with a copy that has one link.` | The file exists but fails a [secret file check](../../reference/errors/#secret-file-codes). The refusal names the check: here a second hard link, and other files report a link that leaves the root, another owner, or a loose mode | | `messaging: the Messaging database connection could not be established: Error occurred while creating a new object: error connecting to server` | Nothing answers at the URL's host and port. `error performing TLS handshake` in its place means the server certificate is not trusted; name the CA bundle in `database.caBundleRef` | | `messaging: the Messaging query failed: db error` | The database has no schema yet. Run `messagingctl plan`, then `apply`, with the migration credential | | `messaging: identity.databaseId does not match the database activation ledger` | The runtime file names another deployment's `identity.databaseId`, or its URL reaches another deployment's database | diff --git a/docs/site/src/content/docs/operate/registry-render.mdx b/docs/site/src/content/docs/operate/registry-render.mdx index c657e88910..c3b61d4b0f 100644 --- a/docs/site/src/content/docs/operate/registry-render.mdx +++ b/docs/site/src/content/docs/operate/registry-render.mdx @@ -122,8 +122,9 @@ These rules are not in the tables: when `secretProviders.environment: {}` is declared. A reference to an undeclared provider is refused. - A file a `secret:file/` reference names (the API key, an OIDC key set, a seal key, a CA bundle) - is a regular file owned by the user serve runs as, with mode `0400` or `0600` and a single link. - Serve follows no symbolic link to one, and refuses any other file at startup with + meets the [secret file rule](../../security/hardening-checklist/#secret-files), for example a + regular file owned by the user serve runs as, with mode `0400` or `0600` and a single link. + Serve refuses any other file at startup with `runtime-invalid` and the message `the referenced secret file is unsafe`. - A string value may come from the environment as `${VAR}`, `${VAR:-default}`, or `${VAR:?message}`, except in `apiKeyRef` and under `secretProviders`. diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index a8b4ac1612..08a0df415c 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -22,8 +22,9 @@ step runs `schedulingctl` or `scheduling` against one runtime file. connection and refuses one it cannot protect. - An OpenID Connect issuer whose access tokens carry the read scope and, for bookings, the [task grant](../../reference/glossary/#task-grant) another system issues. -- A directory of secret files owned by the runtime user, each with mode 0400 or 0600 and - written without a trailing newline. +- A directory of secret files that meet the + [secret file rule](../../security/hardening-checklist/#secret-files), each written without a + trailing newline. - A TLS edge in front of the listener. Scheduling serves plain HTTP on a private address and refuses a public one. diff --git a/docs/site/src/content/docs/reference/bregctl-dev.mdx b/docs/site/src/content/docs/reference/bregctl-dev.mdx index 0efed74200..317b04b50f 100644 --- a/docs/site/src/content/docs/reference/bregctl-dev.mdx +++ b/docs/site/src/content/docs/reference/bregctl-dev.mdx @@ -705,7 +705,7 @@ secretProviders: environment: {} ``` -A referenced file must be an ordinary file you own, with mode 0400 or 0600 and a single link. +A referenced file must meet the [secret file rule](../../security/hardening-checklist/#secret-files), for example an ordinary file you own, with mode 0400 or 0600 and a single link. A referenced value must be non-empty, contain no NUL byte, and fit the member's limit. The session copies each value into its private state when it is prepared, so editing a referenced file later changes nothing until the session is replaced. diff --git a/docs/site/src/content/docs/reference/casework-configuration.mdx b/docs/site/src/content/docs/reference/casework-configuration.mdx index 2089c74396..fe2d3ab240 100644 --- a/docs/site/src/content/docs/reference/casework-configuration.mdx +++ b/docs/site/src/content/docs/reference/casework-configuration.mdx @@ -150,7 +150,7 @@ When set, the runtime serves `/metrics` and `/version` there and nowhere else. The runtime does not fall back from one provider to another. The maintained example uses mounted files. -{/* Evidence: crates/registry-platform-config/src/secrets.rs validate_file_metadata; +{/* Evidence: crates/registry-platform-config/src/secrets.rs judge_file; crates/registry-casework/src/config.rs RuntimeConfig */} ## Database diff --git a/docs/site/src/content/docs/reference/environment-variables.mdx b/docs/site/src/content/docs/reference/environment-variables.mdx index c245f0a92a..f20908932f 100644 --- a/docs/site/src/content/docs/reference/environment-variables.mdx +++ b/docs/site/src/content/docs/reference/environment-variables.mdx @@ -66,7 +66,8 @@ and names `--runtime-config` as the replacement, rather than silently ignoring i Registry Evidence resolves secrets through the providers `runtime.yaml` declares under `secretProviders`: `file: {root: }` enables `secret:file/` references, -which resolve to an owner-only regular file under that directory, and `environment: {}` enables +which resolve to a regular file under that directory that meets the +[secret file rule](../../security/hardening-checklist/#secret-files), and `environment: {}` enables `secret:env/` references, which resolve to the operator-named environment variable. | Grammar | Resolves to | Accepted name | diff --git a/docs/site/src/content/docs/reference/errors.mdx b/docs/site/src/content/docs/reference/errors.mdx index 3bb4818a3a..7498ef5bcd 100644 --- a/docs/site/src/content/docs/reference/errors.mdx +++ b/docs/site/src/content/docs/reference/errors.mdx @@ -188,6 +188,28 @@ A session that failed because the wallet reported an error carries one `failureC closed set; a refusal for a spent budget or a full presentation store is `503` or `429` with `Retry-After`. +## Secret file codes + +A secret file the runtime refuses carries one of these `platform.secret-file.*` codes. The text +names the failed check and never a path, a reference, or a value. A product's own refusal keeps its +product code and repeats the check's text and fix. A process that declares the development posture +loads a file for `world-readable`, `group-access`, and `mode-bits`, and logs the code in the +`error_code` field of one warning per check. The [secret file rule](../../security/hardening-checklist/#secret-files) +states what each check accepts. + +| Code | Meaning | Fix | +| --- | --- | --- | +| `platform.secret-file.link-leaves-root` | The secret file is reached through a link that leaves `secretProviders.file.root`. | Put the file under `secretProviders.file.root`, or use a relative link without `..` that stays below it. | +| `platform.secret-file.too-many-links` | The secret file is reached through more than 8 links. | Point the name at the file, or at a chain of at most 8 links below `secretProviders.file.root`. | +| `platform.secret-file.cannot-open` | The runtime user cannot open the secret file. | Make the file readable by the runtime user: mode `0400` or `0600` owned by that user, or `0440` owned by root with the runtime user's group. On Kubernetes, set the secret volume's `defaultMode` to `0440` and the pod's `securityContext.fsGroup` to the runtime user's group. | +| `platform.secret-file.not-regular` | The secret file is not a regular file. | Point the name at a regular file, not a directory, device, socket or pipe. | +| `platform.secret-file.hard-linked` | The secret file has more than one hard link. | Replace it with a copy that has one link. | +| `platform.secret-file.owner` | The secret file is owned by neither the runtime user nor root. | Give it to the runtime user with mode `0400` or `0600`, or to root with mode `0440` and the runtime user's group. | +| `platform.secret-file.world-writable` | Users outside the file's owner and group can write the secret file. | Remove all access for others (`chmod o-rwx`). | +| `platform.secret-file.world-readable` | Users outside the file's owner and group can read the secret file. | Remove access for others: mode `0400` or `0600` for a file the runtime user owns, `0440` for a root-owned file. On Kubernetes, set the secret volume's `defaultMode` to `0440` and the pod's `securityContext.fsGroup` to the runtime user's group. | +| `platform.secret-file.group-access` | The secret file's group has access the rule does not allow. | Use mode `0400` or `0600` for a file the runtime user owns. Group read is accepted only on a root-owned file (`0440` or `0640`) read by a non-root runtime. | +| `platform.secret-file.mode-bits` | The secret file has an execute, setuid, setgid or sticky bit, or its owner cannot read it. | Set mode `0400` or `0600`. | + ## Retired Relay codes Registry Relay and its problem-code catalogue were retired in Registry Stack 0.39.0. Existing diff --git a/docs/site/src/content/docs/reference/render-configuration.mdx b/docs/site/src/content/docs/reference/render-configuration.mdx index 4e8b519b08..7b1cd7f4f7 100644 --- a/docs/site/src/content/docs/reference/render-configuration.mdx +++ b/docs/site/src/content/docs/reference/render-configuration.mdx @@ -180,8 +180,8 @@ Without `--environment`, `check` reads no chain file and says so: the human outp `"sealChains": "not-read"`. `serve` alone also reads the key and the timestamp authority's CA bundle, and reports -`render.runtime.seal-key-unreadable` (with the secret provider's reason; a key file must be a -regular file owned by the serving user, with mode 0600 or 0400 and one link), +`render.runtime.seal-key-unreadable` (with the secret provider's reason; a key file must meet the +[secret file rule](../../security/hardening-checklist/#secret-files)), `render.runtime.seal-key-invalid`, `render.runtime.seal-key-unsupported`, `render.runtime.seal-key-mismatch` (the key file, or the Transit key version, is not the key the certificate certifies), `render.runtime.seal-transit-unavailable` (the Transit proxy does not diff --git a/docs/site/src/content/docs/reference/scheduling-configuration.mdx b/docs/site/src/content/docs/reference/scheduling-configuration.mdx index 3879edbcd8..4d74f19dbd 100644 --- a/docs/site/src/content/docs/reference/scheduling-configuration.mdx +++ b/docs/site/src/content/docs/reference/scheduling-configuration.mdx @@ -187,8 +187,9 @@ The maintained example uses mounted files. A secret reference is `secret:env/NAME` with an uppercase environment name, or `secret:file/name` with a lowercase file name, each of at most 128 bytes. A resolved value is non-empty text of at most 64 KiB without NUL bytes. -A secret file must be a regular file owned by the runtime user, with mode 0400 or 0600 and exactly -one hard link. +A secret file must meet the [secret file rule](../../security/hardening-checklist/#secret-files), +for example a regular file owned by the runtime user, with mode 0400 or 0600 and exactly one hard +link. Generate the audit key with `openssl rand -hex 32`. {/* Evidence: crates/registry-scheduling/src/config.rs secret_reference, diff --git a/docs/site/src/content/docs/security/evidence.mdx b/docs/site/src/content/docs/security/evidence.mdx index df7dcdcedc..31c7fa3ece 100644 --- a/docs/site/src/content/docs/security/evidence.mdx +++ b/docs/site/src/content/docs/security/evidence.mdx @@ -434,9 +434,8 @@ The matrix describes what the `evidence` binary enforces. The [operator contract](https://github.com/registrystack/registry-stack/blob/main/products/evidence/OPERATOR-CONTRACT.md) holds the duties no service-side control can hold for you: -- Keep every secret file below `secretProviders.file.root` a regular, - non-symlink file owned by the service identity with mode `0400` or `0600`. - The file provider refuses anything else. +- Keep every secret file below `secretProviders.file.root` within the + [secret file rule](../hardening-checklist/#secret-files). The file provider refuses anything else. - Generate the audit and subject-binding masters independently, at least 32 bytes each, under distinct references. The runtime refuses equal references or equal bytes. diff --git a/docs/site/src/content/docs/security/hardening-checklist.mdx b/docs/site/src/content/docs/security/hardening-checklist.mdx index fa79f897ee..fbbbad4fdb 100644 --- a/docs/site/src/content/docs/security/hardening-checklist.mdx +++ b/docs/site/src/content/docs/security/hardening-checklist.mdx @@ -35,10 +35,8 @@ of the shared audit writer that these products and Registry Render use. revoked or malformed active public JWK, and `evidence check --require-runtime-dependencies` on the target host refuses a configured signer that does not match it. - Supply local-assurance private JWKs, HMAC keys, and source credentials through - `secret:file/` references below `secretProviders.file.root`. The file provider accepts only - regular, non-symlink files owned by the service identity at mode `0400` or `0600`, and checks - owner, mode, link count, no-follow behaviour, and open-file identity. Keep the secret root - operator-only. + `secret:file/` references below `secretProviders.file.root`. The file provider applies the + rule in [Secret files](#secret-files). Keep the secret root operator-only. - Prefer the file provider with a secret root dedicated to the deployment. Enable `secretProviders.environment: {}` only for a dedicated, curated process environment. Review each bundle `secret:env/` reference because an enabled environment provider can resolve any @@ -70,6 +68,56 @@ of the shared audit writer that these products and Registry Render use. crates/registry-breg/src/startup.rs, FieldEncryptionCustody; crates/registry-bregctl/src/doctor.rs, startup_diagnostic. */} +## Secret files + +Every `secret:file/` reference resolves under `secretProviders.file.root`. Every runtime +applies one rule when it opens the file. The check runs on the open file, so a file replaced after +the check is not read. + +The file must meet all of these: + +- It is a regular file with one hard link. A directory, device, socket, or pipe is refused. +- It is reached from the root by downward steps only. The name may be a relative link, such as the + chain Kubernetes writes for a mounted Secret, through at most 8 links. A link that is absolute or + holds `..` is refused, so is a link that leaves the root. The root itself must not be a link. +- Others have no access: no read and no write. +- Its owner and mode are one of two shapes. The runtime user owns it with mode `0400` or `0600`. + Or root owns it with no bit outside `0640`, usually `0440` or `0640`, and the runtime is not + root. The runtime then reads it through the file's group. +- No execute, setuid, setgid, or sticky bit is set, and a file the runtime user owns can be read + by that user. + +A file the runtime user owns with any group access is refused. Group read is accepted only on a +file root owns. Give that file's group to the runtime user alone, because every member of the group +can read the secret. On a plain host that is every member of the group in `/etc/group`. + +The root directory's own mode is not part of this rule. Registry Evidence separately requires a +secret root that group and other cannot reach, and `evidence doctor` reports it. + +Each refusal names the failed check by a `platform.secret-file.*` code and states the fix. The +[error reference](../../reference/errors/#secret-file-codes) lists the ten codes. + +A process that declares the development posture loads a file whose read or mode bits are too loose +(`world-readable`, `group-access`, `mode-bits`) and logs one warning per check. Every other +refusal holds in development. Production refuses all of them. + +### Make the files meet the rule + +- **Host or systemd.** Create each file as the service user with `install -m 0400`, or as root with + `chown root:` and `chmod 0440`. Keep the service group to the service user. +- **Kubernetes.** Mount the Secret with `defaultMode: 0440` and set the pod's + `securityContext.fsGroup` to the runtime user's group. The kubelet then presents root-owned files + readable through that group, which the rule accepts, including the link chain it writes. A + `defaultMode` of `0400` without `fsGroup` leaves a root-owned file the runtime user cannot open, + and `0644` is refused as world-readable. `fsGroup` applies to every container in the pod and to + the pod's other volumes, so check that nothing else in the pod needs owner-only volumes. +- **The Helm chart.** The chart stages each secret into a memory volume owned by the runtime user + at mode `0400`, which the rule accepts. It does not use `fsGroup`. See the chart's README. +- **Docker Compose.** A Compose file secret keeps the host file's owner and mode on some hosts, and + on others Compose ignores the `uid`, `gid`, and `mode` you declare and presents the file + world-readable, which production refuses. Prepare a volume or bind-mounted directory with the + owner and mode above instead. + ## Check BReg and Casework authority 1. Use separate migration and runtime database roles with TLS. Run the product's doctor against diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index 87c29cb453..3694630427 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- A secret file the Adapter or an Adapter job refuses names the failed + check and its fix. A link below the secret root now loads, so the hint + that a link reads as a missing file is gone. + - `adapterctl provision --runtime-config FILE` creates the migration and runtime roles and the database from the runtime file's two database URLs, as a non-superuser administrator over verified TLS, or prints the script with diff --git a/products/adapter/schemas/job-runtime.v1alpha1.schema.json b/products/adapter/schemas/job-runtime.v1alpha1.schema.json index 05c419c9a4..8737031701 100644 --- a/products/adapter/schemas/job-runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/job-runtime.v1alpha1.schema.json @@ -104,7 +104,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/adapter/schemas/runtime.v1alpha1.schema.json b/products/adapter/schemas/runtime.v1alpha1.schema.json index e0bc59573f..1dd974bf56 100644 --- a/products/adapter/schemas/runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/runtime.v1alpha1.schema.json @@ -176,7 +176,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index ea53571bcd..f5b3ae7ff0 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- A secret file BReg refuses at startup reports the check that failed and + its fix under `breg.runtime.secret`, instead of one fixed sentence. + - `bregctl provision` creates the PostgreSQL objects a Registry needs, from the two database URLs in its runtime file and an administrator URL read from `--admin-url-file` or `--admin-url-env`. It creates or adopts the migration diff --git a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json index 712504ac38..eb79f079b8 100644 --- a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json @@ -199,7 +199,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/breg/generated/review-runtime/review-runtime.schema.json b/products/breg/generated/review-runtime/review-runtime.schema.json index dcb17ed224..e0e54265e3 100644 --- a/products/breg/generated/review-runtime/review-runtime.schema.json +++ b/products/breg/generated/review-runtime/review-runtime.schema.json @@ -128,7 +128,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/breg/generated/runtime/runtime.schema.json b/products/breg/generated/runtime/runtime.schema.json index 680738124e..3b07dc9c24 100644 --- a/products/breg/generated/runtime/runtime.schema.json +++ b/products/breg/generated/runtime/runtime.schema.json @@ -716,7 +716,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/breg/generated/tools/dev-clients.v1alpha1.schema.json b/products/breg/generated/tools/dev-clients.v1alpha1.schema.json index 229310ed2d..77c7e0459a 100644 --- a/products/breg/generated/tools/dev-clients.v1alpha1.schema.json +++ b/products/breg/generated/tools/dev-clients.v1alpha1.schema.json @@ -171,7 +171,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/casework/generated/runtime/runtime.schema.json b/products/casework/generated/runtime/runtime.schema.json index 8157541e5a..fa158e0311 100644 --- a/products/casework/generated/runtime/runtime.schema.json +++ b/products/casework/generated/runtime/runtime.schema.json @@ -339,7 +339,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index 53250f3fb3..bbe74e92c8 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -781,7 +781,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/documents/generated/runtime/runtime.schema.json b/products/documents/generated/runtime/runtime.schema.json index 4183fcd8bd..cab162e1a2 100644 --- a/products/documents/generated/runtime/runtime.schema.json +++ b/products/documents/generated/runtime/runtime.schema.json @@ -262,7 +262,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/evidence/CHANGELOG.md b/products/evidence/CHANGELOG.md index 3225251867..18aa9d5efc 100644 --- a/products/evidence/CHANGELOG.md +++ b/products/evidence/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- `evidence doctor` judges secret files with the runtime's rule. It no + longer demands exactly `0400` or `0600`, and it accepts a link chain that + stays inside the secret root. It still requires a secret root that group + and other cannot reach, as the runtime does. + - Evidence counts every `401`, `403` and `429` answer by the check that failed in `evidence_request_refusals_total{check}` on the private metrics listener, and writes one `request refused` log line with the check and the request's diff --git a/products/evidence/OPERATOR-CONTRACT.md b/products/evidence/OPERATOR-CONTRACT.md index d1d995cc22..1433317962 100644 --- a/products/evidence/OPERATOR-CONTRACT.md +++ b/products/evidence/OPERATOR-CONTRACT.md @@ -129,7 +129,9 @@ package report lists. The list is the deduplicated union of governed bundle references and generated runtime references, including a local signer's private-key reference; it never resolves or reports a value. Secret ownership and mode requirements remain unchanged: each referenced -secret is a regular owner-only file accepted by the eventual service identity. +secret is a regular file that meets the shared secret-file rule: one hard link, owned by the +eventual service identity (mode 0400 or 0600) or by root (no bit outside 0640), and never +accessible to others. The package and runtime must be non-writable to that identity. The runtime is target-specific and remains outside the immutable `bundle/`. Signed assertions continue to carry only a configuration revision as `configurationRevision`. That value is scoped to the one requirement diff --git a/products/evidence/contracts/bundle.schema.yaml b/products/evidence/contracts/bundle.schema.yaml index 08401ac1f9..0cd1d3dc85 100644 --- a/products/evidence/contracts/bundle.schema.yaml +++ b/products/evidence/contracts/bundle.schema.yaml @@ -2264,8 +2264,10 @@ secret_policy: There is no query-string placement, so no credential can reach a token URL, and the token URL, body, response, and debug output are still fully redacted. file_provider_rule: >- - Resolve secret:file logical names beneath the configured owner-controlled file root, reject - symlinks and path traversal, require regular owner-only files, and parse values as data. + Resolve secret:file logical names beneath the configured owner-controlled file root, follow + only relative downward links, reject path traversal, require regular files that meet the shared + secret-file rule (owned by the service identity or root, never accessible to others), and parse + values as data. environment_provider_rule: >- Resolve secret:env names from the process environment only when the runtime declares secretProviders.environment; a bundle reference naming the environment is refused at diff --git a/products/evidence/contracts/security-invariant-matrix.yaml b/products/evidence/contracts/security-invariant-matrix.yaml index c5ac7cff83..f3baa15b4f 100644 --- a/products/evidence/contracts/security-invariant-matrix.yaml +++ b/products/evidence/contracts/security-invariant-matrix.yaml @@ -382,7 +382,7 @@ cross_cutting: negative_test: sec-unsigned-envelope-not-jws secret_file_identity: threat: A group- or world-accessible, symlinked, multi-link, or oversized secret file exposes or substitutes key material. - enforcement: File secrets must be regular owner-only files opened without following symlinks, with exact service ownership, exact mode 0400 or 0600, single-hard-link, and size checks before use. + enforcement: File secrets must be regular files with one hard link, reached from the file root by relative downward links only, owned by the service identity with mode 0400 or 0600 or by root with no bit outside 0640 read through the service's group, never accessible to others, and size-checked before use. negative_test: sec-secret-file-identity transport_pinning: threat: Workspace dependency feature unification silently changes the TLS backend or introduces transport retries, breaking the per-stage request ceiling and TLS contracts. diff --git a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json index d3c56f7926..8f98c7068a 100644 --- a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json +++ b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json @@ -159,7 +159,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index 19607c4cb6..bd231e1b2b 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -421,7 +421,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index edabecfe43..5eeaa72286 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -4716,7 +4716,7 @@ }, "artifact": { "path": "products/adapter/schemas/job-runtime.v1alpha1.schema.json", - "sha256": "039e8186453aaa3fc9b1fa0cb230172dfe58f05c7b240bfd03f3e5404ef0338c", + "sha256": "de124e0af2f93259704f122d14db4be82304f3470f9e7dbbc0a8afe1b47cf1c9", "mediaType": "application/schema+json" } }, @@ -4896,7 +4896,7 @@ }, "artifact": { "path": "products/adapter/schemas/runtime.v1alpha1.schema.json", - "sha256": "51585af5aeff6da47672cfb2defc6a82b0da0a0fe748b09863e184c588c0f1c5", + "sha256": "acb55cefa753d2fe69ca959a9a35b85484dc9815aa3c92304f7ac256ec283233", "mediaType": "application/schema+json" } }, @@ -5004,7 +5004,7 @@ }, "artifact": { "path": "products/breg/generated/tools/dev-clients.v1alpha1.schema.json", - "sha256": "5020d8c8d12191760b03bfd268a0f11a8a88b7bc06982063573b7e48c9950fae", + "sha256": "cba3b8c3f830e27287b1869408b137cc8dffacf014ccc1875193617648fcc466", "mediaType": "application/schema+json" } }, @@ -5112,7 +5112,7 @@ }, "artifact": { "path": "products/breg/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "ee35b984ef1bf88adcd1e34d7940dae7f9d79c1da3dfdd77ee36433569b69e13", + "sha256": "bdce3a4a2d2b75c7e7e4eaa69dcf7ed5d9444a18169c4e3ab8d9069a4b8e5fc6", "mediaType": "application/schema+json" } }, @@ -5256,7 +5256,7 @@ }, "artifact": { "path": "products/breg/generated/review-runtime/review-runtime.schema.json", - "sha256": "abdb67296c19d687187ce2fea55bef59a47d5212ec5bb3925dcbef35778d5fc8", + "sha256": "bbb405e5aa3cd0417c128cfe9c83a568f1a9bfbc627723a7421a4760b34f3d99", "mediaType": "application/schema+json" } }, @@ -5292,7 +5292,7 @@ }, "artifact": { "path": "products/breg/generated/runtime/runtime.schema.json", - "sha256": "50c12375f8e3410c00d9dbfc9d7460370e0c69a757992975fa5fa96189e06fe7", + "sha256": "d33ce6ac211083c7b2f63fdbaecedd99579ced71f69ab4a745c48768a6ca39c4", "mediaType": "application/schema+json" } }, @@ -5400,7 +5400,7 @@ }, "artifact": { "path": "products/casework/generated/runtime/runtime.schema.json", - "sha256": "0c6aef414ad9becb38794ad1eb0b00b3c8220b507670e27de6b79da710f9b787", + "sha256": "134cc6da382230848063347306870a54367256560872ef00759ec8da1bf60777", "mediaType": "application/schema+json" } }, @@ -5436,7 +5436,7 @@ }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", - "sha256": "e2c774bceda48bfd6814629e779fee5a9613ac82b3c72ccd4a915d0c4e4dd1ee", + "sha256": "3cd8649e2c83f080febf2de58228c0f5fdd341abb2ad531876a8b80cd1631e76", "mediaType": "application/schema+json" } }, @@ -5616,7 +5616,7 @@ }, "artifact": { "path": "products/documents/generated/runtime/runtime.schema.json", - "sha256": "4d22626676c3d535dcca2c86c2d0f675b52b8dce81e3040ddee0462e7ed90420", + "sha256": "5a8b5deb0d312fe840b8445bac481bac73ad370c5562adbf5c9a94f8efe92557", "mediaType": "application/schema+json" } }, @@ -5648,11 +5648,11 @@ "description": "Evidence frozen Version 1 contract and configuration schemas, written as YAML.", "source": { "path": "products/evidence/contracts/bundle.schema.yaml", - "sha256": "53758ed115099de8f41b2060f7c3eb9442f0bdb8e89c5f1f6b3612702171c7b3" + "sha256": "b3797c856289fb46c1706362401392fadb2c41faeda051a41cf0408c3944df4a" }, "artifact": { "path": "products/evidence/contracts/bundle.schema.yaml", - "sha256": "53758ed115099de8f41b2060f7c3eb9442f0bdb8e89c5f1f6b3612702171c7b3", + "sha256": "b3797c856289fb46c1706362401392fadb2c41faeda051a41cf0408c3944df4a", "mediaType": "application/yaml" } }, @@ -5778,7 +5778,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json", - "sha256": "17c5085d53455e203add38e01b2eed330ec53b03bd0e242126b15ad2a58ffd79", + "sha256": "e337df8c818a5fef822c6e1638aff48187923990774f6d59569877e689dd12e5", "mediaType": "application/schema+json" } }, @@ -5796,7 +5796,7 @@ }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "b6ecde469f66120d97fbfb2840fecd42c564642510bda26b98b26ee7ab13cdfa", + "sha256": "b52e6e9fa334860bce9ff5d0d5cad65b5135834d431956ad6628009b5a5ca844", "mediaType": "application/schema+json" } }, @@ -6012,7 +6012,7 @@ }, "artifact": { "path": "products/messaging/generated/runtime/runtime.schema.json", - "sha256": "a91a90441db07340c50710d3bf2aa1a4d3eaf034af0ff1bda7eaa5ea299e09db", + "sha256": "2fa43db649ef28e4c6d4bed81b4b4adf7b9a355cd7a3cfe585d776e4713e637a", "mediaType": "application/schema+json" } }, @@ -6084,7 +6084,7 @@ }, "artifact": { "path": "crates/registry-cli-api/schema/connections.schema.json", - "sha256": "259fec0a491aad88d6055aa0251b6a6baf7d7fdddab1429a04daa73feada8c2e", + "sha256": "8885a96cae62ec9a421f6327ec7b9d165991b6d7996763d20d018c3d7d249f39", "mediaType": "application/schema+json" } }, @@ -6156,7 +6156,7 @@ }, "artifact": { "path": "products/platform/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "9c10f7ac0154005eca148084abf7a0e1980642fbea9e8f2fa30da1c8d5fffa49", + "sha256": "aa723586746147ccf31fbedcdc14aa40ab4232783d7196390033f0241a393f95", "mediaType": "application/schema+json" } }, @@ -6192,7 +6192,7 @@ }, "artifact": { "path": "products/platform/schemas/task-connection.schema.json", - "sha256": "aa5644178df3a358a1bf2a8c4db0e8e489dcdb142c68ff1d0286e39501729ddf", + "sha256": "aa6f4dded82d3614a2ce83916b0e916c63b12def7678a9eab9eb8aa67e55a7dd", "mediaType": "application/schema+json" } }, @@ -6264,7 +6264,7 @@ }, "artifact": { "path": "products/render/schemas/runtime.schema.json", - "sha256": "dfcd05130394e2dec5b8c9d739b2c8c60b680cb399a94c406125f80a707ae5f1", + "sha256": "c34fae9f80a3e3e1ec309794815f9d6d0518e6ce20bb6d2e3d613771554133aa", "mediaType": "application/schema+json" } }, @@ -6372,7 +6372,7 @@ }, "artifact": { "path": "products/scheduling/generated/runtime/runtime.schema.json", - "sha256": "27a6be5ada98978ac33e80e9054540b65c091748e9548744922d08e917ebd739", + "sha256": "5636616f2d0a6448cacfb982baf0be675d8019977ad970e3de936d504fbf7a31", "mediaType": "application/schema+json" } }, diff --git a/products/messaging/generated/runtime/runtime.schema.json b/products/messaging/generated/runtime/runtime.schema.json index 6a4481d1b1..4c67699d83 100644 --- a/products/messaging/generated/runtime/runtime.schema.json +++ b/products/messaging/generated/runtime/runtime.schema.json @@ -265,7 +265,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 415b263b99..a10765bfa2 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +- Every runtime reads a secret file under one rule. A relative link that + stays below `secretProviders.file.root` is followed, at most eight links + deep. A file owned by root with mode `0440` or `0640` loads when the + runtime does not run as root. A file the runtime user owns with group + access, a world-readable file, a file with an execute, setuid, setgid or + sticky bit, a hard-linked file and a link that leaves the root are refused. + Each refusal is a `SecretError::UnsafeFile` that names a + `platform.secret-file.*` check and its fix. A process that declares the + development posture loads a file whose read or mode bits are too loose and + warns once per check. `registry-platform-config` exports `SecretFileCheck` + and `MAX_SECRET_LINKS`, and `SecretResolver` gains `in_development` and + `inspect_reference`. + - BREAKING: `registry-platform-oidc` no longer has the stage-labelled authentication log helpers: `AuthenticationStage`, `AuthenticationDiagnostics`, `OidcError::authentication_stage`, diff --git a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json index 4e611deea9..5ed59368c5 100644 --- a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json @@ -287,7 +287,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index 53e54c7b4b..cd53b033bb 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -147,7 +147,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/platform/schemas/task-connection.schema.json b/products/platform/schemas/task-connection.schema.json index f8021704b0..8d7dcf5b10 100644 --- a/products/platform/schemas/task-connection.schema.json +++ b/products/platform/schemas/task-connection.schema.json @@ -17,7 +17,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/render/CHANGELOG.md b/products/render/CHANGELOG.md index ea6cbd1ab5..7a60338f86 100644 --- a/products/render/CHANGELOG.md +++ b/products/render/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- A secret file Render refuses names the failed check and its fix. + - A scope refusal writes the scope claim name and the scope the route requires on its `request refused` log line. The values are fixed by Render and never come from the caller's token. Responses are unchanged. diff --git a/products/render/schemas/runtime.schema.json b/products/render/schemas/runtime.schema.json index df91dbfad2..8e76f8e8c5 100644 --- a/products/render/schemas/runtime.schema.json +++ b/products/render/schemas/runtime.schema.json @@ -154,7 +154,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/products/scheduling/generated/runtime/runtime.schema.json b/products/scheduling/generated/runtime/runtime.schema.json index a3d1a69b97..59370708b3 100644 --- a/products/scheduling/generated/runtime/runtime.schema.json +++ b/products/scheduling/generated/runtime/runtime.schema.json @@ -286,7 +286,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } From e2d0fc3a16a854c87dfd98874bf667ab09b574aa Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 11:29:38 +0100 Subject: [PATCH 076/136] fix(ci): run the release image test and refresh two side lockfiles The gate inventory requires every release unit test in root CI, and the release image build test was missing from the release tooling job. The Wasm handler SDK and platform fuzz lockfiles now list the posture dependency their shared platform crates gained. Signed-off-by: Jeremi Joslin --- .github/workflows/ci.yml | 3 +++ products/breg/wasm-handler-sdk/Cargo.lock | 2 ++ products/platform/fuzz/Cargo.lock | 1 + 3 files changed, 6 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97dcc63f81..c1f6955f47 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2463,6 +2463,9 @@ jobs: - name: Test supporting release image packaging run: python3 -m unittest release/scripts/test_release_supporting_images.py + - name: Test release image build command + run: python3 -m unittest release/scripts/test_build_release_image.py + - name: Test release candidate manifest and promotion verifier run: python3 -m unittest release/scripts/test_release_candidate.py diff --git a/products/breg/wasm-handler-sdk/Cargo.lock b/products/breg/wasm-handler-sdk/Cargo.lock index 01143aa7fc..217fa81f0a 100644 --- a/products/breg/wasm-handler-sdk/Cargo.lock +++ b/products/breg/wasm-handler-sdk/Cargo.lock @@ -3078,6 +3078,7 @@ version = "0.49.0" dependencies = [ "http", "registry-platform-loopback", + "registry-platform-posture", "serde", "serde_json", "thiserror 2.0.21", @@ -3099,6 +3100,7 @@ dependencies = [ "registry-platform-canonical-json", "registry-platform-crypto", "registry-platform-loopback", + "registry-platform-posture", "reqwest", "rustls-native-certs", "serde", diff --git a/products/platform/fuzz/Cargo.lock b/products/platform/fuzz/Cargo.lock index 1ed8663648..5a52d89039 100644 --- a/products/platform/fuzz/Cargo.lock +++ b/products/platform/fuzz/Cargo.lock @@ -1867,6 +1867,7 @@ dependencies = [ "registry-platform-canonical-json", "registry-platform-crypto", "registry-platform-loopback", + "registry-platform-posture", "reqwest", "rustls-native-certs", "serde", From 7e98c27082ae8e53439658703b7281bde6bf7f75 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 11:34:03 +0100 Subject: [PATCH 077/136] feat(platform): record the declared posture in the activation ledger Each activation now stores the posture its package declared, and the active-package check refuses a runtime whose declared posture differs from the recorded one, naming both. Messaging, Documents, Casework and Scheduling add the column through a migration and report it from their ctl commands. Coordinator protected state moves to schema version 7, which records the posture with each activation and refuses a version 6 namespace. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + .../migrations/0201_activation_posture.sql | 9 + crates/registry-casework/src/activation.rs | 14 +- crates/registry-casework/src/store.rs | 17 +- .../registry-casework/tests/migration_pins.rs | 14 +- .../tests/review_migration_postgres.rs | 6 +- crates/registry-coordinator/src/deployment.rs | 22 +- crates/registry-coordinator/src/store.rs | 8 +- .../tests/deployment_postgres.rs | 16 +- .../migrations/0101_activation_posture.sql | 9 + crates/registry-documents/src/activation.rs | 40 ++- crates/registry-documents/src/store.rs | 7 +- .../tests/migration_pins.rs | 14 +- .../tests/postgres_documents.rs | 4 +- .../tests/postgres_operator.rs | 6 +- .../tests/postgres_startup.rs | 6 +- .../tests/postgres_cli.rs | 2 +- .../migrations/0102_activation_posture.sql | 9 + crates/registry-messaging/src/activation.rs | 40 ++- crates/registry-messaging/src/store.rs | 6 +- .../tests/migration_pins.rs | 4 + .../tests/postgres_messages.rs | 8 +- .../tests/postgres_migrate.rs | 10 +- .../tests/postgres_package.rs | 8 +- .../registry-platform-activation/Cargo.toml | 1 + .../registry-platform-activation/src/lib.rs | 115 ++++++- .../tests/postgres_activation.rs | 298 +++++++++++++++++- .../src/delivery/identity.rs | 4 +- .../migrations/0201_activation_posture.sql | 9 + crates/registry-scheduling/src/store.rs | 4 +- .../src/store/activation.rs | 46 ++- .../tests/migration_pins.rs | 14 +- .../tests/postgres_commitments.rs | 59 ++-- .../tests/activation_postgres.rs | 21 +- .../src/content/docs/operate/coordinator.mdx | 2 +- .../content/docs/reference/api-stability.mdx | 6 +- products/casework/CHANGELOG.md | 4 + products/coordinator/CHANGELOG.md | 6 + products/documents/CHANGELOG.md | 4 + products/messaging/CHANGELOG.md | 4 + products/platform/CHANGELOG.md | 10 + products/scheduling/CHANGELOG.md | 4 + 42 files changed, 713 insertions(+), 178 deletions(-) create mode 100644 crates/registry-casework/migrations/0201_activation_posture.sql create mode 100644 crates/registry-documents/migrations/0101_activation_posture.sql create mode 100644 crates/registry-messaging/migrations/0102_activation_posture.sql create mode 100644 crates/registry-scheduling/migrations/0201_activation_posture.sql diff --git a/Cargo.lock b/Cargo.lock index b1dfc7958d..590318e1b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7781,6 +7781,7 @@ name = "registry-platform-activation" version = "0.49.0" dependencies = [ "chrono", + "registry-platform-posture", "schemars", "serde", "serde_json", diff --git a/crates/registry-casework/migrations/0201_activation_posture.sql b/crates/registry-casework/migrations/0201_activation_posture.sql new file mode 100644 index 0000000000..f216a5fc55 --- /dev/null +++ b/crates/registry-casework/migrations/0201_activation_posture.sql @@ -0,0 +1,9 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- The activation ledger records the posture the activating process declared. +-- A row written before this column existed reads production: a database that +-- was never activated in development can never read as development. +ALTER TABLE casework_activations + ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); +ALTER TABLE casework_activations ALTER COLUMN posture DROP DEFAULT; diff --git a/crates/registry-casework/src/activation.rs b/crates/registry-casework/src/activation.rs index 5e4a8a9791..54dbf1ec1c 100644 --- a/crates/registry-casework/src/activation.rs +++ b/crates/registry-casework/src/activation.rs @@ -687,15 +687,15 @@ async fn apply_in( let activation = platform_activation::append_activation( transaction, &activation_layout(), - &NewActivation { + &NewActivation::without_posture( activation_id, - package_digest: candidate.package_digest, - database_id: candidate.database_id, - operator_reference_hash: operator_reference_hash.as_deref(), - backup_references: &request.backup_references, + candidate.package_digest, + candidate.database_id, + operator_reference_hash.as_deref(), + &request.backup_references, role_mode, - runtime_role: None, - }, + None, + ), ) .await .map_err(platform_error)?; diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index 9c8ea30b0e..d4a1b187ff 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -16,8 +16,13 @@ use uuid::Uuid; /// Every schema version, in the order it is applied. The baseline is /// version [`BASELINE_SCHEMA_VERSION`], above every version an earlier /// release applied; each later migration takes the next number. -pub(crate) const MIGRATIONS: [(i64, &str); 1] = - [(200, include_str!("../migrations/0200_reviews.sql"))]; +pub(crate) const MIGRATIONS: [(i64, &str); 2] = [ + (200, include_str!("../migrations/0200_reviews.sql")), + ( + 201, + include_str!("../migrations/0201_activation_posture.sql"), + ), +]; /// The baseline schema version. A ledger holding any version below it was /// left by an earlier pre-1.0 release, which this release refuses by name: /// version 100 is the v0.42.0 and v0.43.0 baseline, whose completion outbox @@ -942,12 +947,12 @@ mod schema_version_tests { } } assert!(refuse_unsupported_schema(&[]).is_ok()); - assert!(refuse_unsupported_schema(&[200]).is_ok()); + assert!(refuse_unsupported_schema(&[200, 201]).is_ok()); assert!(matches!( - refuse_unsupported_schema(&[200, 201]), + refuse_unsupported_schema(&[200, 201, 202]), Err(StoreError::SchemaNewer { - found: 201, - supported: 200 + found: 202, + supported: 201 }) )); } diff --git a/crates/registry-casework/tests/migration_pins.rs b/crates/registry-casework/tests/migration_pins.rs index 545c492080..b90a3ccb21 100644 --- a/crates/registry-casework/tests/migration_pins.rs +++ b/crates/registry-casework/tests/migration_pins.rs @@ -8,10 +8,16 @@ use std::path::Path; use registry_platform_testing::assert_migration_pins; -const PINS: &[(&str, &str)] = &[( - "0200_reviews.sql", - "72a4b39c7f2cc64e28c1241b76c7277ee4b2581832ca8a2168d84f46b94d6b98", -)]; +const PINS: &[(&str, &str)] = &[ + ( + "0200_reviews.sql", + "72a4b39c7f2cc64e28c1241b76c7277ee4b2581832ca8a2168d84f46b94d6b98", + ), + ( + "0201_activation_posture.sql", + "3eacf388a3ebcc488315291f17c466bcc877932fd2a3c83c2333b36d2d02f85f", + ), +]; #[test] fn every_migration_file_is_pinned_by_its_digest() { diff --git a/crates/registry-casework/tests/review_migration_postgres.rs b/crates/registry-casework/tests/review_migration_postgres.rs index 0ad431ba37..7d9434980b 100644 --- a/crates/registry-casework/tests/review_migration_postgres.rs +++ b/crates/registry-casework/tests/review_migration_postgres.rs @@ -346,7 +346,7 @@ async fn plan_against_an_empty_database_writes_nothing() { assert_eq!(plan.database_id_check, DatabaseIdCheck::NotRecorded); assert_eq!(plan.plan_kind, PlanKind::Initial); assert_eq!(plan.schema_version, None); - assert_eq!(plan.pending_schema_versions.len(), 1); + assert_eq!(plan.pending_schema_versions.len(), 2); assert!(plan.changes_pending, "{:?}", plan.refusals); assert_eq!( fixture.relation_count().await, @@ -370,7 +370,7 @@ async fn initial_apply_records_the_package_and_a_previous_package_reapplies_as_a .expect("initial apply"); assert_eq!(applied.activation.plan_kind, PlanKind::Initial); assert_eq!(applied.activation.role_mode, RoleMode::Single); - assert_eq!(applied.schema_versions_applied, vec![200]); + assert_eq!(applied.schema_versions_applied, vec![200, 201]); fixture .apply(&candidate(&project, &second, &[])) .await @@ -747,7 +747,7 @@ async fn split_role_runtime_cannot_write_the_ledgers_but_still_serves() { ); let client = connect(&fixture.runtime_url).await; for statement in [ - "INSERT INTO casework_activations(activation_id,apply_order,package_digest,database_id,plan_kind,role_mode) VALUES(gen_random_uuid(),99,'sha256:0000000000000000000000000000000000000000000000000000000000000000','x','initial','single')", + "INSERT INTO casework_activations(activation_id,apply_order,package_digest,database_id,plan_kind,role_mode,posture) VALUES(gen_random_uuid(),99,'sha256:0000000000000000000000000000000000000000000000000000000000000000','x','initial','single','production')", "UPDATE casework_activations SET database_id='x'", "DELETE FROM casework_activations", "TRUNCATE casework_activations", diff --git a/crates/registry-coordinator/src/deployment.rs b/crates/registry-coordinator/src/deployment.rs index d4608d6446..7d88762346 100644 --- a/crates/registry-coordinator/src/deployment.rs +++ b/crates/registry-coordinator/src/deployment.rs @@ -580,7 +580,7 @@ const SCHEMA_VERSION: i64 = crate::store::SCHEMA_VERSION as i64; /// with the namespace as the search path. Pinned with the protected state /// schema it records. pub(crate) fn activation_ledger_statements() -> String { - format!("CREATE TABLE IF NOT EXISTS coordinator_migrations(version bigint PRIMARY KEY); INSERT INTO coordinator_migrations VALUES({SCHEMA_VERSION}) ON CONFLICT DO NOTHING; CREATE TABLE IF NOT EXISTS coordinator_activations(activation_id uuid PRIMARY KEY,apply_order bigint UNIQUE NOT NULL,package_digest text NOT NULL,predecessor_package_digest text,database_id text NOT NULL,plan_kind text NOT NULL,applied_at timestamptz NOT NULL,operator_reference_hash text,backup_references text[] NOT NULL,role_mode text NOT NULL,runtime_role text NOT NULL)") + format!("CREATE TABLE IF NOT EXISTS coordinator_migrations(version bigint PRIMARY KEY); INSERT INTO coordinator_migrations VALUES({SCHEMA_VERSION}) ON CONFLICT DO NOTHING; CREATE TABLE IF NOT EXISTS coordinator_activations(activation_id uuid PRIMARY KEY,apply_order bigint UNIQUE NOT NULL,package_digest text NOT NULL,predecessor_package_digest text,database_id text NOT NULL,plan_kind text NOT NULL,applied_at timestamptz NOT NULL,operator_reference_hash text,backup_references text[] NOT NULL,role_mode text NOT NULL,runtime_role text NOT NULL,posture text NOT NULL CHECK(posture IN ('development','production'))); DO $$ BEGIN IF NOT EXISTS(SELECT 1 FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='coordinator_activations' AND column_name='posture') THEN ALTER TABLE coordinator_activations ADD COLUMN posture text NOT NULL DEFAULT 'production' CHECK(posture IN ('development','production')); END IF; END $$") } fn layout() -> Result { @@ -624,7 +624,7 @@ pub async fn check( .suggest("restore database connectivity") })?; let l = layout()?; - let active = activation::check_active_package(&*client, &l, &d.database_id, digest) + let active = activation::check_active_package_without_posture(&*client, &l, &d.database_id, digest) .await .map_err(|_| { fail("run coordinatorctl plan/apply with the correct database identity and packages, then restart every service") @@ -957,15 +957,15 @@ pub async fn apply( "runtime role must not own the schema, migrate or write activation ledgers", )); } - let request = NewActivation { - activation_id: Uuid::new_v4(), - package_digest: workflows.digest(), - database_id: &d.database_id, - operator_reference_hash: None, - backup_references: &[], - role_mode: RoleMode::Split, - runtime_role: Some(&d.runtime_role), - }; + let request = NewActivation::without_posture( + Uuid::new_v4(), + workflows.digest(), + &d.database_id, + None, + &[], + RoleMode::Split, + Some(&d.runtime_role), + ); let active = activation::append_activation(&tx, &l, &request) .await .map_err(|_| fail("restore activation ledger"))?; diff --git a/crates/registry-coordinator/src/store.rs b/crates/registry-coordinator/src/store.rs index 04e860d532..3c0cfa6263 100644 --- a/crates/registry-coordinator/src/store.rs +++ b/crates/registry-coordinator/src/store.rs @@ -51,7 +51,7 @@ enum InspectionBinding<'a> { /// The protected state schema version. It is written once, when apply creates /// the namespace, to `control.schema_version` and to the activation migration /// ledger, and every state transaction fences on it. -pub(crate) const SCHEMA_VERSION: i32 = 6; +pub(crate) const SCHEMA_VERSION: i32 = 7; /// Identifies a namespace whose tables this runtime created and owns. const NAMESPACE_MARKER: &str = "registry-coordinator protected-state"; @@ -3556,15 +3556,15 @@ mod tests { /// every statement that creates the schema, including the shared dispatch /// job table, its product widening, and the activation ledger. #[test] - fn schema_version_6_is_pinned() { + fn schema_version_7_is_pinned() { let mut ddl = schema_statements("coordinator_pin").expect("a valid namespace"); ddl.push(crate::deployment::activation_ledger_statements()); let digest = hex::encode(Sha256::digest(ddl.join("\n"))); assert_eq!( (SCHEMA_VERSION, digest.as_str()), ( - 6, - "c9e4c5df5c2d5f5dfe4a1db6ee69e05f637bc74e98a7a2f2db0bdc42b931ec91" + 7, + "ccc850397a0304baf054aa3315a789ac7889afa953abb3f93a32ccef8d181b48" ), "the protected state schema DDL changed at this SCHEMA_VERSION; {MIGRATION_PIN_RULE}" ); diff --git a/crates/registry-coordinator/tests/deployment_postgres.rs b/crates/registry-coordinator/tests/deployment_postgres.rs index 93882e4e92..e2a8396a30 100644 --- a/crates/registry-coordinator/tests/deployment_postgres.rs +++ b/crates/registry-coordinator/tests/deployment_postgres.rs @@ -563,8 +563,8 @@ async fn assert_reapply_preserves_schema_and_work( .get(0); assert!(!before["runs"].as_array().unwrap().is_empty()); assert!(!before["jobs"].as_array().unwrap().is_empty()); - assert_eq!(before["ledger"], json!([6])); - assert_eq!(before["schemaVersion"], 6); + assert_eq!(before["ledger"], json!([7])); + assert_eq!(before["schemaVersion"], 7); for _ in 0..2 { deployment::apply(migration, runtime, workflows, &[]) .await @@ -863,7 +863,7 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re assert_eq!(checked["databaseId"], "router-test"); assert_eq!(checked["workflowsDigest"], workflows_digest); assert_eq!(checked["workflows"], json!({"delayed-follow-up": digest})); - assert_eq!(checked["schemaVersion"], 6); + assert_eq!(checked["schemaVersion"], 7); assert_eq!(checked["runtimeRole"], role); assert_eq!(checked["active"]["roleMode"], "split"); status_doc["deployment"]["runtimeRole"] = json!("wrong_runtime_role"); @@ -980,7 +980,7 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re admin .batch_execute(&format!( "ALTER TABLE {namespace}.control DROP CONSTRAINT control_schema_version_check; - UPDATE {namespace}.control SET schema_version=5" + UPDATE {namespace}.control SET schema_version=6" )) .await .unwrap(); @@ -991,8 +991,8 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re ); admin .batch_execute(&format!( - "UPDATE {namespace}.control SET schema_version=6; - ALTER TABLE {namespace}.control ADD CONSTRAINT control_schema_version_check CHECK(schema_version=6)" + "UPDATE {namespace}.control SET schema_version=7; + ALTER TABLE {namespace}.control ADD CONSTRAINT control_schema_version_check CHECK(schema_version=7)" )) .await .unwrap(); @@ -1001,8 +1001,8 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re // write authority all refuse status while plan still reports observation. for (damage, repair) in [ ( - format!("INSERT INTO {namespace}.coordinator_migrations VALUES(7)"), - format!("DELETE FROM {namespace}.coordinator_migrations WHERE version=7"), + format!("INSERT INTO {namespace}.coordinator_migrations VALUES(8)"), + format!("DELETE FROM {namespace}.coordinator_migrations WHERE version=8"), ), ( format!("REVOKE SELECT ON {namespace}.jobs FROM {role}"), diff --git a/crates/registry-documents/migrations/0101_activation_posture.sql b/crates/registry-documents/migrations/0101_activation_posture.sql new file mode 100644 index 0000000000..7307045007 --- /dev/null +++ b/crates/registry-documents/migrations/0101_activation_posture.sql @@ -0,0 +1,9 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- The activation ledger records the posture the activating process declared. +-- A row written before this column existed reads production: a database that +-- was never activated in development can never read as development. +ALTER TABLE documents_activations + ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); +ALTER TABLE documents_activations ALTER COLUMN posture DROP DEFAULT; diff --git a/crates/registry-documents/src/activation.rs b/crates/registry-documents/src/activation.rs index 3bbfdb1bc6..52798881de 100644 --- a/crates/registry-documents/src/activation.rs +++ b/crates/registry-documents/src/activation.rs @@ -580,15 +580,15 @@ async fn apply_begun( let activation = platform::append_activation( &*tx, &layout(), - &NewActivation { + &NewActivation::without_posture( activation_id, package_digest, database_id, - operator_reference_hash: operator_reference_hash.as_deref(), - backup_references: &request.backup_references, + operator_reference_hash.as_deref(), + &request.backup_references, role_mode, - runtime_role: None, - }, + None, + ), ) .await .map_err(platform_error)?; @@ -649,18 +649,24 @@ pub async fn check_runtime( return Err(ActivationError::LedgerUnreadable); } crate::store::check_activation_schema(&**client).await?; - let active = platform::check_active_package(&**client, &layout(), database_id, package_digest) - .await - .map_err(|error| match error { - platform::ActivePackageError::NotActivated => ActivationError::NotActivated, - platform::ActivePackageError::DatabaseIdMismatch => ActivationError::DatabaseIdMismatch, - platform::ActivePackageError::PackageNotActive { .. } => { - ActivationError::PackageNotActive - } - platform::ActivePackageError::Activation(error) => { - ActivationError::Store(platform_error(error)) - } - })?; + let active = platform::check_active_package_without_posture( + &**client, + &layout(), + database_id, + package_digest, + ) + .await + .map_err(|error| match error { + platform::ActivePackageError::NotActivated => ActivationError::NotActivated, + platform::ActivePackageError::DatabaseIdMismatch => ActivationError::DatabaseIdMismatch, + platform::ActivePackageError::PackageNotActive { .. } => ActivationError::PackageNotActive, + // Until this product declares a posture it checks as production, + // so a ledger recorded in development is not its active package. + platform::ActivePackageError::PostureMismatch { .. } => ActivationError::PackageNotActive, + platform::ActivePackageError::Activation(error) => { + ActivationError::Store(platform_error(error)) + } + })?; crate::store::schema_ready(&client).await?; let role = observe(&**client, None) .await? diff --git a/crates/registry-documents/src/store.rs b/crates/registry-documents/src/store.rs index c67a28bc25..96d846c77c 100644 --- a/crates/registry-documents/src/store.rs +++ b/crates/registry-documents/src/store.rs @@ -18,11 +18,16 @@ use tokio_postgres::Config as PgConfig; use crate::config::{describe_secret_failure, DatabaseConfig}; const DOCUMENTS_MIGRATION: &str = include_str!("../migrations/0100_documents.sql"); +const ACTIVATION_POSTURE_MIGRATION: &str = + include_str!("../migrations/0101_activation_posture.sql"); /// Every schema version, in the order it is applied. Readiness requires the /// applied set to be exactly this list. The 1.0 baseline is version /// [`BASELINE_SCHEMA_VERSION`]; each later migration takes the next number. -pub(crate) const MIGRATIONS: [(i64, &str); 1] = [(100, DOCUMENTS_MIGRATION)]; +pub(crate) const MIGRATIONS: [(i64, &str); 2] = [ + (100, DOCUMENTS_MIGRATION), + (101, ACTIVATION_POSTURE_MIGRATION), +]; /// The 1.0 baseline schema version, shared with the other products. const BASELINE_SCHEMA_VERSION: i64 = 100; const _: () = assert!( diff --git a/crates/registry-documents/tests/migration_pins.rs b/crates/registry-documents/tests/migration_pins.rs index 5a5d9ee276..b59de6db40 100644 --- a/crates/registry-documents/tests/migration_pins.rs +++ b/crates/registry-documents/tests/migration_pins.rs @@ -8,10 +8,16 @@ use std::path::Path; use registry_platform_testing::assert_migration_pins; -const PINS: &[(&str, &str)] = &[( - "0100_documents.sql", - "d21dae145068a46052af7ec69076ad2bdf883a0e550325db66c811380fe91575", -)]; +const PINS: &[(&str, &str)] = &[ + ( + "0100_documents.sql", + "d21dae145068a46052af7ec69076ad2bdf883a0e550325db66c811380fe91575", + ), + ( + "0101_activation_posture.sql", + "b984c63d7402d024752955aed60dd3b9b5dd821a0210ca64a0e1bbc1a6ec1df9", + ), +]; #[test] fn every_migration_file_is_pinned_by_its_digest() { diff --git a/crates/registry-documents/tests/postgres_documents.rs b/crates/registry-documents/tests/postgres_documents.rs index 2a698aadf2..5fe30762c1 100644 --- a/crates/registry-documents/tests/postgres_documents.rs +++ b/crates/registry-documents/tests/postgres_documents.rs @@ -3889,9 +3889,9 @@ async fn the_runtime_is_ready_only_while_the_ledger_names_its_package_active() { .execute(&format!( "INSERT INTO documents_activations \ (activation_id, apply_order, package_digest, predecessor_package_digest, \ - database_id, plan_kind, applied_at, role_mode) \ + database_id, plan_kind, applied_at, role_mode, posture) \ SELECT gen_random_uuid(), apply_order + 1, 'sha256:{}', package_digest, \ - database_id, 'successor', now(), role_mode \ + database_id, 'successor', now(), role_mode, posture \ FROM documents_activations ORDER BY apply_order DESC LIMIT 1", "0".repeat(64) )) diff --git a/crates/registry-documents/tests/postgres_operator.rs b/crates/registry-documents/tests/postgres_operator.rs index 29121cb3c5..1fd24b327e 100644 --- a/crates/registry-documents/tests/postgres_operator.rs +++ b/crates/registry-documents/tests/postgres_operator.rs @@ -105,7 +105,7 @@ async fn a_fresh_database_is_refused_by_serve_until_the_package_is_applied() { .await .expect("the package applies"); assert!(applied.recorded); - assert_eq!(applied.schema_versions_applied, vec![100]); + assert_eq!(applied.schema_versions_applied, vec![100, 101]); assert_eq!(applied.activation.plan_kind, PlanKind::Initial); assert_eq!(applied.activation.role_mode, RoleMode::Single); prepare(&deployment.runtime) @@ -123,7 +123,7 @@ async fn plan_reports_the_change_and_writes_nothing() { assert_eq!(plan.change, ActivationChange::Activate); assert_eq!(plan.plan_kind, PlanKind::Initial); assert_eq!(plan.active_digest, None); - assert_eq!(plan.pending_schema_versions, vec![100]); + assert_eq!(plan.pending_schema_versions, vec![100, 101]); assert_eq!(plan.database_id, DatabaseIdCheck::NotRecorded); assert!(plan.refusals.is_empty(), "{:?}", plan.refusals); assert!(plan.package_digest.starts_with("sha256:")); @@ -256,7 +256,7 @@ async fn status_reports_the_active_package_and_its_history() { assert_eq!(active.activation_id, second.activation.activation_id); assert_eq!(active.package_digest, second.activation.package_digest); assert_eq!(active.database_id, "registry-documents-test"); - assert_eq!(status.schema_version, Some(100)); + assert_eq!(status.schema_version, Some(101)); assert_eq!( status .history diff --git a/crates/registry-documents/tests/postgres_startup.rs b/crates/registry-documents/tests/postgres_startup.rs index 5c2f5057a5..cf01fc052b 100644 --- a/crates/registry-documents/tests/postgres_startup.rs +++ b/crates/registry-documents/tests/postgres_startup.rs @@ -208,13 +208,13 @@ async fn applying_the_schema_twice_applies_nothing_twice() { .admin .query( &format!( - "SELECT version FROM {}.documents_schema_migrations", + "SELECT version FROM {}.documents_schema_migrations ORDER BY version", deployment.schema ), &[], ) .await .unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].get::<_, i64>(0), 100); + let versions: Vec = rows.iter().map(|row| row.get(0)).collect(); + assert_eq!(versions, [100, 101]); } diff --git a/crates/registry-documentsctl/tests/postgres_cli.rs b/crates/registry-documentsctl/tests/postgres_cli.rs index 02125b2805..7a00a1dfd9 100644 --- a/crates/registry-documentsctl/tests/postgres_cli.rs +++ b/crates/registry-documentsctl/tests/postgres_cli.rs @@ -555,7 +555,7 @@ async fn plan_reports_the_initial_activation_on_a_database_provisioned_as_the_op assert_eq!(plan["change"], "activate"); assert_eq!(plan["planKind"], "initial"); assert_eq!(plan["activeDigest"], Value::Null); - assert_eq!(plan["pendingSchemaVersions"], serde_json::json!([100])); + assert_eq!(plan["pendingSchemaVersions"], serde_json::json!([100, 101])); assert_eq!(plan["runtimeRoleMode"], Value::Null); assert_eq!(plan["refusals"], serde_json::json!([])); let output = Command::new(env!("CARGO_BIN_EXE_documentsctl")) diff --git a/crates/registry-messaging/migrations/0102_activation_posture.sql b/crates/registry-messaging/migrations/0102_activation_posture.sql new file mode 100644 index 0000000000..2d579e2254 --- /dev/null +++ b/crates/registry-messaging/migrations/0102_activation_posture.sql @@ -0,0 +1,9 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- The activation ledger records the posture the activating process declared. +-- A row written before this column existed reads production: a database that +-- was never activated in development can never read as development. +ALTER TABLE messaging_activations + ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); +ALTER TABLE messaging_activations ALTER COLUMN posture DROP DEFAULT; diff --git a/crates/registry-messaging/src/activation.rs b/crates/registry-messaging/src/activation.rs index c3fdebd605..82a97284bb 100644 --- a/crates/registry-messaging/src/activation.rs +++ b/crates/registry-messaging/src/activation.rs @@ -445,15 +445,15 @@ pub async fn apply( let activation = platform::append_activation( &*tx, &layout(), - &NewActivation { + &NewActivation::without_posture( activation_id, package_digest, database_id, - operator_reference_hash: operator_reference_hash.as_deref(), - backup_references: &request.backup_references, + operator_reference_hash.as_deref(), + &request.backup_references, role_mode, - runtime_role: None, - }, + None, + ), ) .await .map_err(platform_error)?; @@ -500,18 +500,24 @@ pub async fn check_runtime( ) -> Result { store.ready().await?; let client = store.client().await?; - let active = platform::check_active_package(&**client, &layout(), database_id, package_digest) - .await - .map_err(|error| match error { - platform::ActivePackageError::NotActivated => ActivationError::NotActivated, - platform::ActivePackageError::DatabaseIdMismatch => ActivationError::DatabaseIdMismatch, - platform::ActivePackageError::PackageNotActive { .. } => { - ActivationError::PackageNotActive - } - platform::ActivePackageError::Activation(error) => { - ActivationError::Store(platform_error(error)) - } - })?; + let active = platform::check_active_package_without_posture( + &**client, + &layout(), + database_id, + package_digest, + ) + .await + .map_err(|error| match error { + platform::ActivePackageError::NotActivated => ActivationError::NotActivated, + platform::ActivePackageError::DatabaseIdMismatch => ActivationError::DatabaseIdMismatch, + platform::ActivePackageError::PackageNotActive { .. } => ActivationError::PackageNotActive, + // Until this product declares a posture it checks as production, + // so a ledger recorded in development is not its active package. + platform::ActivePackageError::PostureMismatch { .. } => ActivationError::PackageNotActive, + platform::ActivePackageError::Activation(error) => { + ActivationError::Store(platform_error(error)) + } + })?; let role = platform::observe_role(&**client, &layout(), None, &[]) .await .map_err(platform_error)? diff --git a/crates/registry-messaging/src/store.rs b/crates/registry-messaging/src/store.rs index 251d8ac6de..2431d8a032 100644 --- a/crates/registry-messaging/src/store.rs +++ b/crates/registry-messaging/src/store.rs @@ -37,14 +37,17 @@ fn database_error_class(error: &tokio_postgres::Error) -> String { const MESSAGING_MIGRATION: &str = include_str!("../migrations/0100_messaging.sql"); const DISPATCH_LEASE_EXPIRY_MIGRATION: &str = include_str!("../migrations/0101_dispatch_lease_expiry.sql"); +const ACTIVATION_POSTURE_MIGRATION: &str = + include_str!("../migrations/0102_activation_posture.sql"); /// Every schema version, in the order it is applied. Readiness requires the /// applied set to be exactly this list. The 1.0 baseline is version /// [`BASELINE_SCHEMA_VERSION`], above every version a pre-1.0 release /// applied; each later migration takes the next number. -pub(crate) const MIGRATIONS: [(i64, &str); 2] = [ +pub(crate) const MIGRATIONS: [(i64, &str); 3] = [ (100, MESSAGING_MIGRATION), (101, DISPATCH_LEASE_EXPIRY_MIGRATION), + (102, ACTIVATION_POSTURE_MIGRATION), ]; /// The 1.0 baseline schema version. A ledger holding any version below it /// was left by a pre-1.0 release, which this release refuses by name. @@ -535,6 +538,7 @@ mod tests { fn the_baseline_is_version_100_and_later_versions_increase() { assert_eq!(MIGRATIONS[0].0, 100); assert_eq!(MIGRATIONS[1].0, 101); + assert_eq!(MIGRATIONS[2].0, 102); assert!(versions_start_at_baseline_and_increase(&MIGRATIONS)); assert!(versions_start_at_baseline_and_increase(&[ (100, ""), diff --git a/crates/registry-messaging/tests/migration_pins.rs b/crates/registry-messaging/tests/migration_pins.rs index 053714ad57..d464af39d9 100644 --- a/crates/registry-messaging/tests/migration_pins.rs +++ b/crates/registry-messaging/tests/migration_pins.rs @@ -17,6 +17,10 @@ const PINS: &[(&str, &str)] = &[ "0101_dispatch_lease_expiry.sql", "2a505e1bac1e306880409ddc67c0fb0a55a5ca65714b41875eda7ac176b9796d", ), + ( + "0102_activation_posture.sql", + "a18f643199189538139927ea61749ca829ba3868ff37cb054877deee8df1e475", + ), ]; #[test] diff --git a/crates/registry-messaging/tests/postgres_messages.rs b/crates/registry-messaging/tests/postgres_messages.rs index b8941c5f49..167dce0dc8 100644 --- a/crates/registry-messaging/tests/postgres_messages.rs +++ b/crates/registry-messaging/tests/postgres_messages.rs @@ -1333,9 +1333,9 @@ async fn the_runtime_is_ready_only_while_the_ledger_names_its_package_active() { .execute( "INSERT INTO messaging_activations \ (activation_id, apply_order, package_digest, predecessor_package_digest, \ - database_id, plan_kind, applied_at, role_mode) \ + database_id, plan_kind, applied_at, role_mode, posture) \ SELECT gen_random_uuid(), apply_order + 1, $1, package_digest, \ - database_id, 'successor', now(), role_mode \ + database_id, 'successor', now(), role_mode, posture \ FROM messaging_activations ORDER BY apply_order DESC LIMIT 1", &[&other], ) @@ -1356,9 +1356,9 @@ async fn readiness_rechecks_the_database_identity_recorded_after_startup() { .execute( "INSERT INTO messaging_activations \ (activation_id, apply_order, package_digest, predecessor_package_digest, \ - database_id, plan_kind, applied_at, role_mode) \ + database_id, plan_kind, applied_at, role_mode, posture) \ SELECT gen_random_uuid(), apply_order + 1, $1, package_digest, \ - 'another-deployment', 'successor', now(), role_mode \ + 'another-deployment', 'successor', now(), role_mode, posture \ FROM messaging_activations ORDER BY apply_order DESC LIMIT 1", &[&digest], ) diff --git a/crates/registry-messaging/tests/postgres_migrate.rs b/crates/registry-messaging/tests/postgres_migrate.rs index 23bcd9d4ce..aa1b1fdb3d 100644 --- a/crates/registry-messaging/tests/postgres_migrate.rs +++ b/crates/registry-messaging/tests/postgres_migrate.rs @@ -245,13 +245,13 @@ async fn concurrent_migrators_apply_each_version_once_and_both_succeed() { a.expect("the first concurrent migration"); b.expect("the second concurrent migration"); c.expect("the third concurrent migration"); - assert_eq!(applied_versions(&isolated).await, [100, 101]); + assert_eq!(applied_versions(&isolated).await, [100, 101, 102]); first .migrate() .await .expect("a repeated migration applies nothing"); - assert_eq!(applied_versions(&isolated).await, [100, 101]); + assert_eq!(applied_versions(&isolated).await, [100, 101, 102]); let runtime = PostgresStore::connect_runtime(&config, &secrets).expect("a runtime store"); runtime.ready().await.expect("a migrated store is ready"); @@ -362,7 +362,7 @@ async fn a_version_100_database_migrates_forward_keeps_its_queue_and_refuses_a_l ); store.migrate().await.expect("version 100 migrates forward"); - assert_eq!(applied_versions(&isolated).await, [100, 101]); + assert_eq!(applied_versions(&isolated).await, [100, 101, 102]); let queued = isolated .admin .query_one( @@ -433,9 +433,9 @@ async fn apply_migrates_a_version_100_database_forward_and_keeps_its_queue() { let applied = apply_activation(&config, &ApplyRequest::default()) .await .expect("messagingctl apply migrates version 100 forward"); - assert_eq!(applied.schema_versions_applied, [101]); + assert_eq!(applied.schema_versions_applied, [101, 102]); assert!(applied.recorded); - assert_eq!(applied_versions(&isolated).await, [100, 101]); + assert_eq!(applied_versions(&isolated).await, [100, 101, 102]); let queued = isolated .admin .query_one( diff --git a/crates/registry-messaging/tests/postgres_package.rs b/crates/registry-messaging/tests/postgres_package.rs index 0eacb11e67..ef3e1832df 100644 --- a/crates/registry-messaging/tests/postgres_package.rs +++ b/crates/registry-messaging/tests/postgres_package.rs @@ -485,7 +485,7 @@ async fn apply_refuses_a_newer_schema_before_activation_and_audits_the_refusal() .iter() .map(|row| row.get(0)) .collect(); - assert_eq!(versions, [100, 101, 199]); + assert_eq!(versions, [100, 101, 102, 199]); let operator_audit = match config .audit @@ -624,8 +624,8 @@ async fn apply_reports_the_active_digest_it_read_under_the_ledger_lock() { .batch_execute(&format!( "BEGIN; SELECT pg_advisory_xact_lock({LEDGER_LOCK_KEY}); \ INSERT INTO {}.messaging_activations \ - (activation_id,apply_order,package_digest,database_id,plan_kind,applied_at,role_mode) \ - VALUES (gen_random_uuid(),1,'{concurrent}','messaging-test','initial',now(),'single')", + (activation_id,apply_order,package_digest,database_id,plan_kind,applied_at,role_mode,posture) \ + VALUES (gen_random_uuid(),1,'{concurrent}','messaging-test','initial',now(),'single','production')", isolated.schema )) .await @@ -812,7 +812,7 @@ async fn split_role_activation_binds_identity_and_withholds_both_ledgers() { ) .await .expect("one transactional split-role activation"); - assert_eq!(applied.schema_versions_applied, [100, 101]); + assert_eq!(applied.schema_versions_applied, [100, 101, 102]); assert!(applied.recorded); assert_eq!(applied.activation.database_id, "messaging-test"); assert_eq!(applied.activation.role_mode.as_str(), "split"); diff --git a/crates/registry-platform-activation/Cargo.toml b/crates/registry-platform-activation/Cargo.toml index a616318915..b6cbc675dd 100644 --- a/crates/registry-platform-activation/Cargo.toml +++ b/crates/registry-platform-activation/Cargo.toml @@ -19,6 +19,7 @@ schema = ["dep:schemars"] [dependencies] schemars = { workspace = true, optional = true, features = ["chrono04", "uuid1"] } chrono = { workspace = true, features = ["serde"] } +registry-platform-posture.workspace = true serde.workspace = true thiserror.workspace = true tokio-postgres.workspace = true diff --git a/crates/registry-platform-activation/src/lib.rs b/crates/registry-platform-activation/src/lib.rs index acbf1a587e..e138a34a81 100644 --- a/crates/registry-platform-activation/src/lib.rs +++ b/crates/registry-platform-activation/src/lib.rs @@ -2,6 +2,7 @@ //! Shared PostgreSQL package activation ledger and runtime-role boundary. use chrono::{DateTime, Utc}; +use registry_platform_posture::Posture; use serde::Serialize; use tokio_postgres::GenericClient; use uuid::Uuid; @@ -12,7 +13,7 @@ pub const SINGLE_ROLE_STATEMENT: &str = const ACTIVATION_COLUMNS: &str = "activation_id,apply_order,package_digest,\ predecessor_package_digest,database_id,plan_kind,applied_at,\ - operator_reference_hash,backup_references,role_mode"; + operator_reference_hash,backup_references,role_mode,posture"; /// One trigger installed by a product migration and therefore allowed on a /// product-owned relation in split-role mode. @@ -189,6 +190,10 @@ pub struct Activation { pub operator_reference_hash: Option, pub backup_references: Vec, pub role_mode: RoleMode, + /// The posture the activating process declared. + #[serde(serialize_with = "serialize_posture")] + #[cfg_attr(feature = "schema", schemars(with = "String"))] + pub posture: Posture, /// Present for ledgers that retain the PostgreSQL runtime user. #[serde(skip_serializing_if = "Option::is_none")] pub runtime_role: Option, @@ -202,9 +207,48 @@ pub struct NewActivation<'a> { pub operator_reference_hash: Option<&'a str>, pub backup_references: &'a [String], pub role_mode: RoleMode, + pub posture: Posture, pub runtime_role: Option<&'a str>, } +impl<'a> NewActivation<'a> { + /// Builds a request that records the production posture. Callers that + /// do not yet declare a posture use this, and it is the only + /// constructor that picks one on their behalf. + #[must_use] + pub fn without_posture( + activation_id: Uuid, + package_digest: &'a str, + database_id: &'a str, + operator_reference_hash: Option<&'a str>, + backup_references: &'a [String], + role_mode: RoleMode, + runtime_role: Option<&'a str>, + ) -> Self { + Self { + activation_id, + package_digest, + database_id, + operator_reference_hash, + backup_references, + role_mode, + posture: Posture::Production, + runtime_role, + } + } +} + +fn parse_posture(value: &str) -> Result { + Posture::parse(value).ok_or(Error::Corrupt) +} + +fn serialize_posture( + posture: &Posture, + serializer: S, +) -> Result { + serializer.serialize_str(posture.as_str()) +} + /// How a configured deployment identity compares with the ledger. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -305,11 +349,11 @@ pub async fn active_activation( if !relation_exists(client, layout.ledger_relation).await? { return Ok(None); } - let columns = activation_columns(layout); + let columns = read_columns(layout); client .query_opt( &format!( - "SELECT {columns} FROM {} ORDER BY apply_order DESC LIMIT 1", + "SELECT {columns} FROM {} AS ledger_row ORDER BY apply_order DESC LIMIT 1", layout.ledger_relation ), &[], @@ -328,11 +372,11 @@ pub async fn activation_history( if !relation_exists(client, layout.ledger_relation).await? { return Ok(Vec::new()); } - let columns = activation_columns(layout); + let columns = read_columns(layout); client .query( &format!( - "SELECT {columns} FROM {} ORDER BY apply_order", + "SELECT {columns} FROM {} AS ledger_row ORDER BY apply_order", layout.ledger_relation ), &[], @@ -351,6 +395,18 @@ fn activation_columns(layout: &Layout) -> String { } } +/// The columns a read selects, in the order `activation_from_row` expects, from +/// a relation aliased `ledger_row`. A ledger that predates the `posture` +/// column has no such field, and its rows read as production. +fn read_columns(layout: &Layout) -> String { + let columns = activation_columns(layout); + columns.replacen( + ",posture", + ",COALESCE(to_jsonb(ledger_row) ->> 'posture','production') AS posture", + 1, + ) +} + fn activation_from_row(row: &tokio_postgres::Row, layout: &Layout) -> Result { Ok(Activation { activation_id: row.try_get(0)?, @@ -363,8 +419,9 @@ fn activation_from_row(row: &tokio_postgres::Row, layout: &Layout) -> Result, expected: &str) -> Databas } } -/// Verify the package and database identity a runtime must serve. +/// Verify the package and database identity a runtime must serve, and that +/// the ledger recorded the posture the process declares. +/// +/// A posture mismatch is a distinct error that carries both postures, so a +/// caller that only reports (such as `doctor`) can match it and continue. pub async fn check_active_package( client: &impl GenericClient, layout: &Layout, database_id: &str, package_digest: &str, + declared: Posture, ) -> Result { let active = active_activation(client, layout) .await? @@ -484,9 +548,33 @@ pub async fn check_active_package( candidate: package_digest.to_owned(), }); } + if active.posture != declared { + return Err(ActivePackageError::PostureMismatch { + recorded: active.posture, + declared, + }); + } Ok(active) } +/// [`check_active_package`] for callers that do not yet declare a posture: +/// it checks as production. +pub async fn check_active_package_without_posture( + client: &impl GenericClient, + layout: &Layout, + database_id: &str, + package_digest: &str, +) -> Result { + check_active_package( + client, + layout, + database_id, + package_digest, + Posture::Production, + ) + .await +} + #[derive(Debug, thiserror::Error)] pub enum ActivePackageError { #[error("no package is active")] @@ -495,6 +583,15 @@ pub enum ActivePackageError { DatabaseIdMismatch, #[error("package {candidate} is not active; the database serves {active}")] PackageNotActive { active: String, candidate: String }, + #[error( + "the database was activated in the {} posture and this process declares {}", + .recorded.as_str(), + .declared.as_str() + )] + PostureMismatch { + recorded: Posture, + declared: Posture, + }, #[error(transparent)] Activation(#[from] Error), } diff --git a/crates/registry-platform-activation/tests/postgres_activation.rs b/crates/registry-platform-activation/tests/postgres_activation.rs index 51450f557e..e0d6d85eda 100644 --- a/crates/registry-platform-activation/tests/postgres_activation.rs +++ b/crates/registry-platform-activation/tests/postgres_activation.rs @@ -6,6 +6,7 @@ use registry_platform_activation::{ observe_role, stray_authority, ActivePackageError, AuthorityCause, DatabaseIdCheck, Layout, NewActivation, PlanKind, RoleMode, }; +use registry_platform_posture::Posture; use tokio_postgres::NoTls; use uuid::Uuid; @@ -57,7 +58,8 @@ async fn ledger_identity_and_split_role_share_one_postgres_boundary() { applied_at timestamptz NOT NULL, operator_reference_hash text, backup_references text[] NOT NULL, - role_mode text NOT NULL CHECK(role_mode IN ('single','split')) + role_mode text NOT NULL CHECK(role_mode IN ('single','split')), + posture text NOT NULL CHECK(posture IN ('development','production')) );" )) .await @@ -90,6 +92,7 @@ async fn ledger_identity_and_split_role_share_one_postgres_boundary() { operator_reference_hash: None, backup_references: &[], role_mode: role.mode, + posture: Posture::Production, runtime_role: None, }, ) @@ -118,6 +121,7 @@ async fn ledger_identity_and_split_role_share_one_postgres_boundary() { &layout(), "fixture-database", "sha256:fixture", + Posture::Production, ) .await .expect("accept exact active package"); @@ -126,7 +130,8 @@ async fn ledger_identity_and_split_role_share_one_postgres_boundary() { &transaction, &layout(), "another-database", - "sha256:fixture" + "sha256:fixture", + Posture::Production ) .await, Err(ActivePackageError::DatabaseIdMismatch) @@ -612,3 +617,292 @@ async fn postgres_version_floor_precedes_missing_ledger_observation() { .expect("connection task") .expect("connection closes"); } + +const POSTURE_FIXTURE_LEDGER: &str = "CREATE TABLE fixture_schema_migrations( + version bigint PRIMARY KEY, + applied_at timestamptz NOT NULL DEFAULT now() + ); + CREATE TABLE fixture_activations( + activation_id uuid PRIMARY KEY, + apply_order bigint NOT NULL UNIQUE, + package_digest text NOT NULL, + predecessor_package_digest text, + database_id text NOT NULL, + plan_kind text NOT NULL CHECK(plan_kind IN ('initial','successor')), + applied_at timestamptz NOT NULL, + operator_reference_hash text, + backup_references text[] NOT NULL, + role_mode text NOT NULL CHECK(role_mode IN ('single','split')) + );"; + +/// The migration every product ledger applies to gain the column. +const POSTURE_MIGRATION: &str = + "ALTER TABLE fixture_activations ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); + ALTER TABLE fixture_activations ALTER COLUMN posture DROP DEFAULT;"; + +struct PostureFixture { + client: tokio_postgres::Client, + schema: String, + connection_task: tokio::task::JoinHandle>, +} + +impl PostureFixture { + async fn new(ledger_sql: &str) -> Self { + let (client, connection) = tokio_postgres::connect(&database_url(), NoTls) + .await + .expect("connect to disposable PostgreSQL"); + let connection_task = tokio::spawn(connection); + let schema = format!("posture_{}", Uuid::new_v4().simple()); + client + .batch_execute(&format!( + "CREATE SCHEMA {schema}; SET search_path TO {schema}; {ledger_sql}" + )) + .await + .expect("create posture fixture"); + Self { + client, + schema, + connection_task, + } + } + + async fn finish(self) { + self.client + .batch_execute(&format!( + "RESET search_path; DROP SCHEMA {} CASCADE;", + self.schema + )) + .await + .expect("remove posture fixture"); + drop(self.client); + self.connection_task + .await + .expect("join PostgreSQL connection") + .expect("PostgreSQL connection completes"); + } +} + +async fn append( + client: &tokio_postgres::Client, + posture: Posture, +) -> registry_platform_activation::Activation { + append_activation( + client, + &layout(), + &NewActivation { + activation_id: Uuid::new_v4(), + package_digest: "sha256:fixture", + database_id: "fixture-database", + operator_reference_hash: None, + backup_references: &[], + role_mode: RoleMode::Single, + posture, + runtime_role: None, + }, + ) + .await + .expect("append activation") +} + +#[tokio::test] +async fn append_activation_round_trips_the_posture() { + let fixture = + PostureFixture::new(&format!("{POSTURE_FIXTURE_LEDGER}{POSTURE_MIGRATION}")).await; + for posture in [Posture::Development, Posture::Production] { + let fresh = + PostureFixture::new(&format!("{POSTURE_FIXTURE_LEDGER}{POSTURE_MIGRATION}")).await; + let appended = append(&fresh.client, posture).await; + assert_eq!(appended.posture, posture); + let read = active_activation(&fresh.client, &layout()) + .await + .expect("read active") + .expect("one row"); + assert_eq!(read.posture, posture); + assert_eq!( + activation_history(&fresh.client, &layout()) + .await + .expect("history"), + vec![appended] + ); + fresh.finish().await; + } + fixture.finish().await; +} + +#[tokio::test] +async fn check_active_package_reports_a_posture_mismatch_in_both_directions() { + for (recorded, declared) in [ + (Posture::Production, Posture::Development), + (Posture::Development, Posture::Production), + ] { + let fixture = + PostureFixture::new(&format!("{POSTURE_FIXTURE_LEDGER}{POSTURE_MIGRATION}")).await; + append(&fixture.client, recorded).await; + let result = check_active_package( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + declared, + ) + .await; + match result { + Err(ActivePackageError::PostureMismatch { + recorded: seen, + declared: asked, + }) => { + assert_eq!((seen, asked), (recorded, declared)); + let message = ActivePackageError::PostureMismatch { + recorded: seen, + declared: asked, + } + .to_string(); + assert!(message.contains(recorded.as_str()) && message.contains(declared.as_str())); + } + other => panic!("expected a posture mismatch, got {other:?}"), + } + let matching = check_active_package( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + recorded, + ) + .await + .expect("matching posture is accepted"); + assert_eq!(matching.posture, recorded); + fixture.finish().await; + } +} + +#[tokio::test] +async fn the_transitional_check_and_constructor_behave_as_production() { + let fixture = + PostureFixture::new(&format!("{POSTURE_FIXTURE_LEDGER}{POSTURE_MIGRATION}")).await; + let request = NewActivation::without_posture( + Uuid::new_v4(), + "sha256:fixture", + "fixture-database", + None, + &[], + RoleMode::Single, + None, + ); + assert_eq!(request.posture, Posture::Production); + append_activation(&fixture.client, &layout(), &request) + .await + .expect("append"); + registry_platform_activation::check_active_package_without_posture( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + ) + .await + .expect("production row passes the transitional check"); + fixture.finish().await; +} + +#[tokio::test] +async fn a_row_from_before_the_migration_reads_production() { + let fixture = PostureFixture::new(POSTURE_FIXTURE_LEDGER).await; + fixture + .client + .batch_execute( + "INSERT INTO fixture_activations VALUES( + '00000000-0000-0000-0000-000000000001', 1, 'sha256:fixture', NULL, + 'fixture-database', 'initial', now(), NULL, '{}', 'single');", + ) + .await + .expect("insert a pre-migration row"); + fixture + .client + .batch_execute(POSTURE_MIGRATION) + .await + .expect("apply the posture migration"); + let read = active_activation(&fixture.client, &layout()) + .await + .expect("read active") + .expect("one row"); + assert_eq!(read.posture, Posture::Production); + check_active_package( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + Posture::Production, + ) + .await + .expect("a legacy row serves production"); + assert!(matches!( + check_active_package( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + Posture::Development, + ) + .await, + Err(ActivePackageError::PostureMismatch { + recorded: Posture::Production, + declared: Posture::Development + }) + )); + // The default is dropped, so an insert that names no posture fails. + let missing = fixture + .client + .batch_execute( + "INSERT INTO fixture_activations(activation_id, apply_order, package_digest, + database_id, plan_kind, applied_at, backup_references, role_mode) + VALUES(gen_random_uuid(), 2, 'sha256:x', 'd', 'successor', now(), '{}', 'single');", + ) + .await; + assert!(missing.is_err(), "the migration leaves no posture default"); + fixture.finish().await; +} + +#[tokio::test] +async fn an_unknown_recorded_posture_is_corrupt() { + let fixture = PostureFixture::new(POSTURE_FIXTURE_LEDGER).await; + fixture + .client + .batch_execute( + "ALTER TABLE fixture_activations ADD COLUMN posture text NOT NULL DEFAULT 'staging'; + INSERT INTO fixture_activations VALUES( + '00000000-0000-0000-0000-000000000001', 1, 'sha256:fixture', NULL, + 'fixture-database', 'initial', now(), NULL, '{}', 'single', 'staging');", + ) + .await + .expect("insert an unknown posture"); + assert!(matches!( + active_activation(&fixture.client, &layout()).await, + Err(registry_platform_activation::Error::Corrupt) + )); + fixture.finish().await; +} + +#[tokio::test] +async fn a_ledger_without_the_posture_column_reads_production() { + let fixture = PostureFixture::new(POSTURE_FIXTURE_LEDGER).await; + fixture + .client + .batch_execute( + "INSERT INTO fixture_activations VALUES( + '00000000-0000-0000-0000-000000000001', 1, 'sha256:fixture', NULL, + 'fixture-database', 'initial', now(), NULL, '{}', 'single');", + ) + .await + .expect("insert a pre-migration row"); + let read = active_activation(&fixture.client, &layout()) + .await + .expect("read active") + .expect("one row"); + assert_eq!(read.posture, Posture::Production); + let history = activation_history(&fixture.client, &layout()) + .await + .expect("read history"); + assert_eq!(history.len(), 1); + assert_eq!(history[0].posture, Posture::Production); + fixture.finish().await; +} diff --git a/crates/registry-platform-hooks/src/delivery/identity.rs b/crates/registry-platform-hooks/src/delivery/identity.rs index 7d7370fc83..3fe0f2a5a5 100644 --- a/crates/registry-platform-hooks/src/delivery/identity.rs +++ b/crates/registry-platform-hooks/src/delivery/identity.rs @@ -9,7 +9,7 @@ //! A runtime left running across an activation then stops delivering rather //! than serving work under a package that is no longer active. -use registry_platform_activation::{check_active_package, Layout}; +use registry_platform_activation::{check_active_package_without_posture, Layout}; use tokio_postgres::Transaction; use super::seams::DeliveryError; @@ -45,7 +45,7 @@ pub async fn verify_active_package( ) .await .map_err(|_| DeliveryError::Unavailable)?; - check_active_package(transaction, layout, database_id, package_digest) + check_active_package_without_posture(transaction, layout, database_id, package_digest) .await .map(drop) .map_err(|_| DeliveryError::Unavailable) diff --git a/crates/registry-scheduling/migrations/0201_activation_posture.sql b/crates/registry-scheduling/migrations/0201_activation_posture.sql new file mode 100644 index 0000000000..9081894fde --- /dev/null +++ b/crates/registry-scheduling/migrations/0201_activation_posture.sql @@ -0,0 +1,9 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- The activation ledger records the posture the activating process declared. +-- A row written before this column existed reads production: a database that +-- was never activated in development can never read as development. +ALTER TABLE scheduling_activations + ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); +ALTER TABLE scheduling_activations ALTER COLUMN posture DROP DEFAULT; diff --git a/crates/registry-scheduling/src/store.rs b/crates/registry-scheduling/src/store.rs index 180c5723f2..995165e30c 100644 --- a/crates/registry-scheduling/src/store.rs +++ b/crates/registry-scheduling/src/store.rs @@ -90,10 +90,12 @@ pub use resource_availability::{ResourceSupplyImpact, ResourceSupplyImpacts}; pub use source_busy::{resource_interval_is_available, BusyStoreError}; const SCHEDULING_MIGRATION: &str = include_str!("../migrations/0200_scheduling.sql"); +const ACTIVATION_POSTURE_MIGRATION: &str = + include_str!("../migrations/0201_activation_posture.sql"); /// Every schema version, in the order it is applied. The baseline is /// version [`BASELINE_SCHEMA_VERSION`], above every version an earlier /// release applied; each later migration takes the next number. -const SCHEMA_VERSIONS: [i64; 1] = [200]; +const SCHEMA_VERSIONS: [i64; 2] = [200, 201]; /// The baseline schema version. A ledger holding any version below it was /// left by an earlier pre-1.0 release, which this release refuses by name: /// version 100 is the v0.42.0 and v0.43.0 baseline, whose outbox and hook diff --git a/crates/registry-scheduling/src/store/activation.rs b/crates/registry-scheduling/src/store/activation.rs index 402dc8c577..636e0b1df0 100644 --- a/crates/registry-scheduling/src/store/activation.rs +++ b/crates/registry-scheduling/src/store/activation.rs @@ -20,12 +20,16 @@ use uuid::Uuid; use super::{ check_policy_publication, current_schema_in, lock_publication, mark_allocation_writer, publish_policy, refuse_combined_conflicts, refuse_pre_1_0_schema, PolicyPublication, - PostgresStore, StoreError, MIGRATION_LOCK_KEY, SCHEDULING_MIGRATION, SCHEMA_VERSIONS, + PostgresStore, StoreError, ACTIVATION_POSTURE_MIGRATION, MIGRATION_LOCK_KEY, + SCHEDULING_MIGRATION, SCHEMA_VERSIONS, }; /// Supported SQL in application order. Keep the version ledger and dispatcher /// aligned: adding a known version without its implementation must not compile. -const SUPPORTED_MIGRATIONS: [(i64, &str); SCHEMA_VERSIONS.len()] = [(200, SCHEDULING_MIGRATION)]; +const SUPPORTED_MIGRATIONS: [(i64, &str); SCHEMA_VERSIONS.len()] = [ + (200, SCHEDULING_MIGRATION), + (201, ACTIVATION_POSTURE_MIGRATION), +]; const _: () = { let mut index = 0; while index < SCHEMA_VERSIONS.len() { @@ -447,15 +451,15 @@ impl PostgresStore { let activation = platform_activation::append_activation( &*transaction, &activation_layout(), - &NewActivation { - activation_id: request.activation_id, - package_digest: request.package_digest, - database_id: request.database_id, - operator_reference_hash: request.operator_reference_hash, - backup_references: request.backup_references, + &NewActivation::without_posture( + request.activation_id, + request.package_digest, + request.database_id, + request.operator_reference_hash, + request.backup_references, role_mode, - runtime_role: Some(request.runtime_role), - }, + Some(request.runtime_role), + ), ) .await .map_err(platform_error)?; @@ -1026,7 +1030,7 @@ pub(super) async fn check_active_package_in( client: &impl GenericClient, expected: &ActivePackage<'_>, ) -> Result { - platform_activation::check_active_package( + platform_activation::check_active_package_without_posture( client, &activation_layout(), expected.database_id, @@ -1041,6 +1045,14 @@ pub(super) async fn check_active_package_in( platform_activation::ActivePackageError::PackageNotActive { active, candidate } => { StoreError::PackageNotActive { active, candidate } } + // Until this product declares a posture it checks as production, so a + // ledger recorded in development is not its active package. + platform_activation::ActivePackageError::PostureMismatch { recorded, .. } => { + StoreError::PackageNotActive { + active: format!("recorded in the {} posture", recorded.as_str()), + candidate: expected.package_digest.to_owned(), + } + } platform_activation::ActivePackageError::Activation(error) => platform_error(error), }) } @@ -1218,7 +1230,7 @@ mod tests { assert!(message.contains("pre-1.0 schema"), "{message}"); assert!(message.contains("fresh database"), "{message}"); } - for applied in [vec![], vec![200]] { + for applied in [vec![], vec![200], vec![200, 201]] { SchemaState { applied, pending: Vec::new(), @@ -1234,10 +1246,14 @@ mod tests { SchemaState::default(), SchemaState { applied: vec![], - pending: vec![200], + pending: vec![200, 201], }, SchemaState { applied: vec![200], + pending: vec![201], + }, + SchemaState { + applied: vec![200, 201], pending: vec![], }, ] { @@ -1256,11 +1272,11 @@ mod tests { }, SchemaState { applied: vec![], - pending: vec![201], + pending: vec![202], }, SchemaState { applied: vec![], - pending: vec![200, 201], + pending: vec![200, 201, 202], }, SchemaState { applied: vec![], diff --git a/crates/registry-scheduling/tests/migration_pins.rs b/crates/registry-scheduling/tests/migration_pins.rs index 6b99623283..69c747b3ce 100644 --- a/crates/registry-scheduling/tests/migration_pins.rs +++ b/crates/registry-scheduling/tests/migration_pins.rs @@ -8,10 +8,16 @@ use std::path::Path; use registry_platform_testing::assert_migration_pins; -const PINS: &[(&str, &str)] = &[( - "0200_scheduling.sql", - "0e488c27a47818f21455292f030940bccc6dd82878fd6fe5baeef7dddda84b6f", -)]; +const PINS: &[(&str, &str)] = &[ + ( + "0200_scheduling.sql", + "0e488c27a47818f21455292f030940bccc6dd82878fd6fe5baeef7dddda84b6f", + ), + ( + "0201_activation_posture.sql", + "70b15bade04de9c5a5cc1d1486a2307c3c8e619c9a1faa0d7dc201316803ac28", + ), +]; #[test] fn every_migration_file_is_pinned_by_its_digest() { diff --git a/crates/registry-scheduling/tests/postgres_commitments.rs b/crates/registry-scheduling/tests/postgres_commitments.rs index a9911a58ed..dceef8ee79 100644 --- a/crates/registry-scheduling/tests/postgres_commitments.rs +++ b/crates/registry-scheduling/tests/postgres_commitments.rs @@ -1916,15 +1916,15 @@ async fn hook_fixture_at(hook_url: &str) -> Fixture { registry_platform_activation::append_activation( &fx.admin, &activation_layout(), - ®istry_platform_activation::NewActivation { - activation_id: Uuid::new_v4(), - package_digest: PACKAGE_DIGEST, - database_id: DATABASE_ID, - operator_reference_hash: None, - backup_references: &[], - role_mode: RoleMode::Single, - runtime_role: Some("scheduling_test"), - }, + ®istry_platform_activation::NewActivation::without_posture( + Uuid::new_v4(), + PACKAGE_DIGEST, + DATABASE_ID, + None, + &[], + RoleMode::Single, + Some("scheduling_test"), + ), ) .await .expect("record the fixture activation"); @@ -2410,15 +2410,15 @@ async fn hook_delivery_is_refused_when_the_activation_record_names_another_datab registry_platform_activation::append_activation( &fx.admin, &activation_layout(), - ®istry_platform_activation::NewActivation { - activation_id: Uuid::new_v4(), - package_digest: PACKAGE_DIGEST, - database_id: "another-scheduling-database", - operator_reference_hash: None, - backup_references: &[], - role_mode: RoleMode::Single, - runtime_role: Some("scheduling_test"), - }, + ®istry_platform_activation::NewActivation::without_posture( + Uuid::new_v4(), + PACKAGE_DIGEST, + "another-scheduling-database", + None, + &[], + RoleMode::Single, + Some("scheduling_test"), + ), ) .await .expect("record an activation naming another database"); @@ -2461,16 +2461,15 @@ async fn hook_delivery_stops_once_the_activation_record_names_another_package() registry_platform_activation::append_activation( &fx.admin, &activation_layout(), - ®istry_platform_activation::NewActivation { - activation_id: Uuid::new_v4(), - package_digest: - "sha256:0000000000000000000000000000000000000000000000000000000000000002", - database_id: DATABASE_ID, - operator_reference_hash: None, - backup_references: &[], - role_mode: RoleMode::Single, - runtime_role: Some("scheduling_test"), - }, + ®istry_platform_activation::NewActivation::without_posture( + Uuid::new_v4(), + "sha256:0000000000000000000000000000000000000000000000000000000000000002", + DATABASE_ID, + None, + &[], + RoleMode::Single, + Some("scheduling_test"), + ), ) .await .expect("record a superseding activation"); @@ -5232,8 +5231,8 @@ async fn a_records_swap_checks_the_active_package_under_its_locks() { .execute( "INSERT INTO scheduling_activations(activation_id, apply_order, package_digest, \ predecessor_package_digest, database_id, plan_kind, applied_at, role_mode, \ - runtime_role) SELECT gen_random_uuid(), max(apply_order) + 1, $1, $2, \ - 'records-ledger', 'successor', now(), 'single', current_user \ + runtime_role, posture) SELECT gen_random_uuid(), max(apply_order) + 1, $1, $2, \ + 'records-ledger', 'successor', now(), 'single', current_user, 'production' \ FROM scheduling_activations", &[&second, &first], ) diff --git a/crates/registry-schedulingctl/tests/activation_postgres.rs b/crates/registry-schedulingctl/tests/activation_postgres.rs index d557442899..95f2baeaa4 100644 --- a/crates/registry-schedulingctl/tests/activation_postgres.rs +++ b/crates/registry-schedulingctl/tests/activation_postgres.rs @@ -398,7 +398,10 @@ async fn plan_on_an_empty_database_reports_the_initial_activation_and_writes_not assert!(report["activePackage"].is_null(), "{report}"); assert_eq!(report["databaseIdCheck"], "initial"); assert_eq!(report["schemaVersion"], 0); - assert_eq!(report["pendingSchemaVersions"], serde_json::json!([200])); + assert_eq!( + report["pendingSchemaVersions"], + serde_json::json!([200, 201]) + ); assert_eq!(report["policy"]["revisionAdvances"], true); assert_eq!(report["policy"]["revision"], 2); assert_eq!(report["retainedHookBindings"], "none-retained"); @@ -490,7 +493,10 @@ async fn apply_records_one_row_per_activation_and_a_previous_package_is_a_new_ro .as_str() .unwrap() .starts_with("single-role mode")); - assert_eq!(initial["schemaVersionsApplied"], serde_json::json!([200])); + assert_eq!( + initial["schemaVersionsApplied"], + serde_json::json!([200, 201]) + ); assert_eq!(initial["effects"]["schedulingIdAdopted"], true); assert_eq!(initial["effects"]["policyRevision"], 2); assert_eq!(initial["effects"]["policyRevisionAdvanced"], true); @@ -586,7 +592,7 @@ async fn apply_records_one_row_per_activation_and_a_previous_package_is_a_new_ro assert_eq!(history[2]["planKind"], "successor"); assert_eq!(history[0]["roleMode"], "single"); assert!(history[0]["runtimeRole"].is_string(), "{report}"); - assert_eq!(report["schemaVersion"], 200); + assert_eq!(report["schemaVersion"], 201); assert_eq!(report["roleMode"], "single"); assert!(report["roleModeStatement"].is_string()); deployment.drop().await; @@ -633,7 +639,10 @@ async fn successor_activation_checks_retained_hook_bindings_on_the_version_100_b ); let initial = apply(&initial_config).expect("the initial package activates"); - assert_eq!(initial["schemaVersionsApplied"], serde_json::json!([200])); + assert_eq!( + initial["schemaVersionsApplied"], + serde_json::json!([200, 201]) + ); assert_eq!(initial["applyOrder"], 1); let config = RuntimeConfig::load(&initial_config).expect("the runtime configuration loads"); @@ -1616,10 +1625,10 @@ async fn denied(client: &tokio_postgres::Client, statement: &str) -> bool { } const LEDGER_INSERT: &str = "INSERT INTO scheduling_activations(activation_id, apply_order, \ - package_digest, database_id, plan_kind, applied_at, role_mode, runtime_role) \ + package_digest, database_id, plan_kind, applied_at, role_mode, runtime_role, posture) \ VALUES(gen_random_uuid(), 99, \ 'sha256:0000000000000000000000000000000000000000000000000000000000000000', \ - 'scheduling-activation-test', 'initial', now(), 'split', 'intruder')"; + 'scheduling-activation-test', 'initial', now(), 'split', 'intruder', 'production')"; #[tokio::test] async fn a_runtime_role_that_can_write_the_ledger_is_refused_at_startup_until_apply_reissues_its_grants( diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index e57e3e46bc..d1e76235fd 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -560,7 +560,7 @@ Startup refuses when a runtime file change alters a live run's endpoint, client Restore the original binding, or investigate with `coordinator --runtime-config FILE --recovery-only`, which admits and dispatches nothing. Recovery-only still verifies the active package, database, schema, role, and custody, and its readiness remains false. -The service requires protected state schema version 6. +The service requires protected state schema version 7. An earlier layout is refused: `apply` reports `coordinator.command.schema-version`, and runtime state access, including `deployment-status`, fails closed as `coordinator.command.store-unavailable`. Apply does not adopt or rewrite an earlier layout, and there is no in-place state migration. Settle the retained work with its matching binary, then create a fresh namespace and database identity for this version, and keep the original keys, packages, and audit history until retention permits erasure. diff --git a/docs/site/src/content/docs/reference/api-stability.mdx b/docs/site/src/content/docs/reference/api-stability.mdx index 0548812463..c9e36a9f49 100644 --- a/docs/site/src/content/docs/reference/api-stability.mdx +++ b/docs/site/src/content/docs/reference/api-stability.mdx @@ -365,9 +365,9 @@ the package with the `v0.44.0` `bregctl test` and `bregctl package` and appointments, and BReg records in the previous database are not carried forward. Messaging keeps its baseline: `messagingctl apply` migrates a `v0.43.0` database forward in place. -Registry Coordinator's protected state schema version 6 is a fresh baseline in the same way. Each -earlier layout, version 5 and below, was replaced without conversion. `coordinatorctl apply` -creates the namespace at version 6 on a fresh database identity, and `apply` and startup refuse a +Registry Coordinator's protected state schema version 7 is a fresh baseline in the same way. Each +earlier layout, version 6 and below, was replaced without conversion. `coordinatorctl apply` +creates the namespace at version 7 on a fresh database identity, and `apply` and startup refuse a namespace at any other version (`apply` reports `coordinator.command.schema-version`). Settle the retained runs with the matching binary, then apply the current package to a fresh namespace and database identity, as [Deploy Registry Coordinator](../../operate/coordinator/#apply-and-start) diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index d677eb7b5f..04edd268d3 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- A migration adds a posture to the activation ledger. Every activation + records production until the runtime declares its posture, and the + activation objects in `caseworkctl` reports carry it as `posture`. + - Casework counts every refused request by the check that refused it, in `casework_request_refusals_total{check}` on the metrics listener, published at zero for every check. Each refusal writes one `request refused` line with diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index 42fd757488..225e9302a4 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- BREAKING: protected state schema version 7 records a posture with each + activation. Every activation records production until the runtime declares + its posture. Version 6 namespaces are refused; settle their Runs with the + matching binary, then apply this version to a fresh namespace and database + identity. + - Coordinator counts every refused caller by the check that refused it, in `coordinator_request_refusals_total{check}` on the metrics listener, and writes one `request refused` line with `failed_check` and the request's diff --git a/products/documents/CHANGELOG.md b/products/documents/CHANGELOG.md index 8fbb4e295e..636c9f2171 100644 --- a/products/documents/CHANGELOG.md +++ b/products/documents/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- A migration adds a posture to the activation ledger. Every activation + records production until the runtime declares its posture, and the + activation objects in `documentsctl` reports carry it as `posture`. + - `authentication.oidc.allowedClients` accepts the keyword `from-package`, which admits the requester clients of the package's access profiles, so the clients are written once, in the package. The member stays required, and an diff --git a/products/messaging/CHANGELOG.md b/products/messaging/CHANGELOG.md index 51e8323086..e2f23515b4 100644 --- a/products/messaging/CHANGELOG.md +++ b/products/messaging/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- A migration adds a posture to the activation ledger. Every activation + records production until the runtime declares its posture, and the + activation objects in `messagingctl` reports carry it as `posture`. + - Messaging counts every refused request by the check that refused it, in `messaging_request_refusals_total{check}` on the metrics listener, published at zero for every check. Each refusal writes one `request refused` line with diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index a10765bfa2..52d5b2c60f 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- The shared activation ledger records a posture with every activation. + `registry-platform-activation` adds `Activation.posture` and + `NewActivation.posture`, and `check_active_package` takes the declared + posture and answers `ActivePackageError::PostureMismatch { recorded, + declared }` when the active row records the other one. A row written + before the column existed reads as production. + `NewActivation::without_posture` and `check_active_package_without_posture` + record and check production, and every runtime uses them until it declares + its posture. + - Every runtime reads a secret file under one rule. A relative link that stays below `secretProviders.file.root` is followed, at most eight links deep. A file owned by root with mode `0440` or `0640` loads when the diff --git a/products/scheduling/CHANGELOG.md b/products/scheduling/CHANGELOG.md index 2c5a34e4c9..a458091ada 100644 --- a/products/scheduling/CHANGELOG.md +++ b/products/scheduling/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- A migration adds a posture to the activation ledger. Every activation + records production until the runtime declares its posture, and the + activation objects in `schedulingctl` reports carry it as `posture`. + - Add `schedulingctl provision`. From the two database URLs in the runtime file and an administrator URL (`--admin-url-file` or `--admin-url-env`, a role with `CREATEROLE` and `CREATEDB` on the same host and port, over verified From f0cb20ce848a171a96e93de3c2109db97ab4ac3c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 11:57:58 +0100 Subject: [PATCH 078/136] fix: point contracts and tests at the current secret and schema rules The Evidence security traceability names the secret-file tests where they now live. The Coordinator state schema test and README expect protected state version 7, and the Casework report schema includes the posture each activation records. Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/tests/support/state_schema.rs | 2 +- products/casework/contracts/cli/report.schema.json | 7 ++++++- products/coordinator/README.md | 2 +- .../evidence/contracts/security-test-traceability.yaml | 5 ++++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/registry-coordinator/tests/support/state_schema.rs b/crates/registry-coordinator/tests/support/state_schema.rs index c2e1d8bd23..68ff2cbf9c 100644 --- a/crates/registry-coordinator/tests/support/state_schema.rs +++ b/crates/registry-coordinator/tests/support/state_schema.rs @@ -51,7 +51,7 @@ async fn a_second_migration_changes_no_schema_object_or_protected_row() { assert_eq!(catalog(&h).await, before, "the second migration ran DDL"); assert_eq!(restored_current_job(&h, run).await, job); assert_eq!(restored_lease_identity(&h, run).await, identity); - assert_eq!(h.store.doctor().await.unwrap().schema_version, 6); + assert_eq!(h.store.doctor().await.unwrap().schema_version, 7); } #[tokio::test] diff --git a/products/casework/contracts/cli/report.schema.json b/products/casework/contracts/cli/report.schema.json index 3e3b7d853e..cfacbf04ea 100644 --- a/products/casework/contracts/cli/report.schema.json +++ b/products/casework/contracts/cli/report.schema.json @@ -90,6 +90,10 @@ "planKind": { "$ref": "#/$defs/PlanKind" }, + "posture": { + "description": "The posture the activating process declared.", + "type": "string" + }, "predecessorPackageDigest": { "anyOf": [ { @@ -121,7 +125,8 @@ "appliedAt", "operatorReferenceHash", "backupReferences", - "roleMode" + "roleMode", + "posture" ], "type": "object" }, diff --git a/products/coordinator/README.md b/products/coordinator/README.md index 463b259772..b83d08990d 100644 --- a/products/coordinator/README.md +++ b/products/coordinator/README.md @@ -11,7 +11,7 @@ installation, custody, activation, and recovery. Coordinator is one of the six products the Registry Stack 1.0 compatibility promise covers: the workflow model, run API, and `coordinator` client namespace. Before 1.0, use one source version's binaries, packages, configuration, and state layout together. The current protected state schema -is version 6, with no in-place migration from earlier layouts. +is version 7, with no in-place migration from earlier layouts. Build the Coordinator service, operator CLI, client, and client bindings from source using the [deployment guide](https://docs.registrystack.org/operate/coordinator/#install-and-package) and the client crate instructions. Release packaging includes the diff --git a/products/evidence/contracts/security-test-traceability.yaml b/products/evidence/contracts/security-test-traceability.yaml index 8c59723e9f..4e2d594b98 100644 --- a/products/evidence/contracts/security-test-traceability.yaml +++ b/products/evidence/contracts/security-test-traceability.yaml @@ -455,7 +455,10 @@ entries: - id: sec-secret-file-identity tests: - {file: crates/registry-platform-config/src/secrets.rs, name: file_secret_accepts_only_owner_read_and_optional_owner_write_modes} - - {file: crates/registry-platform-config/src/secrets.rs, name: file_secret_rejects_symlinks_and_non_regular_files} + - {file: crates/registry-platform-config/src/secrets_tests.rs, name: a_link_that_could_leave_the_root_is_refused_in_both_postures} + - {file: crates/registry-platform-config/src/secrets_tests.rs, name: a_link_to_a_directory_or_a_dangling_link_is_refused} + - {file: crates/registry-platform-config/src/secrets_tests.rs, name: a_directory_is_not_a_secret} + - {file: crates/registry-platform-config/src/secrets_tests.rs, name: a_fifo_is_refused_without_blocking} - {file: crates/registry-platform-config/src/secrets.rs, name: file_secret_rejects_every_name_for_a_hard_link} - {file: crates/registry-platform-config/src/secrets.rs, name: file_secret_read_is_bounded} - id: sec-transport-backend-and-single-attempt From 520736e76eeffb900d6b71e28c2cbebfdf2b1b11 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 12:27:21 +0100 Subject: [PATCH 079/136] feat(platform): refuse task authority from a development peer Task-grant status clients and grant assertion checks take a peer policy. Under the refusing policy, a status answer marked as coming from a development deployment, or an assertion carrying the development claim, is refused with its own code. Every runtime uses the transitional names, which refuse development peers, until it declares its own posture. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-breg/src/auth.rs | 2 +- crates/registry-breg/src/task_grant.rs | 2 +- crates/registry-breg/src/task_grant/config.rs | 2 +- crates/registry-evidence/src/auth.rs | 4 +- crates/registry-platform-oidc/Cargo.toml | 1 + crates/registry-platform-oidc/README.md | 8 + .../src/authorization_claims.rs | 171 +++++++++++++++++- crates/registry-platform-oidc/src/lib.rs | 2 +- .../registry-platform-oidc/src/task_grant.rs | 55 +++++- .../src/task_grant/config.rs | 54 ++++-- .../src/task_grant/tests.rs | 132 +++++++++++++- crates/registry-scheduling/src/auth.rs | 2 +- crates/registry-scheduling/src/runtime.rs | 2 +- crates/registry-scheduling/src/service.rs | 6 +- .../tests/postgres_commitments.rs | 2 +- products/platform/CHANGELOG.md | 17 ++ 17 files changed, 419 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 590318e1b8..d96dee5c42 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8051,6 +8051,7 @@ dependencies = [ "registry-platform-config", "registry-platform-crypto", "registry-platform-httputil", + "registry-platform-posture", "registry-platform-yaml", "reqwest 0.12.28", "schemars", diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index 30bd77e743..0919e1f7e6 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -373,7 +373,7 @@ impl RegistryAuthenticator { })?; if let Some(grant) = &grant { grant - .verify_context(&verified, &self.audience) + .verify_context_without_peer_policy(&verified, &self.audience) .map_err(|error| invalid_claims(grant_context_check(error)))?; task_grant_token_lifetime(verified.claims.iat, verified.claims.exp, now, self.leeway) .map_err(invalid_claims)?; diff --git a/crates/registry-breg/src/task_grant.rs b/crates/registry-breg/src/task_grant.rs index 34505e881a..774a688e12 100644 --- a/crates/registry-breg/src/task_grant.rs +++ b/crates/registry-breg/src/task_grant.rs @@ -163,7 +163,7 @@ impl TaskGrantStatusClient { token: Arc, trusted_roots: Option<&[u8]>, ) -> Result { - registry_platform_oidc::task_grant::TaskGrantStatusClient::new( + registry_platform_oidc::task_grant::TaskGrantStatusClient::new_without_peer_policy( source_issuer, resource, base, diff --git a/crates/registry-breg/src/task_grant/config.rs b/crates/registry-breg/src/task_grant/config.rs index 0f008f0f78..0fbc86c3b8 100644 --- a/crates/registry-breg/src/task_grant/config.rs +++ b/crates/registry-breg/src/task_grant/config.rs @@ -29,7 +29,7 @@ impl TaskGrantStatusRegistry { resource: &str, secrets: &SecretResolver, ) -> Result { - registry_platform_oidc::task_grant::TaskGrantStatusRegistry::activate( + registry_platform_oidc::task_grant::TaskGrantStatusRegistry::activate_without_peer_policy( &endpoints(configs), resource, secrets, diff --git a/crates/registry-evidence/src/auth.rs b/crates/registry-evidence/src/auth.rs index 3f01e8a082..00a08eeed2 100644 --- a/crates/registry-evidence/src/auth.rs +++ b/crates/registry-evidence/src/auth.rs @@ -631,7 +631,9 @@ impl Authenticator { } else { match exactly_matched_resource(verified.claims.aud.as_ref(), &self.resources) { Some(resource) => { - if let Err(error) = grant.verify_context(&verified, resource) { + if let Err(error) = + grant.verify_context_without_peer_policy(&verified, resource) + { task_grant = Err(match error { GrantContextError::MissingVerifiedClient | GrantContextError::InvalidVerifiedClient diff --git a/crates/registry-platform-oidc/Cargo.toml b/crates/registry-platform-oidc/Cargo.toml index 7502e97725..dd8b84d159 100644 --- a/crates/registry-platform-oidc/Cargo.toml +++ b/crates/registry-platform-oidc/Cargo.toml @@ -20,6 +20,7 @@ jsonwebtoken.workspace = true registry-platform-authcommon.workspace = true registry-platform-crypto = { workspace = true } registry-platform-httputil = { workspace = true } +registry-platform-posture.workspace = true registry-platform-config.workspace = true registry-platform-yaml.workspace = true uuid = { workspace = true, features = ["serde"] } diff --git a/crates/registry-platform-oidc/README.md b/crates/registry-platform-oidc/README.md index c16c245eee..dbaa742ee0 100644 --- a/crates/registry-platform-oidc/README.md +++ b/crates/registry-platform-oidc/README.md @@ -163,6 +163,14 @@ response ceiling. Products decide when the check precedes their effects and how failures map to their own API; the primitive owns no mutation or durable lifecycle state. +A runtime passes a `PeerPolicy` to the status client and to `GrantClaims::verify_context`. +Under `RefuseDevelopmentPeer`, a status answer whose `Registry-Posture` field is `development` +is refused as `TaskGrantError::DevelopmentPeer` (`platform.task-grant.development-peer`), and a +task assertion carrying the claim `registry_posture: development` is refused as +`GrantContextError::DevelopmentAssertion` (`platform.task-grant.development-assertion`). +Under `AcceptDevelopmentPeer` both are accepted. Any other value of `registry_posture` is a +malformed claim. The `*_without_peer_policy` forms behave as `RefuseDevelopmentPeer`. + ## Testing ```sh diff --git a/crates/registry-platform-oidc/src/authorization_claims.rs b/crates/registry-platform-oidc/src/authorization_claims.rs index 11c72e0ee3..513ae5d285 100644 --- a/crates/registry-platform-oidc/src/authorization_claims.rs +++ b/crates/registry-platform-oidc/src/authorization_claims.rs @@ -5,6 +5,7 @@ use std::collections::HashSet; use std::fmt; +use registry_platform_httputil::PeerPolicy; use serde::{Deserialize, Serialize}; use serde_json::Value; use thiserror::Error; @@ -27,6 +28,18 @@ const MAX_SCHEDULING_ACTIONS: usize = 32; /// obtained by token exchange does not carry it at all. pub const ASSERTION_ISSUER_CLAIM: &str = "registry_assertion_issuer"; +/// Optional claim by which an issuer in the development posture marks the +/// assertions it signs. Its only meaningful value is `development`. +/// +/// The issuer derives the value from its own posture, so a client cannot choose +/// it, and no first-party signer may declare it as one of its projected +/// attributes. +pub const POSTURE_CLAIM: &str = "registry_posture"; + +/// Machine-readable code for an assertion refused because it comes from a +/// development issuer. +pub const DEVELOPMENT_ASSERTION_CODE: &str = "platform.task-grant.development-assertion"; + const REGISTERED_OR_AUTHENTICATION_CLAIMS: &[&str] = &[ "iss", "sub", @@ -94,9 +107,9 @@ impl ClaimNames { || names .iter() .any(|name| REGISTERED_OR_AUTHENTICATION_CLAIMS.contains(&name.as_str())) - || names - .iter() - .any(|name| name.as_str() == ASSERTION_ISSUER_CLAIM) + || names.iter().any(|name| { + name.as_str() == ASSERTION_ISSUER_CLAIM || name.as_str() == POSTURE_CLAIM + }) || names.iter().collect::>().len() != names.len() { return Err(ClaimError::InvalidNames); @@ -333,6 +346,7 @@ pub struct GrantClaims { exp: u64, bounds: GrantBounds, approver: String, + development: bool, } impl GrantClaims { @@ -381,12 +395,26 @@ impl GrantClaims { &self.approver } + /// Whether the issuer marked this assertion as coming from the development posture. + #[must_use] + pub const fn is_development(&self) -> bool { + self.development + } + /// Bind immutable grant context to identities already selected by the verifier. + /// + /// Under [`PeerPolicy::RefuseDevelopmentPeer`] an assertion marked as coming from the + /// development posture is refused. Under [`PeerPolicy::AcceptDevelopmentPeer`] the mark + /// is not consulted. pub fn verify_context( &self, token: &VerifiedToken, verified_resource: &str, + peer: PeerPolicy, ) -> Result<(), GrantContextError> { + if self.development && peer == PeerPolicy::RefuseDevelopmentPeer { + return Err(GrantContextError::DevelopmentAssertion); + } let client = token .matched_client_id() .map_err(|_| GrantContextError::InvalidVerifiedClient)? @@ -399,6 +427,16 @@ impl GrantClaims { } Ok(()) } + + /// [`Self::verify_context`] under [`PeerPolicy::RefuseDevelopmentPeer`], for a caller + /// that has no runtime peer policy yet. + pub fn verify_context_without_peer_policy( + &self, + token: &VerifiedToken, + verified_resource: &str, + ) -> Result<(), GrantContextError> { + self.verify_context(token, verified_resource, PeerPolicy::RefuseDevelopmentPeer) + } } impl fmt::Debug for GrantClaims { @@ -414,6 +452,7 @@ impl fmt::Debug for GrantClaims { .field("exp", &self.exp) .field("bounds", &self.bounds) .field("approver", &"") + .field("development", &self.development) .finish() } } @@ -432,6 +471,7 @@ pub enum ClaimMember { GrantExpiration, GrantBounds, Approver, + Posture, } #[derive(Clone, Copy, Debug, Eq, Error, PartialEq)] @@ -467,6 +507,22 @@ pub enum GrantContextError { ClientMismatch, #[error("task grant resource does not match the verified resource")] ResourceMismatch, + #[error("task grant was issued in the development posture")] + DevelopmentAssertion, +} + +impl GrantContextError { + /// The machine-readable code of a refusal that has one. + #[must_use] + pub const fn code(self) -> Option<&'static str> { + match self { + Self::DevelopmentAssertion => Some(DEVELOPMENT_ASSERTION_CODE), + Self::MissingVerifiedClient + | Self::InvalidVerifiedClient + | Self::ClientMismatch + | Self::ResourceMismatch => None, + } + } } /// Extract the strict actor kind from a verified token. @@ -548,6 +604,11 @@ pub fn grant_claims( .map_err(|_| ClaimError::Malformed(ClaimMember::GrantBounds))?; bounds.validate()?; let approver = required_extra_string(claims, &names.approver, ClaimMember::Approver)?; + let development = match claims.extra.get(POSTURE_CLAIM) { + None => false, + Some(Value::String(value)) if value == registry_platform_posture::DEVELOPMENT => true, + Some(_) => return Err(ClaimError::Malformed(ClaimMember::Posture)), + }; Ok(Some(GrantClaims { principal, @@ -559,6 +620,7 @@ pub fn grant_claims( exp: grant_exp, bounds, approver, + development, })) } @@ -1261,9 +1323,12 @@ mod tests { matched_client: Some("azp:agent-client".to_owned()), scopes: Vec::new(), }; - assert_eq!(grant.verify_context(&token, "urn:registry:breg"), Ok(())); assert_eq!( - grant.verify_context(&token, "urn:registry:other"), + grant.verify_context_without_peer_policy(&token, "urn:registry:breg"), + Ok(()) + ); + assert_eq!( + grant.verify_context_without_peer_policy(&token, "urn:registry:other"), Err(GrantContextError::ResourceMismatch) ); @@ -1273,7 +1338,7 @@ mod tests { scopes: Vec::new(), }; assert_eq!( - grant.verify_context(&client_id_token, "urn:registry:breg"), + grant.verify_context_without_peer_policy(&client_id_token, "urn:registry:breg"), Ok(()) ); @@ -1283,7 +1348,7 @@ mod tests { scopes: Vec::new(), }; assert_eq!( - grant.verify_context(&missing, "urn:registry:breg"), + grant.verify_context_without_peer_policy(&missing, "urn:registry:breg"), Err(GrantContextError::MissingVerifiedClient) ); @@ -1293,11 +1358,101 @@ mod tests { scopes: Vec::new(), }; assert_eq!( - grant.verify_context(&malformed, "urn:registry:breg"), + grant.verify_context_without_peer_policy(&malformed, "urn:registry:breg"), Err(GrantContextError::InvalidVerifiedClient) ); } + fn posture_grant_and_token( + posture: Option, + ) -> Result<(GrantClaims, VerifiedToken), ClaimError> { + let mut extra = + complete_grant(json!({"type":"evidence","requirement":"urn:requirement:one"})); + if let Some(posture) = posture { + extra[POSTURE_CLAIM] = posture; + } + let input = claims(extra); + let grant = grant_claims(&input, &ClaimNames::default(), 1_500)?.expect("present"); + let token = VerifiedToken { + claims: input, + matched_client: Some("azp:agent-client".to_owned()), + scopes: Vec::new(), + }; + Ok((grant, token)) + } + + #[test] + fn the_peer_policy_decides_whether_a_development_assertion_is_accepted() { + use registry_platform_httputil::PeerPolicy::{ + AcceptDevelopmentPeer, RefuseDevelopmentPeer, + }; + let resource = "urn:registry:breg"; + let (ordinary, ordinary_token) = posture_grant_and_token(None).unwrap(); + let (development, development_token) = + posture_grant_and_token(Some(json!("development"))).unwrap(); + assert_eq!( + ordinary.verify_context(&ordinary_token, resource, RefuseDevelopmentPeer), + Ok(()) + ); + assert_eq!( + ordinary.verify_context(&ordinary_token, resource, AcceptDevelopmentPeer), + Ok(()) + ); + assert_eq!( + development.verify_context(&development_token, resource, RefuseDevelopmentPeer), + Err(GrantContextError::DevelopmentAssertion) + ); + assert_eq!( + development.verify_context(&development_token, resource, AcceptDevelopmentPeer), + Ok(()) + ); + assert_eq!( + development.verify_context_without_peer_policy(&development_token, resource), + Err(GrantContextError::DevelopmentAssertion) + ); + assert_eq!( + ordinary.verify_context_without_peer_policy(&ordinary_token, resource), + Ok(()) + ); + } + + #[test] + fn a_posture_claim_other_than_development_is_malformed() { + for value in [ + json!("production"), + json!("Development"), + json!(""), + json!(true), + json!(1), + json!(["development"]), + json!(null), + ] { + assert_eq!( + posture_grant_and_token(Some(value.clone())).map(|_| ()), + Err(ClaimError::Malformed(ClaimMember::Posture)), + "{value}" + ); + } + } + + #[test] + fn the_posture_claim_name_cannot_serve_another_role() { + let names = ClaimNames { + purpose: POSTURE_CLAIM.to_owned(), + ..ClaimNames::default() + }; + assert_eq!(names.validate(), Err(ClaimError::InvalidNames)); + } + + #[test] + fn the_development_assertion_refusal_has_its_own_code() { + assert_eq!( + GrantContextError::DevelopmentAssertion.code(), + Some("platform.task-grant.development-assertion") + ); + assert_eq!(GrantContextError::ClientMismatch.code(), None); + } + #[test] fn grant_debug_redacts_claim_values() { let input = claims(complete_grant( diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index d663eba17f..c2b682d4b8 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -16,7 +16,7 @@ pub use access_token_algorithm::AccessTokenAlgorithm; pub use authorization_claims::{ actor_kind, grant_claims, ActorKind, BregPermission, ClaimError, ClaimMember, ClaimNames, GrantBounds, GrantClaims, GrantContextError, MatchedClientError, SchedulingPermission, - ASSERTION_ISSUER_CLAIM, + ASSERTION_ISSUER_CLAIM, DEVELOPMENT_ASSERTION_CODE, POSTURE_CLAIM, }; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; diff --git a/crates/registry-platform-oidc/src/task_grant.rs b/crates/registry-platform-oidc/src/task_grant.rs index 8fcd3a67fe..1a6a851fe6 100644 --- a/crates/registry-platform-oidc/src/task_grant.rs +++ b/crates/registry-platform-oidc/src/task_grant.rs @@ -3,7 +3,7 @@ use crate::{GrantBounds, GrantClaims}; use registry_platform_httputil::{ client::{build_client, OutboundOptions, PrivateKeyJwt, ServiceBaseUrl, TokenProvider}, - read_bounded, validate_response_headers_without_peer_policy, + read_bounded, validate_response_headers, PeerPolicy, ResponseHeaderError, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -13,6 +13,10 @@ use uuid::Uuid; mod config; pub use config::{TaskGrantStatusEndpoint, TaskGrantStatusRegistry}; +/// Machine-readable code for a status answer refused because its peer declares +/// the development posture. +pub const DEVELOPMENT_PEER_CODE: &str = "platform.task-grant.development-peer"; + #[derive(Clone, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct TaskGrantStatusBinding { @@ -102,6 +106,19 @@ pub enum TaskGrantError { Unavailable, #[error("task authority status configuration is invalid")] Configuration, + #[error("task authority status peer declares the development posture")] + DevelopmentPeer, +} + +impl TaskGrantError { + /// The machine-readable code of a refusal that has one. + #[must_use] + pub const fn code(self) -> Option<&'static str> { + match self { + Self::DevelopmentPeer => Some(DEVELOPMENT_PEER_CODE), + Self::Refused | Self::Unavailable | Self::Configuration => None, + } + } } /// A status route appended to the service base's path, parsed from a template @@ -154,6 +171,7 @@ pub struct TaskGrantStatusClient { status_path: StatusPath, http: reqwest::Client, token: Arc, + peer_policy: PeerPolicy, } impl fmt::Debug for TaskGrantStatusClient { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -162,7 +180,9 @@ impl fmt::Debug for TaskGrantStatusClient { } impl TaskGrantStatusClient { /// `status_path` is the status route appended to `base`'s path: it starts - /// with `/` and has exactly one whole `{grantId}` segment. + /// with `/` and has exactly one whole `{grantId}` segment. `peer_policy` + /// decides whether a status answer from a development-posture peer is + /// accepted. pub fn new( source_issuer: String, resource: String, @@ -170,6 +190,7 @@ impl TaskGrantStatusClient { status_path: &str, token: Arc, trusted_roots: Option<&[u8]>, + peer_policy: PeerPolicy, ) -> Result { if !registry_platform_httputil::valid_resource_uri(&source_issuer) || !registry_platform_httputil::valid_resource_uri(&resource) @@ -192,8 +213,30 @@ impl TaskGrantStatusClient { status_path, http, token, + peer_policy, }) } + + /// [`Self::new`] under [`PeerPolicy::RefuseDevelopmentPeer`], for a caller + /// that has no runtime peer policy yet. + pub fn new_without_peer_policy( + source_issuer: String, + resource: String, + base: reqwest::Url, + status_path: &str, + token: Arc, + trusted_roots: Option<&[u8]>, + ) -> Result { + Self::new( + source_issuer, + resource, + base, + status_path, + token, + trusted_roots, + PeerPolicy::RefuseDevelopmentPeer, + ) + } } #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -236,8 +279,12 @@ impl TaskGrantStatusClient { .send() .await .map_err(|_| TaskGrantError::Unavailable)?; - validate_response_headers_without_peer_policy(response.headers()) - .map_err(|_| TaskGrantError::Unavailable)?; + validate_response_headers(response.headers(), self.peer_policy).map_err(|error| { + match error { + ResponseHeaderError::DevelopmentPeer => TaskGrantError::DevelopmentPeer, + _ => TaskGrantError::Unavailable, + } + })?; // A concealed or absent grant is a refusal. Rejected status-service // credentials do not establish inactive authority and remain unavailable. if response.status() == reqwest::StatusCode::NOT_FOUND { diff --git a/crates/registry-platform-oidc/src/task_grant/config.rs b/crates/registry-platform-oidc/src/task_grant/config.rs index 0f7eb0d9b8..bb0501ca76 100644 --- a/crates/registry-platform-oidc/src/task_grant/config.rs +++ b/crates/registry-platform-oidc/src/task_grant/config.rs @@ -3,6 +3,7 @@ use super::*; use registry_platform_config::{SecretReference, SecretResolver, TaskGrantStatusConfig}; use registry_platform_httputil::client::{validate_requested_scopes, PrivateKeyJwtConfig}; +use registry_platform_httputil::PeerPolicy; use registry_platform_yaml::{ExternalId, Url}; /// One operator-pinned status authority, as a runtime's `taskGrantStatus` @@ -109,10 +110,28 @@ impl TaskGrantStatusRegistry { Ok(()) } + /// [`Self::activate`] under [`PeerPolicy::RefuseDevelopmentPeer`], for a caller + /// that has no runtime peer policy yet. + pub fn activate_without_peer_policy( + configs: &[TaskGrantStatusEndpoint], + resource: &str, + secrets: &SecretResolver, + ) -> Result { + Self::activate( + configs, + resource, + secrets, + PeerPolicy::RefuseDevelopmentPeer, + ) + } + + /// `peer_policy` decides whether a status answer from a development-posture + /// peer is accepted. pub fn activate( configs: &[TaskGrantStatusEndpoint], resource: &str, secrets: &SecretResolver, + peer_policy: PeerPolicy, ) -> Result { Self::validate_configuration(configs, resource)?; let mut clients = BTreeMap::new(); @@ -155,6 +174,7 @@ impl TaskGrantStatusRegistry { &config.status_path, Arc::new(PrivateKeyJwt::new(token).map_err(|_| TaskGrantError::Configuration)?), ca.as_ref().map(|value| value.expose_secret()), + peer_policy, )?; if clients .insert(config.source_issuer.as_str().to_owned(), client) @@ -272,7 +292,7 @@ mod tests { let root = tempfile::tempdir().unwrap(); let secrets = SecretResolver::new([SecretProvider::File], root.path()).unwrap(); assert!( - TaskGrantStatusRegistry::activate( + TaskGrantStatusRegistry::activate_without_peer_policy( std::slice::from_ref(&config), "urn:resource:test", &secrets @@ -282,7 +302,7 @@ mod tests { ); for resource in ["", "not-an-absolute-resource"] { TaskGrantStatusRegistry::validate_configuration(&[], resource).unwrap(); - TaskGrantStatusRegistry::activate(&[], resource, &secrets).unwrap(); + TaskGrantStatusRegistry::activate_without_peer_policy(&[], resource, &secrets).unwrap(); assert!(TaskGrantStatusRegistry::validate_configuration( std::slice::from_ref(&config), resource @@ -339,7 +359,7 @@ mod tests { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); let secrets = SecretResolver::new([SecretProvider::File], root.path()).unwrap(); let config = endpoint(); - let status = TaskGrantStatusRegistry::activate( + let status = TaskGrantStatusRegistry::activate_without_peer_policy( std::slice::from_ref(&config), "urn:resource:test", &secrets, @@ -349,13 +369,16 @@ mod tests { assert!(!status.contains("https://other.test")); let mut urn_authority = config.clone(); urn_authority.source_issuer = ExternalId::new("urn:authority:source").unwrap(); - let urn_status = - TaskGrantStatusRegistry::activate(&[urn_authority], "urn:resource:test", &secrets) - .unwrap(); + let urn_status = TaskGrantStatusRegistry::activate_without_peer_policy( + &[urn_authority], + "urn:resource:test", + &secrets, + ) + .unwrap(); assert!(urn_status.contains("urn:authority:source")); let mut duplicate = config.clone(); duplicate.base_url = Url::new("https://other-authority.test").unwrap(); - assert!(TaskGrantStatusRegistry::activate( + assert!(TaskGrantStatusRegistry::activate_without_peer_policy( &[config.clone(), duplicate], "urn:resource:test", &secrets @@ -366,15 +389,22 @@ mod tests { let mut invalid = config.clone(); invalid.base_url = Url::new(url).unwrap(); assert!( - TaskGrantStatusRegistry::activate(&[invalid], "urn:resource:test", &secrets) - .is_err(), + TaskGrantStatusRegistry::activate_without_peer_policy( + &[invalid], + "urn:resource:test", + &secrets + ) + .is_err(), "{url}" ); } let mut invalid = config; invalid.status_resource = ExternalId::new("not-an-absolute-resource").unwrap(); - assert!( - TaskGrantStatusRegistry::activate(&[invalid], "urn:resource:test", &secrets).is_err() - ); + assert!(TaskGrantStatusRegistry::activate_without_peer_policy( + &[invalid], + "urn:resource:test", + &secrets + ) + .is_err()); } } diff --git a/crates/registry-platform-oidc/src/task_grant/tests.rs b/crates/registry-platform-oidc/src/task_grant/tests.rs index 2072248dfd..773c54e73c 100644 --- a/crates/registry-platform-oidc/src/task_grant/tests.rs +++ b/crates/registry-platform-oidc/src/task_grant/tests.rs @@ -25,6 +25,7 @@ struct StateData { client_assertion_audience: String, requested: Arc>>, status_paths: Arc>>, + status_posture: Arc>>, } async fn token( State(state): State, @@ -57,7 +58,7 @@ async fn status( State(state): State, uri: Uri, headers: HeaderMap, -) -> Result, axum::http::StatusCode> { +) -> Result<(HeaderMap, Json), axum::http::StatusCode> { assert_eq!( headers.get("authorization").unwrap(), "Bearer synthetic-status-service" @@ -75,7 +76,11 @@ async fn status( if code != axum::http::StatusCode::OK { return Err(code); } - Ok(Json(state.response.lock().unwrap().clone())) + let mut answer_headers = HeaderMap::new(); + if let Some(posture) = *state.status_posture.lock().unwrap() { + answer_headers.insert("registry-posture", posture.parse().unwrap()); + } + Ok((answer_headers, Json(state.response.lock().unwrap().clone()))) } fn binding() -> TaskGrantStatusBinding { serde_json::from_value(serde_json::json!({"grantId":Uuid::new_v4().to_string(),"sourceIssuer":"https://authority.test","principal":"agent","client":"agent-client","resource":"urn:resource:test","purpose":"review","bounds":{"type":"breg","permissions":[{"collection":"records","operations":["get","patch"]}]},"subjects":{"subject_reference":"synthetic-subject","active":true},"expiresAt":chrono::Utc::now().timestamp()+900})).unwrap() @@ -90,6 +95,7 @@ fn state(response: Value, client_assertion_audience: String) -> StateData { client_assertion_audience, requested: Arc::default(), status_paths: Arc::default(), + status_posture: Arc::default(), } } /// Writes an owner-only private JWK as `status-key` under `root`. @@ -152,8 +158,12 @@ async fn status_client_requests_the_configured_scope_resource_and_status_path() endpoint.status_path = "/authority/grants/{grantId}/state".into(); endpoint.status_scope = ExternalId::new("grants:read-status").unwrap(); endpoint.status_resource = ExternalId::new("urn:authority:status").unwrap(); - let client = - TaskGrantStatusRegistry::activate(&[endpoint], "urn:resource:test", &secrets).unwrap(); + let client = TaskGrantStatusRegistry::activate_without_peer_policy( + &[endpoint], + "urn:resource:test", + &secrets, + ) + .unwrap(); client.check(&binding).await.unwrap(); assert_eq!( *state.requested.lock().unwrap(), @@ -191,7 +201,12 @@ async fn activated_status_client_uses_the_configured_assertion_audience_and_chec let mut wrong = config.clone(); wrong.client_assertion_audience = registry_platform_yaml::ExternalId::new(format!("http://{address}/token")).unwrap(); - let wrong = TaskGrantStatusRegistry::activate(&[wrong], "urn:resource:test", &secrets).unwrap(); + let wrong = TaskGrantStatusRegistry::activate_without_peer_policy( + &[wrong], + "urn:resource:test", + &secrets, + ) + .unwrap(); assert_eq!( wrong.check(&binding).await, Err(TaskGrantError::Unavailable) @@ -199,8 +214,12 @@ async fn activated_status_client_uses_the_configured_assertion_audience_and_chec assert_eq!(state.rejected_token_calls.load(Ordering::SeqCst), 1); assert_eq!(state.status_calls.load(Ordering::SeqCst), 0); - let client = - TaskGrantStatusRegistry::activate(&[config], "urn:resource:test", &secrets).unwrap(); + let client = TaskGrantStatusRegistry::activate_without_peer_policy( + &[config], + "urn:resource:test", + &secrets, + ) + .unwrap(); client.check(&binding).await.unwrap(); *response.lock().unwrap() = serde_json::json!({"active":false}); assert_eq!(client.check(&binding).await, Err(TaskGrantError::Refused)); @@ -302,9 +321,12 @@ async fn fixed_bounds_without_disclosed_claims_still_require_exact_fresh_status( let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); let root = tempfile::tempdir().unwrap(); let secrets = status_key_secrets(root.path()); - let client = - TaskGrantStatusRegistry::activate(&[endpoint(&issuer)], "urn:resource:test", &secrets) - .unwrap(); + let client = TaskGrantStatusRegistry::activate_without_peer_policy( + &[endpoint(&issuer)], + "urn:resource:test", + &secrets, + ) + .unwrap(); client.check(&binding).await.unwrap(); let mut changed = serde_json::to_value(&binding).unwrap(); changed["subjects"] = serde_json::json!({"unexpected":"claim"}); @@ -368,3 +390,93 @@ fn the_shared_status_block_maps_onto_one_endpoint_member_for_member() { Some("secret:file/status-ca") ); } + +/// Serves an active status answer that declares `posture`, and returns the +/// registry activated under `peer` plus the server handle. +async fn registry_against_peer_declaring( + posture: &'static str, + peer: PeerPolicy, + transitional: bool, +) -> ( + TaskGrantStatusBinding, + TaskGrantStatusRegistry, + tokio::task::JoinHandle<()>, +) { + let binding = binding(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let state = state( + serde_json::json!({"active":true,"grant":binding}), + base.clone(), + ); + *state.status_posture.lock().unwrap() = Some(posture); + let app = Router::new() + .route("/token", post(token)) + .route("/v1/task-grants/{id}/status", get(status)) + .with_state(state); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let root = tempfile::tempdir().unwrap(); + let secrets = status_key_secrets(root.path()); + let registry = if transitional { + TaskGrantStatusRegistry::activate_without_peer_policy( + &[endpoint(&base)], + "urn:resource:test", + &secrets, + ) + } else { + TaskGrantStatusRegistry::activate(&[endpoint(&base)], "urn:resource:test", &secrets, peer) + } + .unwrap(); + (binding, registry, server) +} + +#[tokio::test] +async fn a_production_policy_refuses_a_status_answer_from_a_development_peer() { + let (binding, registry, server) = + registry_against_peer_declaring("development", PeerPolicy::RefuseDevelopmentPeer, false) + .await; + assert_eq!( + registry.check(&binding).await, + Err(TaskGrantError::DevelopmentPeer) + ); + server.abort(); +} + +#[tokio::test] +async fn a_development_policy_accepts_a_status_answer_from_a_development_peer() { + let (binding, registry, server) = + registry_against_peer_declaring("development", PeerPolicy::AcceptDevelopmentPeer, false) + .await; + registry.check(&binding).await.unwrap(); + server.abort(); +} + +#[tokio::test] +async fn the_transitional_activation_refuses_a_development_peer() { + let (binding, registry, server) = + registry_against_peer_declaring("development", PeerPolicy::AcceptDevelopmentPeer, true) + .await; + assert_eq!( + registry.check(&binding).await, + Err(TaskGrantError::DevelopmentPeer) + ); + server.abort(); +} + +#[tokio::test] +async fn a_production_policy_accepts_a_status_answer_declaring_production() { + let (binding, registry, server) = + registry_against_peer_declaring("production", PeerPolicy::RefuseDevelopmentPeer, false) + .await; + registry.check(&binding).await.unwrap(); + server.abort(); +} + +#[test] +fn the_development_peer_refusal_has_its_own_code() { + assert_eq!( + TaskGrantError::DevelopmentPeer.code(), + Some("platform.task-grant.development-peer") + ); + assert_eq!(TaskGrantError::Refused.code(), None); +} diff --git a/crates/registry-scheduling/src/auth.rs b/crates/registry-scheduling/src/auth.rs index 80e79d9d6b..9e083b82e3 100644 --- a/crates/registry-scheduling/src/auth.rs +++ b/crates/registry-scheduling/src/auth.rs @@ -285,7 +285,7 @@ impl SchedulingAuthenticator { })?; if let Some(grant) = &grant { grant - .verify_context(&verified, &self.audience) + .verify_context_without_peer_policy(&verified, &self.audience) .map_err(|_| AuthenticationError::Profile(FailedCheck::TaskGrantBinding))?; } let client = verified diff --git a/crates/registry-scheduling/src/runtime.rs b/crates/registry-scheduling/src/runtime.rs index 996115d9c8..2429eac657 100644 --- a/crates/registry-scheduling/src/runtime.rs +++ b/crates/registry-scheduling/src/runtime.rs @@ -274,7 +274,7 @@ pub async fn serve_from_path(path: impl AsRef) -> Result<(), RuntimeError> let task_grant_status = match &config.task_grant_status { Some(TaskGrantStatus::UncheckedFinalFifteenMinutes) => None, Some(TaskGrantStatus::Authorities(authorities)) => Some(Arc::new( - TaskGrantStatusRegistry::activate( + TaskGrantStatusRegistry::activate_without_peer_policy( &crate::config::task_grant_status_endpoints(authorities), &config.authentication.oidc.provider.audience, &secrets, diff --git a/crates/registry-scheduling/src/service.rs b/crates/registry-scheduling/src/service.rs index cec2e7f17e..b1a78b56dc 100644 --- a/crates/registry-scheduling/src/service.rs +++ b/crates/registry-scheduling/src/service.rs @@ -3099,7 +3099,9 @@ impl From> for GrantVerdict { match verdict { Ok(()) => Self::Current, Err(TaskGrantError::Refused) => Self::Refused, - Err(TaskGrantError::Unavailable) => Self::Unavailable, + // A development-posture status peer proves no grant state, so it is + // treated like an unreachable authority. + Err(TaskGrantError::Unavailable | TaskGrantError::DevelopmentPeer) => Self::Unavailable, Err(TaskGrantError::Configuration) => Self::Configuration, } } @@ -4891,7 +4893,7 @@ mod tests { "statusResource": "urn:casework:test" })) .expect("the status authority configuration"); - let registry = TaskGrantStatusRegistry::activate( + let registry = TaskGrantStatusRegistry::activate_without_peer_policy( &crate::config::task_grant_status_endpoints(&[status]), STATUS_RESOURCE, &secrets, diff --git a/crates/registry-scheduling/tests/postgres_commitments.rs b/crates/registry-scheduling/tests/postgres_commitments.rs index dceef8ee79..10626b2afd 100644 --- a/crates/registry-scheduling/tests/postgres_commitments.rs +++ b/crates/registry-scheduling/tests/postgres_commitments.rs @@ -581,7 +581,7 @@ async fn activated_task_status( "statusResource": "urn:casework:test" })) .expect("the status authority configuration"); - let registry = TaskGrantStatusRegistry::activate( + let registry = TaskGrantStatusRegistry::activate_without_peer_policy( &[TaskGrantStatusEndpoint::from(&status)], AUDIENCE, &secrets, diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index 52d5b2c60f..aaefa57895 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +- `registry-platform-oidc` can refuse task authority that comes from a + development peer. `TaskGrantStatusClient::new` and + `TaskGrantStatusRegistry::activate` take a `PeerPolicy`. Under + `RefuseDevelopmentPeer`, a status answer carrying + `Registry-Posture: development` is refused as + `TaskGrantError::DevelopmentPeer` (`platform.task-grant.development-peer`). + `GrantClaims` reads the optional `registry_posture` claim, whose only valid + value is `development`; any other value is malformed. + `GrantClaims::verify_context` takes a `PeerPolicy` and, under + `RefuseDevelopmentPeer`, refuses a development assertion as + `GrantContextError::DevelopmentAssertion` + (`platform.task-grant.development-assertion`). + `TaskGrantStatusClient::new_without_peer_policy`, + `TaskGrantStatusRegistry::activate_without_peer_policy` and + `GrantClaims::verify_context_without_peer_policy` refuse development + peers, and every runtime uses them until it declares its posture. + - The shared activation ledger records a posture with every activation. `registry-platform-activation` adds `Activation.posture` and `NewActivation.posture`, and `check_active_package` takes the declared From a0925c2b621141655cf19219963562744317b06b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 12:31:05 +0100 Subject: [PATCH 080/136] test(platform): assert the MCP edge refusal line whichever thread logs first The inbound refusal test captured the log line through a subscriber whose callsite interest depended on which test thread reached the callsite first, so it failed under parallel runs. It now uses the shared captured diagnostic logs, reaches the callsite from another thread first, and asserts exactly one refusal line. Signed-off-by: Jeremi Joslin --- .../src/compatibility_tests/inbound.rs | 74 ++++++------------- 1 file changed, 24 insertions(+), 50 deletions(-) diff --git a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs index 4a677391fc..b96548dd2b 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs @@ -1,10 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 -use std::{ - io::{self, Write}, - sync::{Arc, Mutex}, - time::Duration, -}; +use std::{sync::Arc, time::Duration}; use axum::{ body::Body, @@ -20,7 +16,7 @@ use registry_platform_oidc::{ access_token_typ_set, is_access_token_typ_pair, Claims, JwksFetcher, JwksFetcherConfig, OidcError, VerifiedToken, }; -use registry_platform_testing::{TestAuthorizationServer, TestClient}; +use registry_platform_testing::{CapturedDiagnosticLogs, TestAuthorizationServer, TestClient}; use serde_json::{json, Value}; use tower::ServiceExt; use url::Url; @@ -37,37 +33,6 @@ const CHAT_HOST: &str = "chat-host"; const SCOPE: &str = "address-correction:self"; const METADATA: &str = "https://gateway.example.test/.well-known/oauth-protected-resource/mcp"; -#[derive(Clone, Default)] -struct CapturedLogs(Arc>>); - -impl Write for CapturedLogs { - fn write(&mut self, bytes: &[u8]) -> io::Result { - self.0 - .lock() - .expect("log buffer lock") - .extend_from_slice(bytes); - Ok(bytes.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for CapturedLogs { - type Writer = Self; - - fn make_writer(&'writer self) -> Self::Writer { - self.clone() - } -} - -impl CapturedLogs { - fn text(&self) -> String { - String::from_utf8(self.0.lock().expect("log buffer lock").clone()).expect("UTF-8 logs") - } -} - fn now() -> i64 { i64::try_from( std::time::SystemTime::now() @@ -513,14 +478,9 @@ async fn every_refusal_is_a_problem_document() { #[tokio::test(flavor = "current_thread")] async fn an_unreachable_key_set_is_the_operators_failure() { - let logs = CapturedLogs::default(); - let subscriber = tracing_subscriber::fmt() - .json() - .without_time() - .with_max_level(tracing::Level::TRACE) - .with_writer(logs.clone()) - .finish(); - let _capture = tracing::subscriber::set_default(subscriber); + let logs = CapturedDiagnosticLogs::default(); + let _capture = + tracing::dispatcher::set_default(&logs.subscriber_with_max_level(tracing::Level::TRACE)); let auth = authorization_server().await; let token = auth.issue_access_token(CHAT_HOST, "citizen-a", RESOURCE, SCOPE, now() + 300); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") @@ -560,17 +520,31 @@ async fn an_unreachable_key_set_is_the_operators_failure() { let router = Router::new() .route("/mcp", post(|| async { "ok" })) .layer(axum::middleware::from_fn_with_state(server, require_caller)); - // A test on another thread can register the refusal line's callsite - // while no scoped subscriber exists, which caches it as never enabled. - // Rebuild the cache so this thread's subscriber is asked again. - tracing::callsite::rebuild_interest_cache(); + // Another test thread, with no subscriber of its own, may reach the + // refusal line first. A capture that is the only registered dispatcher + // then never sees that line, so this test reaches it first on purpose + // and relies on the shared capture to keep it enabled here. + let elsewhere = resource_server_for(&auth, 10, 10); + std::thread::spawn(move || { + assert_eq!( + elsewhere.refuse(Refusal::KeySource).status(), + StatusCode::SERVICE_UNAVAILABLE + ); + }) + .join() + .expect("a thread without a subscriber refuses"); assert_eq!( call(&router, Some(&token)).await.status(), StatusCode::SERVICE_UNAVAILABLE ); let logs = logs.text(); + let refusals: Vec<&str> = logs + .lines() + .filter(|line| line.contains("request refused")) + .collect(); + assert_eq!(refusals.len(), 1, "{logs}"); assert!( - logs.contains("\"failed_check\":\"key-source-unavailable\""), + refusals[0].contains("\"failed_check\":\"key-source-unavailable\""), "{logs}" ); assert!(!logs.contains("citizen-a"), "{logs}"); From 04d52917a2ca599b7ee3381dcceb0bd71403c8d1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 12:31:51 +0100 Subject: [PATCH 081/136] fix(identifiers): pin the current Casework report schema The catalog records the digest of the Casework command report schema, which now includes the posture each activation records. Signed-off-by: Jeremi Joslin --- products/identifiers/generated/catalog.v1.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 5eeaa72286..bead8cb53f 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5382,7 +5382,7 @@ }, "artifact": { "path": "products/casework/contracts/cli/report.schema.json", - "sha256": "b80fb562dbef1c9bdee11eb9466f5408ab7ba53ff925344e8ace47edd0ce537e", + "sha256": "0b19dbf18c681a79ad2f4bca44b0645c8ca0cd164d4d502a32b0c50fe22813c3", "mediaType": "application/schema+json" } }, From dfc5d2f7f36b1251b690acf8e025b887b36cbfd9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 13:05:20 +0100 Subject: [PATCH 082/136] feat(breg): let projects say common rules once and draft migrations Registry projects repeated the same row boundary lists in every grant, could not express month-based date rules, gave callers only a guard's reason code, and had to send a condition even for Actions that only patch the current row. - rowBoundarySets declares a named list of row boundaries once per project or module file; grants, targets and accessRequirements reference it and compile to the same package as the inline list. - A date guard can shift the registry-local date by whole calendar months with currentDateOffsetMonths, clamping to the last day of a shorter month and failing closed outside years 1 to 9999. - A commit guard with a reason can carry a constant display label, returned with the guard failure and in the availability response. - An immediate Action can declare execution with concurrency current-revision: BReg evaluates its guards against the Record it locks and patches that row, so the caller sends no condition. - bregctl migration draft writes the descriptor and rehearsal for a successor whose changes alter no table, column or index, bound to the verified baseline, and refuses when a change needs SQL. The authoring, runtime and tool schemas, the CLI catalog and the identifier catalog are regenerated. Signed-off-by: Jeremi Joslin --- crates/registry-breg-client/src/actions.rs | 7 + .../tests/write_http_boundary.rs | 29 +- crates/registry-breg/src/api/actions.rs | 17 +- .../src/api/actions/availability.rs | 47 ++ crates/registry-breg/src/api/proposals.rs | 2 +- crates/registry-breg/src/artifacts.rs | 1 + crates/registry-breg/src/commit_guard.rs | 122 +++- crates/registry-breg/src/contract.rs | 228 ++++++- crates/registry-breg/src/contract/sentinel.rs | 85 ++- crates/registry-breg/src/correlation.rs | 60 +- crates/registry-breg/src/fixtures.rs | 83 ++- crates/registry-breg/src/immediate_actions.rs | 154 ++++- crates/registry-breg/src/migration_plan.rs | 4 +- crates/registry-breg/src/model.rs | 24 + crates/registry-breg/src/mutation/action.rs | 4 +- crates/registry-breg/src/mutation/proposal.rs | 21 +- crates/registry-breg/src/postgres/mod.rs | 2 +- crates/registry-breg/src/postgres/schema.rs | 35 +- crates/registry-breg/src/proposal_hooks.rs | 2 +- crates/registry-breg/src/proposal_prepare.rs | 2 +- crates/registry-breg/src/proposal_workflow.rs | 2 + crates/registry-breg/src/rhai_planner.rs | 5 +- crates/registry-breg/src/startup.rs | 18 +- .../tests/artifacts_response_schema_tests.rs | 38 ++ .../registry-breg/tests/compiled_ddl_pins.rs | 4 +- .../registry-breg/tests/compiler_contract.rs | 1 + .../tests/immediate_action_compiler.rs | 44 ++ .../tests/immediate_action_requirements.rs | 367 +++++++++++ .../postgres_immediate_action_requirements.rs | 152 +++++ .../tests/postgres_immediate_actions.rs | 322 +++++++++ .../tests/postgres_proposal_guard_failure.rs | 94 ++- .../registry-breg/tests/refactor_contract.rs | 4 +- .../registry-breg/tests/row_boundary_sets.rs | 319 +++++++++ crates/registry-bregctl/src/explain_report.rs | 39 +- crates/registry-bregctl/src/lib.rs | 133 ++++ .../registry-bregctl/src/migration_draft.rs | 613 ++++++++++++++++++ .../src/reviewed_migrations.rs | 23 +- crates/registry-bregctl/src/test_lifecycle.rs | 7 +- crates/registry-bregctl/tests/cli.rs | 13 +- .../registry-bregctl/tests/migration_draft.rs | 341 ++++++++++ crates/registry-cli-docs/catalog.json | 90 +++ .../content/docs/configure/breg-access.mdx | 37 +- .../content/docs/configure/breg-actions.mdx | 81 ++- .../src/content/docs/operate/breg-changes.mdx | 42 +- docs/site/src/content/docs/security/breg.mdx | 33 + products/breg/CHANGELOG.md | 46 ++ .../contracts/security-invariant-matrix.yaml | 4 +- .../contracts/security-test-traceability.yaml | 4 + products/breg/examples/facility/registry.yaml | 54 +- .../breg/examples/formats/ctl-report.json | 6 +- .../formats/explain/actions-explanation.json | 2 +- .../formats/explain/model-explanation.json | 88 +-- .../breg/examples/formats/odrl-coverage.json | 2 +- .../authoring/registry-module.schema.json | 76 ++- .../authoring/registry-project.schema.json | 76 ++- ...facility.availability.response.schema.json | 2 +- .../generated/facility/generated/openapi.json | 2 +- ...ct-email.availability.response.schema.json | 2 +- .../generated/minimal/generated/openapi.json | 2 +- .../breg/scripts/test-adopter-workflow.sh | 66 +- .../breg/scripts/test_validate_product.py | 2 +- products/breg/scripts/validate_product.py | 2 +- .../identifiers/generated/catalog.v1.json | 8 +- 63 files changed, 3921 insertions(+), 274 deletions(-) create mode 100644 crates/registry-breg/tests/row_boundary_sets.rs create mode 100644 crates/registry-bregctl/src/migration_draft.rs create mode 100644 crates/registry-bregctl/tests/migration_draft.rs diff --git a/crates/registry-breg-client/src/actions.rs b/crates/registry-breg-client/src/actions.rs index f8e1c36078..a8f0923d1c 100644 --- a/crates/registry-breg-client/src/actions.rs +++ b/crates/registry-breg-client/src/actions.rs @@ -849,6 +849,7 @@ fn decode_availability( | "recovery" | "missingInputs" | "guardReason" + | "guardLabel" ) }) { return Err(BRegActionError::InvalidResponse); @@ -875,6 +876,9 @@ fn decode_availability( }; let reason = optional_string("reason")?; let guard_reason = optional_string("guardReason")?; + // An authored label rides only beside its reason. Like every refusal + // text it is bounded and never retained. + let guard_label = optional_string("guardLabel")?; let recovery = optional_string("recovery")?; let missing_inputs = availability .get("missingInputs") @@ -917,6 +921,9 @@ fn decode_availability( || guard_reason.as_deref().is_some_and(|reason| { available != Some(false) || !crate::error::valid_guard_reason(reason) }) + || guard_label.as_deref().is_some_and(|label| { + guard_reason.is_none() || !crate::error::bounded_refusal_label(label) + }) { return Err(BRegActionError::InvalidResponse); } diff --git a/crates/registry-breg-client/tests/write_http_boundary.rs b/crates/registry-breg-client/tests/write_http_boundary.rs index cc1f8cfc00..6ddc411f7f 100644 --- a/crates/registry-breg-client/tests/write_http_boundary.rs +++ b/crates/registry-breg-client/tests/write_http_boundary.rs @@ -2498,7 +2498,16 @@ async fn action_availability_is_metadata_bound_validated_and_sent_once() { json!({"availability":{"available":null,"observedRevision":7, "reason":"input-required","guardReason":"misplaced","recovery":"correct-input", "missingInputs":["legalName"]}}), + json!({"availability":{"available":false,"observedRevision":7, + "reason":"guard-not-satisfied","guardLabel":"A label without its reason.","recovery":"none"}}), + json!({"availability":{"available":false,"observedRevision":7, + "reason":"guard-not-satisfied","guardReason":"legal_name_unchanged", + "guardLabel":"é".repeat(257),"recovery":"none"}}), + json!({"availability":{"available":false,"observedRevision":7, + "reason":"guard-not-satisfied","guardReason":"legal_name_unchanged", + "guardLabel":"label\ncanary","recovery":"none"}}), ]; + let malformed_count = malformed.len(); let fixture = test_client( std::iter::once(MockResponse::json(StatusCode::OK, metadata)) .chain(std::iter::once(MockResponse::json( @@ -2515,6 +2524,14 @@ async fn action_availability_is_metadata_bound_validated_and_sent_once() { ) .with_header("cache-control", "no-store") .with_header("vary", "authorization, accept"))) + .chain(std::iter::once(MockResponse::json( + StatusCode::OK, + json!({"availability":{"available":false,"observedRevision":9, + "reason":"guard-not-satisfied","guardReason":"legal_name_unchanged", + "guardLabel":"The legal name cannot change here.","recovery":"none"}}), + ) + .with_header("cache-control", "no-store") + .with_header("vary", "authorization, accept"))) .chain(malformed.into_iter().map(|body| MockResponse::json(StatusCode::OK, body) .with_header("cache-control", "no-store") .with_header("vary", "authorization, accept"))) @@ -2568,7 +2585,17 @@ async fn action_availability_is_metadata_bound_validated_and_sent_once() { assert_eq!(unavailable.available(), Some(false)); assert_eq!(unavailable.observed_revision(), Some(8)); assert_eq!(unavailable.guard_reason(), Some("legal_name_unchanged")); - for _ in 0..6 { + // An authored guard label rides beside its reason. The client checks its + // bounds and, like every refusal text, does not retain it. + let labelled = fixture + .client + .action_availability(&action, &request) + .await + .unwrap() + .value; + assert_eq!(labelled.observed_revision(), Some(9)); + assert_eq!(labelled.guard_reason(), Some("legal_name_unchanged")); + for _ in 0..malformed_count { let error = fixture .client .action_availability(&action, &request) diff --git a/crates/registry-breg/src/api/actions.rs b/crates/registry-breg/src/api/actions.rs index a2eb88adb8..21815a5617 100644 --- a/crates/registry-breg/src/api/actions.rs +++ b/crates/registry-breg/src/api/actions.rs @@ -431,12 +431,17 @@ pub(super) async fn dispatch( ) .await { - Ok(availability::Availability::NotSatisfied { guard_reason, .. }) => { - crate::correlation::note_refusal( - crate::correlation::action_guard_failure_response(guard_reason), - FailedCheck::ActionGuard, - ) - } + Ok(availability::Availability::NotSatisfied { + guard_reason, + guard_label, + .. + }) => crate::correlation::note_refusal( + crate::correlation::action_guard_failure_response( + guard_reason, + guard_label, + ), + FailedCheck::ActionGuard, + ), // Visibility and the record may have changed since rollback. // Never turn the private cause into an existence oracle. _ => crate::correlation::note_refusal( diff --git a/crates/registry-breg/src/api/actions/availability.rs b/crates/registry-breg/src/api/actions/availability.rs index d65040b0d0..93eb72ffb1 100644 --- a/crates/registry-breg/src/api/actions/availability.rs +++ b/crates/registry-breg/src/api/actions/availability.rs @@ -14,6 +14,7 @@ pub(super) enum Availability { NotSatisfied { revision: u64, guard_reason: Option, + guard_label: Option, }, InputRequired { revision: u64, @@ -31,6 +32,7 @@ impl Availability { Self::NotSatisfied { revision, guard_reason, + guard_label, } => { let mut value = json!({ "available": false, "observedRevision": revision, @@ -38,6 +40,9 @@ impl Availability { }); if let Some(reason) = guard_reason { value["guardReason"] = json!(reason); + if let Some(label) = guard_label { + value["guardLabel"] = json!(label); + } } value } @@ -143,6 +148,7 @@ pub(super) async fn observe( return Ok(Availability::NotSatisfied { revision, guard_reason: guard.reason.clone(), + guard_label: guard.label.clone(), }); } } @@ -281,3 +287,44 @@ pub(in crate::api) async fn observe_target( } Ok(Some(ObservedTarget { revision, current })) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_satisfied_guard_label_rides_only_beside_its_reason() { + let labelled = Availability::NotSatisfied { + revision: 3, + guard_reason: Some("not-submitted".into()), + guard_label: Some("Only a submitted application can be approved.".into()), + }; + assert_eq!( + labelled.value(), + json!({ + "available": false, "observedRevision": 3, + "reason": "guard-not-satisfied", "recovery": "none", + "guardReason": "not-submitted", + "guardLabel": "Only a submitted application can be approved." + }) + ); + let unlabelled = Availability::NotSatisfied { + revision: 3, + guard_reason: Some("not-submitted".into()), + guard_label: None, + }; + assert!(unlabelled.value().get("guardLabel").is_none()); + let orphan = Availability::NotSatisfied { + revision: 3, + guard_reason: None, + guard_label: Some("A label without its reason.".into()), + }; + assert!(orphan.value().get("guardLabel").is_none()); + assert!(Availability::NotDisclosed + .value() + .as_object() + .unwrap() + .keys() + .all(|key| !key.starts_with("guard"))); + } +} diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index 072710c304..13c20a3a83 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -1245,7 +1245,7 @@ async fn guard_failure_response( ) { return mutation_problem(MutationError::PreconditionFailed); } - crate::correlation::action_guard_failure_response(guard.reason.clone()) + crate::correlation::action_guard_failure_response(guard.reason.clone(), guard.label.clone()) } /// Batch transport only: every item retains the scalar context read's current diff --git a/crates/registry-breg/src/artifacts.rs b/crates/registry-breg/src/artifacts.rs index 38b65afaf4..58fa0b6625 100644 --- a/crates/registry-breg/src/artifacts.rs +++ b/crates/registry-breg/src/artifacts.rs @@ -1046,6 +1046,7 @@ pub(crate) fn openapi_action_availability_response_schema(action: &CompiledActio "observedRevision": observed_revision, "reason": {"const": "guard-not-satisfied"}, "guardReason": {"type":"string","pattern":"^[a-z][a-z0-9_-]{0,63}$"}, + "guardLabel": {"type":"string","minLength":1,"maxLength":256}, "recovery": {"const": "none"}, }, }, diff --git a/crates/registry-breg/src/commit_guard.rs b/crates/registry-breg/src/commit_guard.rs index 5ee66e8da8..50382b033b 100644 --- a/crates/registry-breg/src/commit_guard.rs +++ b/crates/registry-breg/src/commit_guard.rs @@ -44,7 +44,12 @@ pub(crate) fn guard_matches( actual.as_i64().is_some_and(|actual| actual <= maximum) } (None, None, None, None, Some(relation), None, None) => { - let Some(today) = registry_today(registry, now, guard.current_date_offset_days) else { + let Some(today) = registry_today( + registry, + now, + guard.current_date_offset_days, + guard.current_date_offset_months, + ) else { return false; }; actual @@ -68,24 +73,18 @@ pub(crate) fn guard_matches( } /// The registry's calendar date at `now`, the "today" a `currentDate` guard -/// compares against. A date that cannot be resolved fails the guard closed. +/// compares against, shifted by whole days or whole calendar months. A date +/// that cannot be resolved fails the guard closed. fn registry_today( registry: &CompiledRegistry, now: time::OffsetDateTime, offset_days: i32, + offset_months: i32, ) -> Option { - // The same years 1 through 9999 the Rhai date helpers allow. let shifted = registry .local_date_at(now) .ok() - .and_then(|date| { - if offset_days >= 0 { - date.checked_add_days(chrono::Days::new(offset_days as u64)) - } else { - date.checked_sub_days(chrono::Days::new(u64::from(offset_days.unsigned_abs()))) - } - }) - .filter(|date| (1..=9999).contains(&chrono::Datelike::year(date))); + .and_then(|date| shift_date(date, offset_days, offset_months)); match shifted { Some(date) => Some(date), None => { @@ -94,6 +93,7 @@ fn registry_today( #[cfg(feature = "runtime")] tracing::error!( offset_days, + offset_months, "a currentDate guard could not resolve the registry's offset date and fails closed" ); None @@ -101,6 +101,26 @@ fn registry_today( } } +/// Shift a date by whole days, or by whole calendar months that clamp to the +/// last day of a shorter month, and keep it within the years 1 through 9999 +/// the Rhai date helpers allow. A compiled guard carries at most one nonzero +/// offset. +fn shift_date(date: chrono::NaiveDate, days: i32, months: i32) -> Option { + let shifted = if months >= 0 { + date.checked_add_months(chrono::Months::new(months.unsigned_abs())) + } else { + date.checked_sub_months(chrono::Months::new(months.unsigned_abs())) + }?; + let shifted = if days >= 0 { + shifted.checked_add_days(chrono::Days::new(u64::from(days.unsigned_abs()))) + } else { + shifted.checked_sub_days(chrono::Days::new(u64::from(days.unsigned_abs()))) + }?; + (1..=9999) + .contains(&chrono::Datelike::year(&shifted)) + .then_some(shifted) +} + /// Order a stored value against a submitted one. The compiler only pairs a /// field with an input of the same integer, date, or instant type, so the value /// shape tells the three apart: numbers are integers, strings are instants for a @@ -202,7 +222,9 @@ mod tests { at_least: None, at_most: None, current_date: None, + label: None, current_date_offset_days: 0, + current_date_offset_months: 0, at_least_input: None, at_most_input: None, } @@ -211,7 +233,7 @@ mod tests { #[test] fn the_offset_date_stays_within_years_1_to_9999() { let registry = registry(Some("UTC")); - let date = |now, offset| registry_today(®istry, now, offset); + let date = |now, offset| registry_today(®istry, now, offset, 0); assert_eq!( date(datetime!(9999-12-30 12:00 UTC), 1), chrono::NaiveDate::from_ymd_opt(9999, 12, 31) @@ -224,6 +246,82 @@ mod tests { assert_eq!(date(datetime!(0001-01-01 12:00 UTC), -1), None); } + #[test] + fn a_month_offset_clamps_to_the_last_day_of_a_shorter_month() { + let registry = registry(Some("UTC")); + let date = |now, months| registry_today(®istry, now, 0, months); + let ymd = |year, month, day| chrono::NaiveDate::from_ymd_opt(year, month, day); + // January 31 plus one month is February 28, or 29 in a leap year. + assert_eq!(date(datetime!(2026-01-31 12:00 UTC), 1), ymd(2026, 2, 28)); + assert_eq!(date(datetime!(2028-01-31 12:00 UTC), 1), ymd(2028, 2, 29)); + // March 31 minus one month is the last day of February. + assert_eq!(date(datetime!(2026-03-31 12:00 UTC), -1), ymd(2026, 2, 28)); + assert_eq!(date(datetime!(2028-03-31 12:00 UTC), -1), ymd(2028, 2, 29)); + // A shift across a year boundary changes the year. + assert_eq!(date(datetime!(2026-12-15 12:00 UTC), 1), ymd(2027, 1, 15)); + assert_eq!(date(datetime!(2026-01-15 12:00 UTC), -1), ymd(2025, 12, 15)); + assert_eq!(date(datetime!(2026-10-14 12:00 UTC), 0), ymd(2026, 10, 14)); + // A shift past year 9999 or before year 1 fails closed. + assert_eq!(date(datetime!(9999-12-15 12:00 UTC), 1), None); + assert_eq!(date(datetime!(9999-11-15 12:00 UTC), 1), ymd(9999, 12, 15)); + assert_eq!(date(datetime!(0001-01-15 12:00 UTC), -1), None); + } + + #[test] + fn the_guard_and_the_planner_helper_agree_on_month_arithmetic() { + let starts = [ + (2026, 1, 31), + (2028, 1, 31), + (2026, 3, 31), + (2028, 2, 29), + (2026, 12, 15), + (2026, 1, 1), + (2024, 2, 29), + (2026, 5, 31), + (2026, 10, 14), + (1, 1, 31), + (9999, 12, 31), + ]; + let months = [ + -25, -13, -12, -2, -1, 0, 1, 2, 12, 13, 24, 100, -100, 12_000, -12_000, + ]; + for (year, month, day) in starts { + let start = chrono::NaiveDate::from_ymd_opt(year, month, day).unwrap(); + for offset in months { + let guard = shift_date(start, 0, offset).map(|date| date.to_string()); + let planner = + crate::rhai_planner::add_months(start.to_string().into(), offset.into()) + .ok() + .map(|date| date.to_string()); + assert_eq!(guard, planner, "{start} plus {offset} months"); + } + } + } + + #[test] + fn a_current_date_guard_applies_its_signed_month_offset() { + let inputs = Map::new(); + let mut guard = guard(); + guard.current_date = Some(CompiledCurrentDateRelation::OnOrAfter); + guard.current_date_offset_months = 1; + let at = |stored: &str, now| { + guard_matches( + &guard, + &inputs, + json!({"value": stored}).as_object().unwrap(), + ®istry(Some("UTC")), + now, + false, + ) + }; + assert!(at("2026-02-28", datetime!(2026-01-31 12:00 UTC))); + assert!(!at("2026-02-27", datetime!(2026-01-31 12:00 UTC))); + assert!(at("2026-11-14", noon())); + assert!(!at("2026-11-13", noon())); + // An offset past year 9999 fails closed. + assert!(!at("9999-12-31", datetime!(9999-12-15 12:00 UTC))); + } + #[test] fn missing_values_and_ambiguous_predicates_fail_closed() { let mut guard = guard(); diff --git a/crates/registry-breg/src/contract.rs b/crates/registry-breg/src/contract.rs index 05695dc317..ba4beeea24 100644 --- a/crates/registry-breg/src/contract.rs +++ b/crates/registry-breg/src/contract.rs @@ -140,6 +140,17 @@ pub struct RegistryProject { schemars(schema_with = "local_id_map_schema::") )] pub value_types: BTreeMap, + /// Named lists of row boundaries, declared once and referenced as + /// `rowBoundaries: {rowBoundarySet: }` wherever a row reach is written + /// in this file. A reference expands to the set's boundaries when the file + /// is read, so each grant still states its own reach. A set holds at least + /// one boundary and is never `unrestricted`. + #[serde(default, skip_serializing, deserialize_with = "local_id_map")] + #[cfg_attr( + feature = "schema", + schemars(schema_with = "local_id_map_schema::") + )] + pub row_boundary_sets: BTreeMap, /// Written as a mapping from each function id to the rest of the function /// (CFG-ID-5) and held sorted by id. #[serde( @@ -426,8 +437,33 @@ pub struct ReviewAuthoritySource { // Authored once per bounded package, rather than allocated per Record. #[allow(clippy::large_enum_variant)] pub enum ActionExecutionSource { - Immediate {}, - Proposal { proposal: ProposalPolicySource }, + Immediate { + #[serde( + default, + skip_serializing_if = "ActionConcurrency::is_condition_required" + )] + concurrency: ActionConcurrency, + }, + Proposal { + proposal: ProposalPolicySource, + }, +} +/// How an immediate Action guards its patches against a concurrent write. +/// `condition-required` asks the caller to prove the revision it saw. +/// `current-revision` evaluates the Action's commit guards against the locked +/// current row instead, so the caller sends no condition. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ActionConcurrency { + #[default] + ConditionRequired, + CurrentRevision, +} +impl ActionConcurrency { + pub fn is_condition_required(&self) -> bool { + matches!(self, Self::ConditionRequired) + } } registry_platform_yaml::tagged_union!(ActionExecutionSource, tag = "mode"); serialize_tagged_union!(ActionExecutionSource, tag = "mode"); @@ -859,6 +895,117 @@ pub struct ProposalTargetPermissionSource { pub row_boundaries: Vec, } +/// A reusable list of row boundaries, written under `rowBoundarySets`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RowBoundarySetSource(pub Vec); + +impl<'de> Deserialize<'de> for RowBoundarySetSource { + fn deserialize>(deserializer: D) -> Result { + sentinel::row_boundary_set_rows(deserializer).map(Self) + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for RowBoundarySetSource { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + "RowBoundarySetSource".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + generator.subschema_for::, sentinel::RowBoundarySetRows>>() + } +} + +/// Replaces every `rowBoundaries: {rowBoundarySet: }` with the boundaries +/// the file's set lists, and reports whether it replaced any. A reference to a +/// set the file does not declare, or one that carries another member, is +/// refused: an empty list means every row, so no reference may fall through +/// to one. Sets are read before this runs, so each holds at least one +/// boundary. +fn resolve_row_boundary_sets(value: &mut Value) -> Result { + let sets = value + .get("rowBoundarySets") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + let Some(root) = value.as_object_mut() else { + return Ok(false); + }; + let mut replaced = false; + for (key, member) in root.iter_mut() { + if key == "rowBoundarySets" { + continue; + } + let pointer = format!("/{}", key.replace('~', "~0").replace('/', "~1")); + replaced |= resolve_row_boundary_set_references(member, &pointer, &sets)?; + } + Ok(replaced) +} + +fn resolve_row_boundary_set_references( + node: &mut Value, + pointer: &str, + sets: &serde_json::Map, +) -> Result { + let mut replaced = false; + match node { + Value::Object(members) => { + for (key, child) in members.iter_mut() { + let child_pointer = + format!("{pointer}/{}", key.replace('~', "~0").replace('/', "~1")); + let is_reference = key == "rowBoundaries" + && child + .as_object() + .is_some_and(|object| object.contains_key("rowBoundarySet")); + if !is_reference { + replaced |= resolve_row_boundary_set_references(child, &child_pointer, sets)?; + continue; + } + let site = format!("{child_pointer}/rowBoundarySet"); + let Some(object) = child.as_object().filter(|object| object.len() == 1) else { + return Err(( + site, + "a row boundary set reference is a mapping with only a rowBoundarySet member", + )); + }; + let Some(name) = object.get("rowBoundarySet").and_then(Value::as_str) else { + return Err(( + site, + "rowBoundarySet must be a local row boundary set identifier", + )); + }; + let Some(boundaries) = sets + .get(name) + .and_then(Value::as_array) + .filter(|boundaries| !boundaries.is_empty()) + else { + return Err(( + site, + "rowBoundarySet must name a row boundary set declared in this file", + )); + }; + *child = Value::Array(boundaries.clone()); + replaced = true; + } + } + Value::Array(items) => { + for (index, child) in items.iter_mut().enumerate() { + replaced |= resolve_row_boundary_set_references( + child, + &format!("{pointer}/{index}"), + sets, + )?; + } + } + _ => {} + } + Ok(replaced) +} + fn resolve_local_value_types(value: &mut Value) -> Result<(), (String, &'static str)> { let types = value .get("valueTypes") @@ -1728,6 +1875,17 @@ pub struct RegistryModule { schemars(schema_with = "local_id_map_schema::") )] pub value_types: BTreeMap, + /// Named lists of row boundaries, declared once and referenced as + /// `rowBoundaries: {rowBoundarySet: }` wherever a row reach is written + /// in this file. A reference expands to the set's boundaries when the file + /// is read, so each grant still states its own reach. A set holds at least + /// one boundary and is never `unrestricted`. + #[serde(default, skip_serializing, deserialize_with = "local_id_map")] + #[cfg_attr( + feature = "schema", + schemars(schema_with = "local_id_map_schema::") + )] + pub row_boundary_sets: BTreeMap, /// Written as a mapping from each function id to the rest of the function /// (CFG-ID-5) and held sorted by id. #[serde( @@ -2698,6 +2856,12 @@ impl ActionSource { pub fn is_proposal(&self) -> bool { matches!(self.execution, ActionExecutionSource::Proposal { .. }) } + pub fn concurrency(&self) -> ActionConcurrency { + match &self.execution { + ActionExecutionSource::Immediate { concurrency } => *concurrency, + ActionExecutionSource::Proposal { .. } => ActionConcurrency::ConditionRequired, + } + } } pub const ACTION_PLAN_ABI_V1: &str = "registry.action-plan/v1"; @@ -2792,6 +2956,21 @@ pub struct ActionRequirementSource { )] #[cfg_attr(feature = "schema", schemars(with = "Option"))] pub reason: Option, + /// Authored refusal text, a constant of at most 256 bytes that requires + /// `reason`. It is returned as the Problem `detail` and as the availability + /// `guardLabel` exactly where `reason` is returned, so it is disclosed only + /// when every guard and boundary fact is readable. It never replaces the + /// generic precondition refusal. + #[serde( + default, + deserialize_with = "registry_platform_yaml::optional_display_text", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr( + feature = "schema", + schemars(with = "Option") + )] + pub label: Option, #[serde(default)] pub field: String, #[serde( @@ -2827,6 +3006,14 @@ pub struct ActionRequirementSource { #[serde(default, skip_serializing_if = "crate::model::is_zero_i32")] #[cfg_attr(feature = "schema", schemars(range(min = -365000, max = 365000)))] pub current_date_offset_days: i32, + /// Whole calendar months added to the registry-local date before applying + /// `currentDate`, clamping to the last day of a shorter month (January 31 + /// plus one month is February 28 or 29). Requires `currentDate`, is + /// exclusive with `currentDateOffsetDays`, and zero preserves the + /// unshifted comparison. + #[serde(default, skip_serializing_if = "crate::model::is_zero_i32")] + #[cfg_attr(feature = "schema", schemars(range(min = -12000, max = 12000)))] + pub current_date_offset_months: i32, /// Requires the stored value to be at or above the named required action /// input of the same date, instant, or integer type. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -6398,21 +6585,42 @@ fn read_with_value_types( if !option_errors.is_empty() { return Err(document.report_with(option_errors)); } - if value.get("valueTypes").is_none() { - return document.decode().map(|value| Decoded { value, document }); + let has_value_types = value.get("valueTypes").is_some(); + let has_row_boundary_sets = value.get("rowBoundarySets").is_some(); + // Validate declarations at their authored sites before copying them into + // use sites. A bad named set or type must point to its declaration. + if value.get("rowBoundarySets").is_some() { + let _: BTreeMap = document.decode_at("/rowBoundarySets")?; } - // Validate declarations at their authored sites before copying constraints - // into use sites. A bad named type must point to its declaration. - let _: BTreeMap = document.decode_at("/valueTypes")?; - resolve_local_value_types(&mut value).map_err(|(path, message)| { + let resolved_sets = resolve_row_boundary_sets(&mut value).map_err(|(path, message)| { Report::new(vec![document.diagnostic_at_value( Severity::Error, - "breg.value-type.reference-invalid", + "breg.row-boundary-set.reference-invalid", &path, message, - "Name a declared value type and keep its constraints at that declaration.", + "Declare the set under rowBoundarySets in this file and reference it by its identifier, with no other member.", )]) })?; + if !has_value_types && !resolved_sets && !has_row_boundary_sets { + return document.decode().map(|value| Decoded { value, document }); + } + // Every reference is expanded, so the read file holds the boundaries + // inline and no set: it serializes to source that reads back the same. + if let Some(root) = value.as_object_mut() { + root.remove("rowBoundarySets"); + } + if has_value_types { + let _: BTreeMap = document.decode_at("/valueTypes")?; + resolve_local_value_types(&mut value).map_err(|(path, message)| { + Report::new(vec![document.diagnostic_at_value( + Severity::Error, + "breg.value-type.reference-invalid", + &path, + message, + "Name a declared value type and keep its constraints at that declaration.", + )]) + })?; + } let normalized = serde_json::to_vec(&value).expect("normalized authoring value serializes"); match read_authored::(file, &normalized, format) { Ok(decoded) => Ok(Decoded { diff --git a/crates/registry-breg/src/contract/sentinel.rs b/crates/registry-breg/src/contract/sentinel.rs index e06f906f69..b984d78c60 100644 --- a/crates/registry-breg/src/contract/sentinel.rs +++ b/crates/registry-breg/src/contract/sentinel.rs @@ -15,7 +15,7 @@ use std::convert::Infallible; use std::marker::PhantomData; -use registry_platform_yaml::{shape_union, Invalid}; +use registry_platform_yaml::{shape_union, Invalid, LocalId}; use serde::{de::IgnoredAny, Deserialize, Deserializer, Serialize, Serializer}; use super::{ @@ -167,8 +167,20 @@ pub(super) enum RequiredScopes { shape_union!(RequiredScopes { scalar => Unrestricted, list => Listed }); -/// The rows a permission reaches: the keyword `unrestricted`, or a list of at -/// least one row boundary. +/// A reference to a named list of row boundaries the file declares under +/// `rowBoundarySets`. The reader expands a reference into the set's boundaries +/// before the typed model is decoded, so the compiler never holds one. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(super) struct RowBoundarySetReference { + /// The identifier of a set declared under `rowBoundarySets` in the same file. + #[allow(dead_code)] + row_boundary_set: LocalId, +} + +/// The rows a permission reaches: the keyword `unrestricted`, a list of at +/// least one row boundary, or a reference to a named list of them. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schema", schemars(untagged))] pub(super) enum RowBoundaries { @@ -176,9 +188,19 @@ pub(super) enum RowBoundaries { Unrestricted(Unrestricted), /// Reach the rows every listed boundary binds to the caller's claims. Listed(Listed, Rows>), + /// Reach the rows every boundary of a named set binds to the caller's claims. + // The reader expands the reference before decoding, so the typed model + // only refuses it and never reads the identifier. + Reference(#[allow(dead_code)] RowBoundarySetReference), } -shape_union!(RowBoundaries { scalar => Unrestricted, list => Listed }); +shape_union!(RowBoundaries { scalar => Unrestricted, list => Listed, mapping => Reference }); + +/// What an unexpanded reference means to the typed model: nothing it may +/// read. An empty list means every row, so a reference that reaches typed +/// decoding is refused and never read as one. +const UNRESOLVED_REFERENCE: &str = "a row boundary set reference that the reader expanded"; +const UNRESOLVED_REFERENCE_ACTION: &str = "Declare the set under rowBoundarySets in the same file and read the file through the project reader."; /// The OAuth clients a runtime accepts tokens from. #[cfg(feature = "runtime")] @@ -238,11 +260,16 @@ pub(super) fn serialize_required_scopes( } impl RowBoundaries { - /// The boundaries the compiler holds, where `unrestricted` is none. - fn into_boundaries(self) -> Vec { + /// The boundaries the compiler holds, where `unrestricted` is none. An + /// unexpanded reference is refused rather than read as none. + fn into_boundaries(self) -> Result, Invalid> { match self { - Self::Unrestricted(_) => Vec::new(), - Self::Listed(Listed(boundaries, _)) => boundaries, + Self::Unrestricted(_) => Ok(Vec::new()), + Self::Listed(Listed(boundaries, _)) => Ok(boundaries), + Self::Reference(_) => Err(Invalid::expected( + UNRESOLVED_REFERENCE, + UNRESOLVED_REFERENCE_ACTION, + )), } } } @@ -250,7 +277,9 @@ impl RowBoundaries { pub(super) fn row_boundaries<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { - RowBoundaries::deserialize(deserializer).map(RowBoundaries::into_boundaries) + RowBoundaries::deserialize(deserializer)? + .into_boundaries() + .map_err(Invalid::into_error) } pub(super) fn serialize_row_boundaries( @@ -347,6 +376,37 @@ narrowing_member!( "Omit rowBoundaries when the entity demands no row boundary of its profiles; an access requirement only narrows what a profile may grant." ); +narrowing_member!( + RowBoundarySetRows, + RowBoundarySetRowsShapes, + row_boundary_set_rows, + Vec, + "a list of at least one row boundary", + "List the row boundaries the set holds. A set is a reusable list, so it is never empty and never unrestricted: write unrestricted on the grant that reaches every row." +); + +/// The schema of a record type's required row boundaries: a list of at least +/// one boundary, or a reference to a named set of them. +#[cfg(feature = "schema")] +struct RequirementRowBoundaries; + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for RequirementRowBoundaries { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + "RequirementRowBoundaries".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let listed = generator.subschema_for::, RequirementRows>>(); + let reference = generator.subschema_for::(); + schemars::json_schema!({"anyOf": [listed, reference]}) + } +} + // The authored form of `AccessRequirementsSource`. /// Compile-time requirements, not grants. Profiles must explicitly satisfy them. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -382,10 +442,7 @@ pub(super) struct AuthoredAccessRequirements { deserialize_with = "requirement_rows", skip_serializing_if = "Vec::is_empty" )] - #[cfg_attr( - feature = "schema", - schemars(with = "Listed, RequirementRows>") - )] + #[cfg_attr(feature = "schema", schemars(with = "RequirementRowBoundaries"))] row_boundaries: Vec, } @@ -750,7 +807,7 @@ impl TryFrom for EntityPermissionSource { required_filters: authored.required_filters, sortable_fields: authored.sortable_fields, spatial_queries: authored.spatial_queries, - row_boundaries: row_boundaries.into_boundaries(), + row_boundaries: row_boundaries.into_boundaries()?, membership_boundaries: authored.membership_boundaries, require_consent: authored.require_consent, lookups: authored.lookups, diff --git a/crates/registry-breg/src/correlation.rs b/crates/registry-breg/src/correlation.rs index c0da04c7ba..6a2ab004d4 100644 --- a/crates/registry-breg/src/correlation.rs +++ b/crates/registry-breg/src/correlation.rs @@ -115,6 +115,7 @@ pub(crate) struct PublicProblem { field_path: Option, declared_refusal: Option<(String, String)>, guard_reason: Option, + guard_label: Option, declared_field: Option<(String, String)>, declared_constraint: Option>, timer_window_fields: Option<(String, String)>, @@ -144,6 +145,7 @@ pub(crate) fn problem_response( field_path: None, declared_refusal: None, guard_reason: None, + guard_label: None, declared_field: None, declared_constraint: None, timer_window_fields: None, @@ -189,6 +191,7 @@ pub(crate) fn problem_response_with_field_path( field_path: Some(field_path.clone()), declared_refusal: None, guard_reason: None, + guard_label: None, declared_field: None, declared_constraint: None, timer_window_fields: None, @@ -243,8 +246,12 @@ pub(crate) fn action_refusal_response( response } -/// Called only after the ordinary guard and boundary disclosure recheck. -pub(crate) fn action_guard_failure_response(reason: Option) -> Response { +/// Called only after the ordinary guard and boundary disclosure recheck. The +/// authored label, when the guard has one, replaces the generic `detail`. +pub(crate) fn action_guard_failure_response( + reason: Option, + label: Option, +) -> Response { let code = crate::problem::ProblemCode::ActionGuardFailed; let mut response = problem_response( StatusCode::PRECONDITION_FAILED, @@ -252,11 +259,12 @@ pub(crate) fn action_guard_failure_response(reason: Option) -> Response code.description(), code.code(), ); - response + let problem = response .extensions_mut() .get_mut::() - .expect("problem metadata") - .guard_reason = reason; + .expect("problem metadata"); + problem.guard_reason = reason; + problem.guard_label = label; response } @@ -408,6 +416,11 @@ pub(crate) fn finish_response( } if let Some(reason) = &problem.guard_reason { object.insert("guardReason".to_owned(), Value::String(reason.clone())); + // A label is authored beside its reason, so it rides only where the + // reason does. + if let Some(label) = &problem.guard_label { + object.insert("detail".to_owned(), Value::String(label.clone())); + } } if let Some((name, value)) = problem.statistical_detail { object.insert(name.to_owned(), Value::String(value.to_owned())); @@ -606,4 +619,41 @@ mod refusal_guard_tests { )); assert_eq!(response.status(), StatusCode::NOT_FOUND); } + + async fn body_of(response: Response) -> Value { + let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) + .await + .expect("the problem body reads"); + serde_json::from_slice(&bytes).expect("the problem body is JSON") + } + + #[tokio::test] + async fn a_guard_label_replaces_the_detail_only_beside_its_reason() { + let label = "Only a submitted application can be approved."; + let labelled = body_of(finish(note_refusal( + action_guard_failure_response(Some("not-submitted".into()), Some(label.into())), + FailedCheck::ActionGuard, + ))) + .await; + assert_eq!(labelled["code"], "action.guard_failed"); + assert_eq!(labelled["guardReason"], "not-submitted"); + assert_eq!(labelled["detail"], label); + + let plain = body_of(finish(note_refusal( + action_guard_failure_response(Some("not-submitted".into()), None), + FailedCheck::ActionGuard, + ))) + .await; + assert_eq!(plain["detail"], "The action guard was not satisfied."); + + // A label never rides without the reason it is authored beside. + let orphan = body_of(finish(note_refusal( + action_guard_failure_response(None, Some(label.into())), + FailedCheck::ActionGuard, + ))) + .await; + assert_eq!(orphan["detail"], "The action guard was not satisfied."); + assert!(orphan.get("guardReason").is_none()); + assert!(!orphan.to_string().contains(label)); + } } diff --git a/crates/registry-breg/src/fixtures.rs b/crates/registry-breg/src/fixtures.rs index aeda7a7edf..e3ccf6429a 100644 --- a/crates/registry-breg/src/fixtures.rs +++ b/crates/registry-breg/src/fixtures.rs @@ -1106,6 +1106,9 @@ struct ValidatedStep { #[derive(Clone, Default)] struct FixtureProblemBindings { refusal_label: Option, + /// The `(reason, label)` pairs of the Action's guards, so a refusal may + /// carry a guard's authored label as its `detail`. + guard_labels: BTreeSet<(String, String)>, refusal_field_paths: BTreeSet, request_field_paths: BTreeSet, /// A record step's refusal may name one closed record location instead @@ -3034,6 +3037,15 @@ fn compile_problem_bindings( } } } + if expectation.problem_code.as_deref() == Some("action.guard_failed") { + if let Some(action) = action { + bindings.guard_labels = action + .requires + .iter() + .filter_map(|guard| Some((guard.reason.clone()?, guard.label.clone()?))) + .collect(); + } + } if matches!( expectation.problem_code.as_deref(), Some("action.refused" | "action.handler_failed" | "action.evidence_failed") @@ -4723,14 +4735,22 @@ fn assert_response_with_observations( ) } else if code == "action.guard_failed" && document.get("guardReason").is_some() { keys.push("guardReason"); - if document + let Some(reason) = document .get("guardReason") .and_then(Value::as_str) - .is_none_or(|reason| registry_platform_yaml::LocalId::new(reason).is_err()) - { + .filter(|reason| registry_platform_yaml::LocalId::new(*reason).is_ok()) + else { return Err(FixtureError::ResponseShapeRefused); - } - None + }; + // A guard that authors a label answers with it as the detail. + document + .get("detail") + .and_then(Value::as_str) + .filter(|detail| { + step.problem_bindings + .guard_labels + .contains(&(reason.to_owned(), (*detail).to_owned())) + }) } else if let Some((entity, field)) = &step.problem_bindings.pattern_field { keys.extend(["recordType", "fieldId"]); if document.get("recordType").and_then(Value::as_str) != Some(entity.as_str()) @@ -8615,6 +8635,59 @@ journeys: .expect("constraint journeys validate") } + #[test] + fn guard_failed_problem_accepts_a_bound_guard_label_as_its_detail() { + let suite = row_local_constraint_suite( + "jurisdiction, label, note, quantity, valid-from, valid-to", + "validFrom: 2, validTo: 1", + ); + let label = "Only an active parent takes a child."; + let mut guard_step = suite.journeys[0].steps[0].clone(); + guard_step.expect.status = 412; + guard_step.expect.problem_code = Some("action.guard_failed".to_owned()); + guard_step + .problem_bindings + .guard_labels + .insert(("parent-inactive".to_owned(), label.to_owned())); + let problem = |reason: &str, detail: &str| { + json!({ + "type": crate::problem::type_uri("action.guard_failed"), + "title": "Precondition Failed", + "status": 412, + "detail": detail, + "code": "action.guard_failed", + "traceId": "11111111111111111111111111111111", + "guardReason": reason + }) + }; + assert_response( + &guard_step, + StatusCode::PRECONDITION_FAILED, + &problem("parent-inactive", label), + ) + .expect("a bound label is the detail of the refusal that names its reason"); + assert_response( + &guard_step, + StatusCode::PRECONDITION_FAILED, + &problem("parent-inactive", "The action guard was not satisfied."), + ) + .expect("the generic detail stays admitted"); + for (reason, detail) in [ + ("other-reason", label), + ("parent-inactive", "Some other text."), + ] { + assert!( + assert_response( + &guard_step, + StatusCode::PRECONDITION_FAILED, + &problem(reason, detail), + ) + .is_err(), + "a detail that is no bound label for its reason is refused" + ); + } + } + #[test] fn guard_failed_problem_accepts_only_a_local_id_guard_reason() { let suite = row_local_constraint_suite( diff --git a/crates/registry-breg/src/immediate_actions.rs b/crates/registry-breg/src/immediate_actions.rs index fa628b7e3b..6e02a461c6 100644 --- a/crates/registry-breg/src/immediate_actions.rs +++ b/crates/registry-breg/src/immediate_actions.rs @@ -24,6 +24,9 @@ use crate::model::{ }; use crate::plan::{MAX_PLAN_FIELD_MUTATIONS, MAX_PLAN_SNAPSHOT_BYTES, MAX_PLAN_TARGETS}; +/// The longest authored guard label, matching the longest Function refusal label. +const MAXIMUM_GUARD_LABEL_BYTES: usize = 256; + type CompiledEffectSet = ( Vec, Vec, @@ -321,6 +324,15 @@ fn compile_action( } } let requires = compile_requirements(action, &input_map, entities, &target_uses, errors); + let concurrency = action.concurrency(); + if concurrency == crate::contract::ActionConcurrency::CurrentRevision { + validate_current_revision(action, &requires, &effects, handler.is_some(), errors); + // The caller proves no revision: the guards run against the locked + // current row instead, so no target use asks for a condition. + for use_ in &mut target_uses { + use_.condition_required = false; + } + } let attachments = compile_action_attachments(action, &inputs, entities, timer_actions, errors); let writes_path = if handler.is_some() { "actions[].plan.writes" @@ -378,6 +390,7 @@ fn compile_action( display: action.display.display(), grouping: action.display.grouping(), execution, + concurrency, definition_revision: String::new(), evidence: Vec::new(), commit_evidence, @@ -1083,6 +1096,25 @@ fn compile_requirements( if let Some(reason) = &requirement.reason { validate_id(reason, "actions[].commitGuards.targets[].reason", errors); } + if let Some(label) = &requirement.label { + if requirement.reason.is_none() { + errors.push(Diagnostic::error( + "breg.action.commit_guards.label-requires-reason", + "actions[].commitGuards.targets[].label", + "a guard label is the text of the refusal that names the guard's reason, so it requires a reason", + )); + } + if label.trim().is_empty() + || label.len() > MAXIMUM_GUARD_LABEL_BYTES + || label.chars().any(char::is_control) + { + errors.push(Diagnostic::error( + "breg.action.commit_guards.label-invalid", + "actions[].commitGuards.targets[].label", + "a guard label must be non-empty display text of at most 256 bytes without control characters", + )); + } + } if !seen.insert((&requirement.input, &requirement.field)) { errors.push(Diagnostic::error( "breg.action.commit_guards.targets-duplicate", @@ -1127,6 +1159,7 @@ fn compile_requirements( }); if !revision_is_bound || requirement.reason.is_some() + || requirement.label.is_some() || !requirement.field.is_empty() || requirement.equals.is_some() || requirement.equals_input.is_some() @@ -1135,6 +1168,7 @@ fn compile_requirements( || requirement.at_most.is_some() || requirement.current_date.is_some() || requirement.current_date_offset_days != 0 + || requirement.current_date_offset_months != 0 || requirement.at_least_from_input.is_some() || requirement.at_most_from_input.is_some() { @@ -1155,7 +1189,9 @@ fn compile_requirements( at_least: None, at_most: None, current_date: None, + label: None, current_date_offset_days: 0, + current_date_offset_months: 0, at_least_input: None, at_most_input: None, }); @@ -1200,6 +1236,18 @@ fn compile_requirements( )); continue; } + if requirement.current_date_offset_months != 0 + && (requirement.current_date.is_none() + || requirement.current_date_offset_days != 0 + || !(-12_000..=12_000).contains(&requirement.current_date_offset_months)) + { + errors.push(Diagnostic::error( + "breg.action.commit_guards.current-date-offset-invalid", + "actions[].commitGuards.targets[].currentDateOffsetMonths", + "currentDateOffsetMonths requires currentDate, cannot be combined with currentDateOffsetDays, and must be from -12000 through 12000 whole months", + )); + continue; + } let literal = requirement.literal(); let literal_invalid = literal.as_ref().is_some_and(|equals| { equals.is_array() @@ -1276,7 +1324,9 @@ fn compile_requirements( crate::model::CompiledCurrentDateRelation::OnOrBefore } }), + label: requirement.label.clone(), current_date_offset_days: requirement.current_date_offset_days, + current_date_offset_months: requirement.current_date_offset_months, at_least_input: requirement.at_least_from_input.clone(), at_most_input: requirement.at_most_from_input.clone(), }); @@ -1285,6 +1335,94 @@ fn compile_requirements( compiled } +/// The rules that make a write without a caller condition safe. A guard is +/// evaluated against the locked current row, so a second, stale write fails +/// exactly when the first write falsified a guard. Every record the Action +/// patches therefore needs a guard its own write makes false, and the write +/// may carry no value the caller chose, because a caller value read from a +/// stale view would silently overwrite a concurrent update. +fn validate_current_revision( + action: &ActionSource, + requires: &[CompiledCommitGuard], + effects: &[CompiledPlanEffect], + function_plan: bool, + errors: &mut Vec, +) { + if requires.iter().any(|guard| guard.revision_unchanged) { + errors.push(Diagnostic::error( + "breg.action.concurrency-revision-guard", + "actions[].commitGuards.targets[].revision", + &format!( + "Action `{}` uses concurrency: current-revision, which sends no condition, so it cannot require revision: unchanged", + action.id + ), + )); + } + // Final value each patched record's fields take, keyed by reference input. + let mut patched = BTreeMap::<&str, BTreeMap<&str, Option<&serde_json::Value>>>::new(); + for effect in effects { + let CompiledPlanTargetBinding::Existing { input } = &effect.target.binding else { + continue; + }; + if function_plan { + errors.push(Diagnostic::error( + "breg.action.concurrency-caller-value", + "actions[].plan", + &format!( + "Action `{}` uses concurrency: current-revision, and a function plan writes values computed from the caller's inputs into an existing record", + action.id + ), + )); + continue; + } + let fields = patched.entry(input.as_str()).or_default(); + for mutation in &effect.mutations { + match mutation { + CompiledPlanMutation::Set { + field, + value: CompiledPlanValue::Literal { value }, + } => { + fields.insert(field.as_str(), Some(value)); + } + CompiledPlanMutation::Clear { field } => { + fields.insert(field.as_str(), None); + } + CompiledPlanMutation::Set { field, .. } => errors.push(Diagnostic::error( + "breg.action.concurrency-caller-value", + "actions[].plan.effects[].set", + &format!( + "effect `{}` sets field `{field}` of an existing record from a caller value, which concurrency: current-revision does not allow. Set a constant with `value`, or use the default concurrency", + effect.id + ), + )), + } + } + } + for (input, fields) in patched { + let falsified = requires.iter().any(|guard| { + guard.input == input + && guard.equals_input.is_none() + && guard.equals.as_ref().is_some_and(|expected| { + match fields.get(guard.field.as_str()) { + Some(Some(value)) => *value != expected, + Some(None) => !expected.is_null(), + None => false, + } + }) + }); + if !falsified { + errors.push(Diagnostic::error( + "breg.action.concurrency-guard-missing", + "actions[].commitGuards.targets", + &format!( + "Action `{}` uses concurrency: current-revision and patches the record of input `{input}`, so it needs an `equals` or `isNull` guard on that input that its own write makes false", + action.id + ), + )); + } + } +} + fn compile_inputs( action: &ActionSource, entities: &BTreeMap, @@ -3338,6 +3476,9 @@ pub fn migration_review_revision(action: &CompiledAction) -> String { label.clear(); } } + for guard in &mut action.requires { + guard.label = None; + } if let crate::model::CompiledActionExecution::Proposal { proposal } = &mut action.execution { proposal .permissions @@ -3611,7 +3752,13 @@ pub(crate) fn definition_revision( Some((id,json!({"fields":fields,"constraints":target.constraints,"mutationMode":target.mutation_mode,"changeControl":target.change_control}))) }).collect::>(); let policy = match &action.execution { - crate::model::CompiledActionExecution::Immediate => json!({"mode":"immediate"}), + crate::model::CompiledActionExecution::Immediate => { + let mut policy = json!({"mode":"immediate"}); + if !action.concurrency.is_condition_required() { + policy["concurrency"] = json!(action.concurrency); + } + policy + } crate::model::CompiledActionExecution::Proposal { proposal } => { let mut policy = json!({"mode":"proposal","review":proposal.review,"application":proposal.application,"retention":proposal.retention,"reviewContext":proposal.review_context,"attachments":proposal.attachments}); // Promotions change what an approved Proposal writes, so they are @@ -3638,7 +3785,10 @@ pub(crate) fn definition_revision( value["refusals"] = json!(function.refusals.keys().collect::>()); value }); - let mut payload = json!({"id":action.id,"apiName":action.api_name,"inputs":inputs,"plan":{"effects":action.effects,"function":function},"commitGuards":{"targets":action.requires,"evidence":action.commit_evidence},"planEvidence":action.evidence,"targets":targets,"execution":policy,"consentIssuer":action.consent_issuer}); + // Guard labels are presentation copy, so rewording one leaves the Action's + // identity, and every Proposal frozen against it, unchanged. + let requires = crate::model::without_labels(&action.requires); + let mut payload = json!({"id":action.id,"apiName":action.api_name,"inputs":inputs,"plan":{"effects":action.effects,"function":function},"commitGuards":{"targets":requires,"evidence":action.commit_evidence},"planEvidence":action.evidence,"targets":targets,"execution":policy,"consentIssuer":action.consent_issuer}); // Request-file bindings decide which request part fills which record // slot, so they are part of the Action's identity. Omitting an empty map // keeps the revision of every Action without request files unchanged. diff --git a/crates/registry-breg/src/migration_plan.rs b/crates/registry-breg/src/migration_plan.rs index 56bc3c2b6e..ef0077bdf6 100644 --- a/crates/registry-breg/src/migration_plan.rs +++ b/crates/registry-breg/src/migration_plan.rs @@ -3249,8 +3249,10 @@ fn encryption_cover_matches_implicit_lookup_index( == cover.target.member_id.as_deref() } +/// Whether every cover names a change that alters no table, column, or index, +/// so a descriptor with no steps and no assertions can review it. #[cfg(feature = "tooling")] -fn covers_are_metadata_only(covers: &[ReviewedChangeCover]) -> bool { +pub fn covers_are_metadata_only(covers: &[ReviewedChangeCover]) -> bool { covers.iter().all(|cover| { matches!( cover.code, diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index fa4dfc4c68..60771d351c 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -492,6 +492,13 @@ pub struct CompiledAction { #[serde(default, skip_serializing_if = "Option::is_none")] pub grouping: Option, pub execution: CompiledActionExecution, + /// How an immediate Action guards its patches. Absent on every Action + /// that asks the caller for a condition. + #[serde( + default, + skip_serializing_if = "crate::contract::ActionConcurrency::is_condition_required" + )] + pub concurrency: crate::contract::ActionConcurrency, pub definition_revision: String, } @@ -637,6 +644,9 @@ pub struct CompiledCommitGuard { pub input: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option, + /// Authored text for the refusal that names `reason`. Presentation only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, #[serde(rename = "recordType")] pub entity_id: String, pub field: String, @@ -654,6 +664,8 @@ pub struct CompiledCommitGuard { pub current_date: Option, #[serde(default, skip_serializing_if = "is_zero_i32")] pub current_date_offset_days: i32, + #[serde(default, skip_serializing_if = "is_zero_i32")] + pub current_date_offset_months: i32, /// Keeps the stored field at or above the named action input. #[serde(default, skip_serializing_if = "Option::is_none")] pub at_least_input: Option, @@ -662,6 +674,18 @@ pub struct CompiledCommitGuard { pub at_most_input: Option, } +/// The guards without their authored labels. A label is presentation copy, so +/// a frozen Proposal binds and compares the guards without it. +pub(crate) fn without_labels(guards: &[CompiledCommitGuard]) -> Vec { + guards + .iter() + .map(|guard| CompiledCommitGuard { + label: None, + ..guard.clone() + }) + .collect() +} + impl CompiledCommitGuard { /// The action input this guard compares the stored field with, if any. pub fn compared_input(&self) -> Option<&str> { diff --git a/crates/registry-breg/src/mutation/action.rs b/crates/registry-breg/src/mutation/action.rs index d105ffb49c..4bca79cdc4 100644 --- a/crates/registry-breg/src/mutation/action.rs +++ b/crates/registry-breg/src/mutation/action.rs @@ -2636,7 +2636,9 @@ impl MutationTransaction { .await .map_err(map_database_error)?; let current = load_action_row(transaction, entity, &target_effects[0].2, true).await?; - if timer_authority.is_none() { + // A `current-revision` Action sends no condition: its commit guards + // were evaluated against this same locked row. + if timer_authority.is_none() && action.concurrency.is_condition_required() { for (input_id, effect, _) in &target_effects { let token = action_condition_token( self.audit.profile(), diff --git a/crates/registry-breg/src/mutation/proposal.rs b/crates/registry-breg/src/mutation/proposal.rs index a18ed843b8..3107d49bc1 100644 --- a/crates/registry-breg/src/mutation/proposal.rs +++ b/crates/registry-breg/src/mutation/proposal.rs @@ -2384,7 +2384,7 @@ impl MutationTransaction { Err(MutationError::PreconditionFailed) }; }; - if preconditions.contract != action.requires { + if preconditions.contract != crate::model::without_labels(&action.requires) { return Err(MutationError::PreconditionFailed); } preconditions.validate().map_err(workflow_error)?; @@ -2443,7 +2443,8 @@ impl MutationTransaction { Some(target.expected_revision), registry, trusted_now, - )?; + ) + .map_err(|error| restore_guard_label(error, action))?; } if let Some(fields) = crate::commit_evidence::target_fields(&preconditions.evidence).get(&target.id) @@ -4368,6 +4369,20 @@ fn verify_guard( } } +/// A frozen Proposal holds its guards without labels, so a refusal at Apply +/// takes the label from the Action as it is compiled now. +fn restore_guard_label(error: MutationError, action: &CompiledAction) -> MutationError { + let MutationError::ProposalGuardFailed(mut failure) = error else { + return error; + }; + failure.guard.label = action + .requires + .iter() + .find(|guard| guard.input == failure.guard.input && guard.field == failure.guard.field) + .and_then(|guard| guard.label.clone()); + MutationError::ProposalGuardFailed(failure) +} + fn proposal_read_fields(action: &CompiledAction, entity_id: &str) -> BTreeSet { action .target_uses @@ -4806,7 +4821,9 @@ mod commit_guard_date_tests { at_least: None, at_most: None, current_date: Some(crate::model::CompiledCurrentDateRelation::OnOrAfter), + label: None, current_date_offset_days: 0, + current_date_offset_months: 0, at_least_input: None, at_most_input: None, }; diff --git a/crates/registry-breg/src/postgres/mod.rs b/crates/registry-breg/src/postgres/mod.rs index dad73109de..b55ce3d595 100644 --- a/crates/registry-breg/src/postgres/mod.rs +++ b/crates/registry-breg/src/postgres/mod.rs @@ -238,7 +238,7 @@ pub(crate) use schema::verify_postgres_17_or_newer; pub(crate) use schema::PreparedSchemaTestCatalogVerifier; #[cfg(all(feature = "runtime", feature = "tooling"))] pub use schema::{ - prepare_schema_test_database_with_connections, PreparedSchemaTestDatabase, + prepare_schema_test_database_with_connections, PreparedSchemaTestDatabase, SchemaMeasurement, SchemaTestDatabaseIdentity, }; #[cfg(all(feature = "runtime", feature = "tooling"))] diff --git a/crates/registry-breg/src/postgres/schema.rs b/crates/registry-breg/src/postgres/schema.rs index 77b2d39321..53c13f5733 100644 --- a/crates/registry-breg/src/postgres/schema.rs +++ b/crates/registry-breg/src/postgres/schema.rs @@ -933,22 +933,32 @@ pub async fn prepare_schema_test_database_with_connections( }) } +/// What a fresh install of one compiled Registry measures on a disposable +/// database: the managed schema fingerprint and the server's PostgreSQL major +/// version. +#[cfg(all(feature = "runtime", feature = "tooling"))] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SchemaMeasurement { + pub fingerprint: String, + pub postgres_major: u16, +} + /// Install one compiled Registry into an empty disposable database transaction, /// verify the exact managed catalog, roll the transaction back, and return only -/// its schema fingerprint. This is a measurement path only: it never writes -/// active package identity and it never returns a pool, client, database id, -/// role, URL, or SQL. +/// its schema fingerprint and the server's PostgreSQL major version. This is a +/// measurement path only: it never writes active package identity and it never +/// returns a pool, client, database id, role, URL, or SQL. #[cfg(all(feature = "runtime", feature = "tooling"))] pub(crate) async fn rehearse_schema_fingerprint_with_connection( migration_connection: &ConnectionConfig, migration_role: &SqlIdentifier, runtime_role: &SqlIdentifier, registry: &CompiledRegistry, -) -> std::result::Result { +) -> 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 { + let migration_result: Result = async { verify_migration_role(&migration, migration_role).await?; let transaction = migration.transaction().await?; transaction @@ -959,8 +969,21 @@ pub(crate) async fn rehearse_schema_fingerprint_with_connection( let expected_catalog = ExpectedManagedCatalog::compiled(registry); let fingerprint = managed_schema_fingerprint(&transaction, runtime_role, &expected_catalog).await?; + let version: i32 = transaction + .query_one( + "SELECT current_setting('server_version_num')::integer / 10000", + &[], + ) + .await? + .get(0); + let postgres_major = u16::try_from(version).map_err(|_| { + PostgresKernelError::Configuration("the PostgreSQL major version is out of range") + })?; transaction.rollback().await?; - Ok(fingerprint) + Ok(SchemaMeasurement { + fingerprint, + postgres_major, + }) } .await; migration_task.abort(); diff --git a/crates/registry-breg/src/proposal_hooks.rs b/crates/registry-breg/src/proposal_hooks.rs index 9eb2a341d0..59eb470606 100644 --- a/crates/registry-breg/src/proposal_hooks.rs +++ b/crates/registry-breg/src/proposal_hooks.rs @@ -51,7 +51,7 @@ pub fn source_hooks( actions.iter().flat_map(|action| { let hooks = match &action.execution { ActionExecutionSource::Proposal { proposal } => proposal.hooks.as_slice(), - ActionExecutionSource::Immediate {} => &[], + ActionExecutionSource::Immediate { .. } => &[], }; hooks.iter().map(move |hook| (action.id.as_str(), hook)) }) diff --git a/crates/registry-breg/src/proposal_prepare.rs b/crates/registry-breg/src/proposal_prepare.rs index db427b2c5e..de8392fccb 100644 --- a/crates/registry-breg/src/proposal_prepare.rs +++ b/crates/registry-breg/src/proposal_prepare.rs @@ -601,7 +601,7 @@ pub(crate) fn prepare_with_reserved_create_fields( } proposal = workflow(proposal.with_application_preconditions( FrozenApplicationPreconditions { - contract: action.requires.clone(), + contract: crate::model::without_labels(&action.requires), evidence: action.commit_evidence.clone(), input_values: input.clone().into_iter().collect(), targets, diff --git a/crates/registry-breg/src/proposal_workflow.rs b/crates/registry-breg/src/proposal_workflow.rs index b2c4529d1a..fd80bc3f51 100644 --- a/crates/registry-breg/src/proposal_workflow.rs +++ b/crates/registry-breg/src/proposal_workflow.rs @@ -3067,7 +3067,9 @@ mod source_owned_review_tests { at_least: None, at_most: None, current_date: Some(crate::model::CompiledCurrentDateRelation::OnOrAfter), + label: None, current_date_offset_days: 0, + current_date_offset_months: 0, at_least_input: None, at_most_input: None, }], diff --git a/crates/registry-breg/src/rhai_planner.rs b/crates/registry-breg/src/rhai_planner.rs index ad4faba2ce..4a4bf1fb5e 100644 --- a/crates/registry-breg/src/rhai_planner.rs +++ b/crates/registry-breg/src/rhai_planner.rs @@ -193,7 +193,10 @@ fn add_days(value: ImmutableString, days: INT) -> Result Result> { +pub(crate) fn add_months( + value: ImmutableString, + months: INT, +) -> Result> { if !(-12_000..=12_000).contains(&months) { return Err(helper_error()); } diff --git a/crates/registry-breg/src/startup.rs b/crates/registry-breg/src/startup.rs index 3c6e9cccb2..fd4b09c67a 100644 --- a/crates/registry-breg/src/startup.rs +++ b/crates/registry-breg/src/startup.rs @@ -1259,6 +1259,18 @@ pub async fn rehearse_schema_fingerprint( config: &RuntimeConfig, registry: &CompiledRegistry, ) -> Result { + measure_schema_install(config, registry) + .await + .map(|measurement| measurement.fingerprint) +} + +/// The same rehearsal as [`rehearse_schema_fingerprint`], also returning the +/// server's PostgreSQL major version, which a rehearsal receipt records. +#[cfg(all(feature = "runtime", feature = "tooling"))] +pub async fn measure_schema_install( + config: &RuntimeConfig, + registry: &CompiledRegistry, +) -> Result { validate_rehearsal_registry_binding(registry)?; let migration = config .migration_database_connection_config() @@ -1302,7 +1314,9 @@ pub async fn rehearse_schema_fingerprint_with_connection_config_for_test( migration: &crate::postgres::ConnectionConfig, ) -> Result { validate_rehearsal_registry_binding(registry)?; - rehearse_schema_fingerprint_with_connection_config(config, registry, migration).await + rehearse_schema_fingerprint_with_connection_config(config, registry, migration) + .await + .map(|measurement| measurement.fingerprint) } #[cfg(all(feature = "runtime", feature = "tooling"))] @@ -1310,7 +1324,7 @@ async fn rehearse_schema_fingerprint_with_connection_config( config: &RuntimeConfig, registry: &CompiledRegistry, migration: &crate::postgres::ConnectionConfig, -) -> Result { +) -> Result { crate::postgres::rehearse_schema_fingerprint_with_connection( migration, config.database().roles().migration(), diff --git a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs index 4df980de14..00797af48e 100644 --- a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs +++ b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs @@ -52,6 +52,44 @@ fn prospective_row_boundary_refusal_is_documented_only_where_it_can_apply() { assert_eq!(example["title"], "Forbidden"); } +#[test] +fn availability_response_admits_a_bounded_guard_label_beside_its_reason() { + let registry = compiled_asset_result_action_registry(); + let action = registry + .actions() + .actions + .iter() + .find(|action| action.id == "register-asset") + .unwrap(); + let schema = inline_validator(&super::openapi_action_availability_response_schema(action)); + let unavailable = |members: Value| { + let mut availability = json!({ + "available": false, "observedRevision": 3, + "reason": "guard-not-satisfied", "recovery": "none" + }); + for (key, value) in members.as_object().unwrap() { + availability[key] = value.clone(); + } + json!({"availability": availability}) + }; + assert_valid(&schema, &unavailable(json!({}))); + assert_valid( + &schema, + &unavailable( + json!({"guardReason": "not-submitted", "guardLabel": "Only a submitted application can be approved."}), + ), + ); + assert_invalid(&schema, &unavailable(json!({"guardLabel": ""}))); + assert_invalid( + &schema, + &unavailable(json!({"guardLabel": "a".repeat(257)})), + ); + assert_invalid( + &schema, + &json!({"availability": {"available": true, "observedRevision": 3, "guardLabel": "Misplaced."}}), + ); +} + #[test] fn write_outside_boundary_problem_is_exact_and_does_not_narrow_located_problems() { let schema = inline_validator(&super::problem_schema()); diff --git a/crates/registry-breg/tests/compiled_ddl_pins.rs b/crates/registry-breg/tests/compiled_ddl_pins.rs index 8154a650c5..49a4091fc6 100644 --- a/crates/registry-breg/tests/compiled_ddl_pins.rs +++ b/crates/registry-breg/tests/compiled_ddl_pins.rs @@ -126,7 +126,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/facility-registry-actions/modules/facility-registry-actions-core/module.yaml" )), ddl_sha256: "6439a877ee6508b999a77242542695d8ccddc6d80518699d90eddc32b305780b", - revision: "sha256:b2b2a04f66dc65e9144b4b77099953572e3e16d8e94446dbfcb47954c31f7667", + revision: "sha256:bc4eede614ac48f7d0c1020f54280e8c801b71cbf1d3ba45f8e1905a5b69bfae", }, Fixture { name: "household-contact-actions", @@ -137,7 +137,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/household-contact-actions/modules/household-contact-actions-core/module.yaml" )), ddl_sha256: "f82f2f8376df97fb184c04d31c8e42c291f7a03dbd909828e1bf61612106de35", - revision: "sha256:80a558305edc78b5db62bac2eb75c078994aad4a518b1f6f8eed1d235a226717", + revision: "sha256:b17f1a3fb58c847395b280ba8df5575aa48793db0e2f5017305bed95a7b9b56c", }, ]; diff --git a/crates/registry-breg/tests/compiler_contract.rs b/crates/registry-breg/tests/compiler_contract.rs index 366e558870..8c2ce960e2 100644 --- a/crates/registry-breg/tests/compiler_contract.rs +++ b/crates/registry-breg/tests/compiler_contract.rs @@ -3180,6 +3180,7 @@ fn all_acceptance_fixtures_compile_manifest_projection_under_production() { dependencies: Vec::new(), functions: Vec::new(), value_types: Default::default(), + row_boundary_sets: Default::default(), entities: Vec::new(), extend_entities: Vec::new(), actions: Vec::new(), diff --git a/crates/registry-breg/tests/immediate_action_compiler.rs b/crates/registry-breg/tests/immediate_action_compiler.rs index e4745f884a..d303891e34 100644 --- a/crates/registry-breg/tests/immediate_action_compiler.rs +++ b/crates/registry-breg/tests/immediate_action_compiler.rs @@ -1046,3 +1046,47 @@ fn ambiguous_action_can_require_explicit_profile_but_cannot_have_two_defaults() .iter() .any(|diagnostic| diagnostic.code == "breg.action.route-access-default-multiple")); } + +#[test] +fn current_revision_refuses_a_function_plan_that_writes_an_existing_record() { + use registry_breg::compiler::compile_project_with_assets; + use registry_breg::contract::ModuleAssetSource; + use serde_json::{json, Value}; + + let mut source: Value = serde_json::from_str(&household_contact_project("")).unwrap(); + let effects = source["actions"]["register-household-contact"]["plan"]["effects"].take(); + let writes = effects + .as_array() + .unwrap() + .iter() + .map(|effect| { + json!({ + "id": effect["id"], "target": effect["target"], "operation": effect["operation"], + "fields": effect["set"].as_object().unwrap().keys().collect::>() + }) + }) + .collect::>(); + source["functions"] = json!({"contact-plan": {"runtime":"rhai","source":"scripts/handler.rhai","entrypoint":"handle","abi":"registry.action-plan/v1"}}); + source["actions"]["register-household-contact"]["plan"] = json!({"type":"function","function":"contact-plan","inputs":["household","person-code","legal-name"],"writes":writes}); + source["actions"]["register-household-contact"]["execution"] = + json!({"mode":"immediate","concurrency":"current-revision"}); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let failure = compile_project_with_assets( + &project, + &[], + &[ModuleAssetSource { + module: None, + path: "scripts/handler.rhai".to_owned(), + bytes: br#"fn handle(ctx) { #{effects:[]} }"#.to_vec(), + }], + CompileProfile::Authoring, + ) + .expect_err("a function plan cannot write an existing record without a condition"); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == "breg.action.concurrency-caller-value"), + "{failure:?}" + ); +} diff --git a/crates/registry-breg/tests/immediate_action_requirements.rs b/crates/registry-breg/tests/immediate_action_requirements.rs index 973a15e0e1..241d08282c 100644 --- a/crates/registry-breg/tests/immediate_action_requirements.rs +++ b/crates/registry-breg/tests/immediate_action_requirements.rs @@ -65,6 +65,88 @@ fn authored_guard_copy_keys_are_bounded_and_only_apply_to_field_guards() { } } +#[test] +fn a_guard_label_is_a_bounded_constant_that_requires_a_reason() { + let guard = |members: Value| { + let mut source = support::project(); + let target = &mut source["actions"]["register-child"]["commitGuards"]["targets"][0]; + for (key, value) in members.as_object().unwrap() { + target[key] = value.clone(); + } + source + }; + let refused = |members: Value, code: &str| { + let report = format!("{:?}", compile(guard(members)).unwrap_err()); + assert!(report.contains(code), "{report}"); + }; + + let registry = compile(guard(json!({ + "reason": "parent-inactive", "label": "Only an active parent takes a child." + }))) + .expect("a label beside its reason compiles"); + let compiled = ®istry.actions().actions[0].requires[0]; + assert_eq!(compiled.reason.as_deref(), Some("parent-inactive")); + assert_eq!( + compiled.label.as_deref(), + Some("Only an active parent takes a child.") + ); + compile(guard( + json!({"reason": "parent-inactive", "label": "é".repeat(128)}), + )) + .expect("256 bytes is the bound itself"); + + refused( + json!({"label": "A label without a reason."}), + "breg.action.commit_guards.label-requires-reason", + ); + for label in [ + "".to_owned(), + " ".to_owned(), + "a".repeat(257), + "é".repeat(129), + "line\nbreak".to_owned(), + ] { + refused( + json!({"reason": "parent-inactive", "label": label}), + "breg.action.commit_guards.label-invalid", + ); + } + + let unlabelled = compile(guard(json!({"reason": "parent-inactive"}))).unwrap(); + let compiled = serde_json::to_value(&unlabelled).unwrap(); + assert!( + !compiled.to_string().contains("\"label\":\"Only"), + "an Action without a label serializes without the member" + ); +} + +#[test] +fn rewording_a_guard_label_changes_neither_the_action_revision_nor_the_migration_review_revision() { + let guarded = |label: Option<&str>| { + let mut source = support::project(); + let target = &mut source["actions"]["register-child"]["commitGuards"]["targets"][0]; + target["reason"] = json!("parent-inactive"); + if let Some(label) = label { + target["label"] = json!(label); + } + compile(source).unwrap().actions().actions[0].clone() + }; + let none = guarded(None); + let first = guarded(Some("Only an active parent takes a child.")); + let second = guarded(Some("The parent must be active.")); + assert_ne!(first, second, "the compiled Actions differ by their label"); + assert_eq!(first.definition_revision, second.definition_revision); + assert_eq!(first.definition_revision, none.definition_revision); + assert_eq!( + registry_breg::immediate_actions::migration_review_revision(&first), + registry_breg::immediate_actions::migration_review_revision(&second) + ); + assert_eq!( + registry_breg::immediate_actions::migration_review_revision(&first), + registry_breg::immediate_actions::migration_review_revision(&none) + ); +} + #[test] fn action_requirements_can_compare_a_target_field_to_a_typed_action_input() { let mut source = support::project(); @@ -146,6 +228,67 @@ fn current_date_offsets_are_bounded_and_bound_to_current_date() { } } +#[test] +fn current_date_month_offsets_are_bounded_bound_to_current_date_and_exclusive_with_days() { + let guard_project = |members: Value| { + let mut source = ordered_guard_project(); + source["project"]["timezone"] = json!("UTC"); + let mut guard = json!({"input": "parent", "field": "opened-on"}); + for (key, value) in members.as_object().unwrap() { + guard[key] = value.clone(); + } + source["actions"]["register-child"]["commitGuards"]["targets"] = json!([guard]); + source + }; + let refused = |members: Value| { + let report = format!("{:?}", compile(guard_project(members)).unwrap_err()); + assert!( + report.contains("breg.action.commit_guards.current-date-offset-invalid"), + "{report}" + ); + }; + + let registry = compile(guard_project( + json!({"currentDate": "on-or-after", "currentDateOffsetMonths": -3}), + )) + .expect("a signed whole-month offset compiles"); + let guard = ®istry.actions().actions[0].requires[0]; + assert_eq!(guard.current_date_offset_months, -3); + assert_eq!(guard.current_date_offset_days, 0); + + let explicit_zero = compile(guard_project( + json!({"currentDate": "on-or-after", "currentDateOffsetMonths": 0}), + )) + .expect("zero keeps the existing comparison"); + let absent = compile(guard_project(json!({"currentDate": "on-or-after"}))) + .expect("an absent offset keeps the existing comparison"); + assert_eq!( + explicit_zero.actions().actions[0].requires[0], + absent.actions().actions[0].requires[0] + ); + let compiled = serde_json::to_value(&absent).unwrap(); + assert!( + !compiled.to_string().contains("currentDateOffsetMonths"), + "a zero month offset leaves the compiled model, and every digest over it, unchanged" + ); + + for months in [12_000, -12_000] { + compile(guard_project( + json!({"currentDate": "on-or-after", "currentDateOffsetMonths": months}), + )) + .expect("the bound itself compiles"); + } + for months in [12_001, -12_001] { + refused(json!({"currentDate": "on-or-after", "currentDateOffsetMonths": months})); + } + refused(json!({"currentDateOffsetMonths": 1})); + refused(json!({ + "currentDate": "on-or-after", + "currentDateOffsetMonths": 1, + "currentDateOffsetDays": 1 + })); +} + /// A project whose parent stores one ordered field of each kind and whose /// action takes a required input of each kind. fn ordered_guard_project() -> Value { @@ -507,3 +650,227 @@ fn equality_inputs_must_be_required_and_an_unset_value_is_stated_explicitly() { assert!(format!("{:?}", compile(source).unwrap_err()) .contains("breg.action.commit_guards.targets-value-invalid")); } + +/// `support::project()` plus `deactivate-parent`, an immediate Action that +/// patches an existing parent and guards the status the patch changes. +fn deactivate_project(execution: Value) -> Value { + let mut source = support::project(); + source["actions"]["deactivate-parent"] = json!({ + "execution": execution, + "inputs": [ + {"id": "parent", "apiName": "parentId", "type": "reference", "target": "parent", "required": true, "classification": "restricted"}, + {"id": "zone", "type": "string", "maximumLength": 32, "required": true, "classification": "restricted"} + ], + "commitGuards": {"targets": [ + {"input": "parent", "field": "status", "equals": "active", "reason": "not-active"} + ]}, + "plan": {"type": "fixed", "effects": [ + {"id": "deactivate", "target": {"fromInput": "parent"}, "operation": "patch", + "set": {"status": {"value": "inactive"}}} + ]} + }); + source["accessProfiles"]["registrar"]["permissions"]["actions"] + .as_array_mut() + .unwrap() + .push(json!({"action": "deactivate-parent", "operations": ["invoke"], "targets": [ + {"recordType": "parent", "rowBoundaries": [{"field": "zone", "claim": "zone", "operator": "equals"}]} + ]})); + source +} + +fn current_revision() -> Value { + json!({"mode": "immediate", "concurrency": "current-revision"}) +} + +fn deactivate_parent( + registry: ®istry_breg::CompiledRegistry, +) -> ®istry_breg::model::CompiledAction { + registry + .actions() + .actions + .iter() + .find(|action| action.id == "deactivate-parent") + .expect("the project declares deactivate-parent") +} + +fn refused_with(source: Value, code: &str) -> String { + let failure = compile(source).expect_err("the Action is refused"); + let report = format!("{failure:?}"); + assert!( + failure.diagnostics().iter().any(|d| d.code == code), + "expected {code}: {report}" + ); + report +} + +#[test] +fn a_current_revision_action_needs_no_condition_from_the_caller() { + let conditioned = compile(deactivate_project(json!({"mode": "immediate"}))).unwrap(); + let before = deactivate_parent(&conditioned); + assert!(before.condition_route.is_some()); + assert!(before + .target_uses + .iter() + .any(|use_| use_.condition_required)); + + let registry = compile(deactivate_project(current_revision())).unwrap(); + let action = deactivate_parent(®istry); + assert!(action.condition_route.is_none()); + assert!(action + .target_uses + .iter() + .all(|use_| !use_.condition_required)); + assert_eq!( + action.concurrency, + registry_breg::contract::ActionConcurrency::CurrentRevision + ); + assert_ne!( + action.definition_revision, before.definition_revision, + "the concurrency mode is part of the Action's identity" + ); + assert_ne!( + registry_breg::immediate_actions::migration_review_revision(action), + registry_breg::immediate_actions::migration_review_revision(before), + "turning it on is a reviewed change" + ); +} + +#[test] +fn omitting_concurrency_leaves_the_compiled_action_unchanged() { + let omitted = compile(deactivate_project(json!({"mode": "immediate"}))).unwrap(); + let named = compile(deactivate_project( + json!({"mode": "immediate", "concurrency": "condition-required"}), + )) + .unwrap(); + assert_eq!( + serde_json::to_value(deactivate_parent(&omitted)).unwrap(), + serde_json::to_value(deactivate_parent(&named)).unwrap() + ); + assert!(!serde_json::to_string(deactivate_parent(&omitted)) + .unwrap() + .contains("concurrency")); +} + +#[test] +fn concurrency_is_refused_under_a_proposal_execution() { + let mut source = deactivate_project(current_revision()); + let proposal = json!({"mode": "proposal", "concurrency": "current-revision"}); + source["actions"]["deactivate-parent"]["execution"] = proposal; + let error = parse_project_json(&serde_json::to_vec(&source).unwrap()) + .expect_err("a proposal Action names no concurrency"); + assert!(format!("{error:?}").contains("concurrency"), "{error:?}"); +} + +#[test] +fn current_revision_refuses_a_revision_guard() { + let mut source = deactivate_project(current_revision()); + source["actions"]["deactivate-parent"]["commitGuards"]["targets"] + .as_array_mut() + .unwrap() + .push(json!({"input": "parent", "revision": "unchanged"})); + refused_with(source, "breg.action.concurrency-revision-guard"); +} + +#[test] +fn current_revision_refuses_caller_values_written_into_an_existing_record() { + let mut from_input = deactivate_project(current_revision()); + from_input["actions"]["deactivate-parent"]["plan"]["effects"][0]["set"] = + json!({"status": {"value": "inactive"}, "zone": {"fromInput": "zone"}}); + let report = refused_with(from_input, "breg.action.concurrency-caller-value"); + assert!( + report.contains("deactivate") && report.contains("zone"), + "{report}" + ); + + let mut from_effect = deactivate_project(current_revision()); + from_effect["actions"]["deactivate-parent"] = json!({ + "execution": current_revision(), + "inputs": [ + {"id": "child", "apiName": "childId", "type": "reference", "target": "child", "required": true, "classification": "restricted"} + ], + "commitGuards": {"targets": [{"input": "child", "field": "label", "equals": "old"}]}, + "plan": {"type": "fixed", "effects": [ + {"id": "fresh", "target": {"recordType": "parent"}, "operation": "create", + "set": {"status": {"value": "active"}, "zone": {"value": "north"}}}, + {"id": "reparent", "target": {"fromInput": "child"}, "operation": "patch", + "set": {"label": {"value": "new"}, "parent": {"fromEffect": "fresh"}}} + ]} + }); + from_effect["accessProfiles"]["registrar"]["permissions"]["actions"][1]["targets"] = json!([ + {"recordType": "parent", "rowBoundaries": "unrestricted"}, + {"recordType": "child", "rowBoundaries": "unrestricted"} + ]); + refused_with(from_effect, "breg.action.concurrency-caller-value"); +} + +#[test] +fn current_revision_allows_a_caller_value_into_a_created_record() { + let mut source = deactivate_project(current_revision()); + source["actions"]["deactivate-parent"]["plan"]["effects"] + .as_array_mut() + .unwrap() + .push( + json!({"id": "child", "target": {"recordType": "child"}, "operation": "create", + "set": {"parent": {"fromInput": "parent"}, "label": {"fromInput": "zone"}}}), + ); + source["accessProfiles"]["registrar"]["permissions"]["actions"][1]["targets"] + .as_array_mut() + .unwrap() + .push(json!({"recordType": "child", "rowBoundaries": "unrestricted"})); + compile(source).expect("a create takes a caller value under current-revision"); +} + +#[test] +fn current_revision_allows_clearing_a_field() { + let mut source = support::project(); + source["recordTypes"]["parent"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id": "note", "type": "string", "maximumLength": 32, "classification": "restricted"})); + let mut with_note = deactivate_project(current_revision()); + with_note["recordTypes"] = source["recordTypes"].clone(); + with_note["actions"]["deactivate-parent"]["plan"]["effects"][0]["clear"] = json!(["note"]); + compile(with_note).expect("a clear is a constant"); +} + +#[test] +fn current_revision_needs_a_guard_the_write_falsifies() { + // No guard on the patched record. + let mut unguarded = deactivate_project(current_revision()); + unguarded["actions"]["deactivate-parent"]["commitGuards"] = json!({"targets": []}); + refused_with(unguarded, "breg.action.concurrency-guard-missing"); + + // A guard on a field the write does not change. + let mut elsewhere = deactivate_project(current_revision()); + elsewhere["actions"]["deactivate-parent"]["commitGuards"]["targets"] = + json!([{"input": "parent", "field": "zone", "equals": "north"}]); + refused_with(elsewhere, "breg.action.concurrency-guard-missing"); + + // A guard the write leaves true: both want "inactive". + let mut same = deactivate_project(current_revision()); + same["actions"]["deactivate-parent"]["commitGuards"]["targets"] = + json!([{"input": "parent", "field": "status", "equals": "inactive"}]); + refused_with(same, "breg.action.concurrency-guard-missing"); + + // A guard that depends on the caller cannot be falsified by the write. + let mut by_input = deactivate_project(current_revision()); + by_input["actions"]["deactivate-parent"]["commitGuards"]["targets"] = + json!([{"input": "parent", "field": "zone", "equalsFromInput": "zone"}]); + refused_with(by_input, "breg.action.concurrency-guard-missing"); +} + +#[test] +fn current_revision_accepts_a_null_guard_the_write_falsifies() { + let mut source = support::project(); + source["recordTypes"]["parent"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id": "closed-on", "type": "string", "maximumLength": 32, "classification": "restricted"})); + let mut open = deactivate_project(current_revision()); + open["recordTypes"] = source["recordTypes"].clone(); + open["actions"]["deactivate-parent"]["commitGuards"]["targets"] = + json!([{"input": "parent", "field": "closed-on", "isNull": true}]); + open["actions"]["deactivate-parent"]["plan"]["effects"][0]["set"] = + json!({"closed-on": {"value": "2026-11-27"}}); + compile(open).expect("setting a field the guard requires unset falsifies the guard"); +} diff --git a/crates/registry-breg/tests/postgres_immediate_action_requirements.rs b/crates/registry-breg/tests/postgres_immediate_action_requirements.rs index 7c9e3d3d5a..32542ee220 100644 --- a/crates/registry-breg/tests/postgres_immediate_action_requirements.rs +++ b/crates/registry-breg/tests/postgres_immediate_action_requirements.rs @@ -363,6 +363,41 @@ async fn current_date_offset_is_enforced_at_immediate_commit() { database.cleanup().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn current_date_month_offset_is_enforced_at_immediate_commit() { + let mut source = support::project(); + source["project"]["timezone"] = json!("UTC"); + source["recordTypes"]["parent"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({ + "id":"eligible-on", "type":"date", "classification":"restricted" + })); + source["actions"]["register-child"]["commitGuards"]["targets"] + .as_array_mut() + .unwrap() + .push(json!({ + "input":"parent", "field":"eligible-on", "currentDate":"on-or-after", + "currentDateOffsetMonths":1 + })); + let (database, registry, identity) = setup_with_project(source).await; + let today = registry + .local_date_at(time::OffsetDateTime::now_utc()) + .unwrap(); + let threshold = today.checked_add_months(chrono::Months::new(1)).unwrap(); + set_parent_eligible_on(&database, ®istry, threshold).await; + let app = app(&database, registry.clone(), identity, None); + let accepted = invoke(app.clone(), "month-offset-accepted", ID).await; + assert_eq!(accepted.0, StatusCode::OK, "{}", accepted.1); + let committed = counts(&database, ®istry).await; + + set_parent_eligible_on(&database, ®istry, today).await; + let refused = invoke(app, "month-offset-refused", ID).await; + assert_eq!(refused.0, StatusCode::PRECONDITION_FAILED, "{}", refused.1); + assert_eq!(counts(&database, ®istry).await, committed); + database.cleanup().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn ordered_input_guards_compare_dates_and_instants_against_stored_fields() { let mut source = with_parent_get( @@ -1103,6 +1138,123 @@ async fn counts(database: &TestDatabase, registry: ®istry_breg::CompiledRegis (0..6).map(|index| row.get(index)).collect() } +const GUARD_LABEL: &str = "Only an active parent can take a new child."; + +/// The registrar's one guard carries a reason and an authored label. +fn with_guard_label(mut source: Value) -> Value { + let guard = &mut source["actions"]["register-child"]["commitGuards"]["targets"][0]; + guard["reason"] = json!("parent-inactive"); + guard["label"] = json!(GUARD_LABEL); + source +} + +/// A body without the per-request `traceId`, so two refusals compare. +fn without_trace(mut body: Value) -> Value { + body.as_object_mut().unwrap().remove("traceId"); + body +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_guard_label_rides_only_the_readable_guard_refusal_and_availability() { + let source = with_guard_label(with_parent_get(support::project(), &["status", "zone"])); + let (database, registry, identity) = setup_with_project(source).await; + let app = app(&database, registry.clone(), identity, None); + database + .admin + .execute( + &status_sql(®istry), + &[&"inactive", &Uuid::parse_str(ID).unwrap()], + ) + .await + .unwrap(); + let before = counts(&database, ®istry).await; + + let refused = invoke(app.clone(), "labelled-guard", ID).await; + assert_eq!(refused.0, StatusCode::PRECONDITION_FAILED, "{}", refused.1); + assert_eq!(refused.1["code"], "action.guard_failed"); + assert_eq!(refused.1["guardReason"], "parent-inactive"); + assert_eq!(refused.1["detail"], GUARD_LABEL); + + let unavailable = availability(app.clone(), json!({"parentId":ID})).await; + assert_eq!(unavailable.0, StatusCode::OK, "{}", unavailable.1); + assert_eq!( + unavailable.1, + json!({"availability":{ + "available":false, + "observedRevision":2, + "reason":"guard-not-satisfied", + "guardReason":"parent-inactive", + "guardLabel":GUARD_LABEL, + "recovery":"none" + }}) + ); + assert_eq!(before, counts(&database, ®istry).await); + database.cleanup().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_unreadable_guard_field_never_discloses_the_guard_label() { + // The profile cannot read `status`, so the failed guard stays the fixed + // precondition refusal, byte-identical to a row-boundary refusal. + let source = with_guard_label(with_parent_get(support::project(), &["zone"])); + let (database, registry, identity) = setup_with_project(source).await; + insert_parent( + &database, + ®istry, + &identity.activation_id, + FOREIGN_ID, + "active", + "zone-b", + ) + .await; + let mut app = app(&database, registry.clone(), identity, None); + database + .admin + .execute( + &status_sql(®istry), + &[&"inactive", &Uuid::parse_str(ID).unwrap()], + ) + .await + .unwrap(); + + let hidden_guard = invoke(app.clone(), "hidden-guard", ID).await; + let boundary = invoke(app.clone(), "hidden-boundary", FOREIGN_ID).await; + assert_eq!(hidden_guard.0, StatusCode::PRECONDITION_FAILED); + assert_eq!(hidden_guard.0, boundary.0); + assert_eq!(hidden_guard.1["code"], "precondition.failed"); + assert_eq!( + without_trace(hidden_guard.1.clone()), + without_trace(boundary.1), + "a hidden guard answers exactly as a boundary refusal does" + ); + assert!(!hidden_guard.1.to_string().contains(GUARD_LABEL)); + assert!(hidden_guard.1.get("guardReason").is_none()); + + // Neither the headers nor an availability answer carry the label. + let mut request = Request::builder() + .method("POST") + .uri("/v1/actions/register-child") + .header("content-type", "application/json") + .header("idempotency-key", "hidden-guard-headers") + .body(Body::from( + serde_json::to_vec(&json!({"input": {"parentId": ID, "label": "synthetic"}})).unwrap(), + )) + .unwrap(); + request.extensions_mut().insert(registrar_claims()); + let response = app.call(request).await.unwrap(); + assert!(response + .headers() + .iter() + .all(|(_, value)| !String::from_utf8_lossy(value.as_bytes()).contains(GUARD_LABEL))); + let hidden_availability = availability(app, json!({"parentId":ID})).await; + assert!( + !hidden_availability.1.to_string().contains(GUARD_LABEL), + "{}", + hidden_availability.1 + ); + database.cleanup().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn action_requirements_are_acceptance_only_atomic_and_replayable() { let (database, registry, identity) = setup().await; diff --git a/crates/registry-breg/tests/postgres_immediate_actions.rs b/crates/registry-breg/tests/postgres_immediate_actions.rs index 72898e5063..326dcbf2b1 100644 --- a/crates/registry-breg/tests/postgres_immediate_actions.rs +++ b/crates/registry-breg/tests/postgres_immediate_actions.rs @@ -3828,3 +3828,325 @@ fn history_registry() -> registry_breg::CompiledRegistry { .expect("history project parses"); compile_project(&project, &[], CompileProfile::Authoring).expect("history project compiles") } + +/// The action project plus `close-household`, a `current-revision` Action +/// whose guard (`status-note` unset) is the write it makes false, and +/// `recode-household`, a condition-required Action that changes another +/// field of the same record. +fn current_revision_registry() -> registry_breg::CompiledRegistry { + let mut source: Value = serde_json::from_slice(ACTION_PROJECT).expect("action project is JSON"); + let household_input = json!({ + "id": "household", "apiName": "householdId", "type": "reference", + "target": "household", "required": true, "classification": "restricted" + }); + source["actions"]["close-household"] = json!({ + "inputs": [household_input.clone()], + "execution": {"mode": "immediate", "concurrency": "current-revision"}, + "commitGuards": {"targets": [ + {"input": "household", "field": "status-note", "isNull": true, "reason": "already-closed"} + ]}, + "plan": {"type": "fixed", "effects": [ + {"id": "close", "target": {"fromInput": "household"}, "operation": "patch", + "set": {"status-note": {"value": "closed"}}} + ]} + }); + source["actions"]["recode-household"] = json!({ + "inputs": [household_input, { + "id": "household-code", "apiName": "householdCode", "type": "string", + "maximumLength": 64, "required": true, "classification": "restricted" + }], + "execution": {"mode": "immediate"}, + "plan": {"type": "fixed", "effects": [ + {"id": "recode", "target": {"fromInput": "household"}, "operation": "patch", + "set": {"household-code": {"fromInput": "household-code"}}} + ]} + }); + let boundary = json!([{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]); + let permissions = source["accessProfiles"]["contact-registrar"]["permissions"]["actions"] + .as_array_mut() + .expect("the registrar grants Actions"); + for (action, result) in [("close-household", "close"), ("recode-household", "recode")] { + permissions.push(json!({ + "action": action, "operations": ["invoke"], + "targets": [{"recordType": "household", "rowBoundaries": boundary.clone()}], + "results": [result] + })); + } + let project = parse_project_json(&serde_json::to_vec(&source).expect("project serializes")) + .expect("current-revision project parses"); + compile_project(&project, &[], CompileProfile::Authoring) + .expect("current-revision project compiles") +} + +async fn invoke_close( + app: &axum::Router, + household: &str, + key: &str, + extra: Value, +) -> ResponseParts { + let mut body = json!({"input": {"householdId": household}}); + if let Value::Object(extra) = extra { + body.as_object_mut() + .expect("body is an object") + .extend(extra); + } + response_parts( + send( + app, + Method::POST, + "/v1/actions/close-household", + Some(action_claims()), + &[ + ("content-type", "application/json"), + ("idempotency-key", key), + ], + serde_json::to_vec(&body).expect("body serializes"), + ) + .await, + ) + .await +} + +fn without_trace(mut body: Value) -> Value { + body.as_object_mut().map(|map| map.remove("traceId")); + body +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_current_revision_action_commits_over_plain_http_without_a_condition() { + let (database, registry, identity) = install_action_registry(current_revision_registry()).await; + seed_household( + &database, + ®istry, + &identity, + HOUSEHOLD_ID, + "H-001", + "zone-a", + ) + .await; + let app = action_router(&database, registry.clone(), identity); + + // The contract names no condition route, so a caller has none to ask for. + let route = response_parts( + send( + &app, + Method::POST, + "/v1/actions/close-household/target-conditions", + Some(action_claims()), + &[("content-type", "application/json")], + serde_json::to_vec(&json!({"input": {"householdId": HOUSEHOLD_ID}})).unwrap(), + ) + .await, + ) + .await; + assert_eq!(route.status, StatusCode::NOT_FOUND, "{}", route.body); + + let closed = invoke_close(&app, HOUSEHOLD_ID, "close-1", json!({})).await; + assert_eq!(closed.status, StatusCode::OK, "{}", closed.body); + assert_eq!( + closed.body["results"]["close"]["revision"], 2, + "{}", + closed.body + ); + let (code, note, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!( + (code.as_str(), note.as_deref(), revision), + ("H-001", Some("closed"), 2) + ); + + // A second run finds the guard false on the current row. + let again = invoke_close(&app, HOUSEHOLD_ID, "close-2", json!({})).await; + assert_eq!( + again.status, + StatusCode::PRECONDITION_FAILED, + "{}", + again.body + ); + // The caller holds no read grant on the guarded field, so the refusal + // is the generic one and names no guard. + assert_eq!(again.body["code"], "precondition.failed", "{}", again.body); + assert!(again.body.get("guardReason").is_none(), "{}", again.body); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn two_concurrent_current_revision_invocations_commit_exactly_once() { + let (database, registry, identity) = install_action_registry(current_revision_registry()).await; + seed_household( + &database, + ®istry, + &identity, + HOUSEHOLD_ID, + "H-001", + "zone-a", + ) + .await; + let app = action_router(&database, registry.clone(), identity); + + let (first, second) = tokio::join!( + invoke_close(&app, HOUSEHOLD_ID, "race-a", json!({})), + invoke_close(&app, HOUSEHOLD_ID, "race-b", json!({})), + ); + let mut statuses = [first.status, second.status]; + statuses.sort(); + assert_eq!( + statuses, + [StatusCode::OK, StatusCode::PRECONDITION_FAILED], + "{} / {}", + first.body, + second.body + ); + let loser = if first.status == StatusCode::OK { + &second + } else { + &first + }; + assert_eq!(loser.body["code"], "precondition.failed", "{}", loser.body); + let (_, note, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!((note.as_deref(), revision), (Some("closed"), 2)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn condition_required_still_demands_a_condition_and_current_revision_refuses_one() { + let (database, registry, identity) = install_action_registry(current_revision_registry()).await; + seed_household( + &database, + ®istry, + &identity, + HOUSEHOLD_ID, + "H-001", + "zone-a", + ) + .await; + let app = action_router(&database, registry.clone(), identity); + + let recode = |preconditions: Option, key: &'static str| { + let app = app.clone(); + async move { + let mut body = + json!({"input": {"householdId": HOUSEHOLD_ID, "householdCode": "H-NEW"}}); + if let Some(preconditions) = preconditions { + body["preconditions"] = preconditions; + } + response_parts( + send( + &app, + Method::POST, + "/v1/actions/recode-household", + Some(action_claims()), + &[ + ("content-type", "application/json"), + ("idempotency-key", key), + ], + serde_json::to_vec(&body).unwrap(), + ) + .await, + ) + .await + } + }; + let missing = recode(None, "recode-missing").await; + assert_eq!(missing.status, StatusCode::BAD_REQUEST, "{}", missing.body); + let (code, _, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!((code.as_str(), revision), ("H-001", 1)); + + // A condition sent to an Action that asks for none is refused, and the + // row is untouched. + let stale = json!({"householdId": {"ifMatch": "W/\"anything\""}}); + let unwanted = invoke_close( + &app, + HOUSEHOLD_ID, + "close-conditioned", + json!({"preconditions": stale}), + ) + .await; + assert_eq!( + unwanted.status, + StatusCode::BAD_REQUEST, + "{}", + unwanted.body + ); + let (_, note, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!((note, revision), (None, 1)); + + // The conditioned Action changes the code, then the current-revision + // Action patches the locked current row: the code keeps its new value. + let condition = response_parts( + send( + &app, + Method::POST, + "/v1/actions/recode-household/target-conditions", + Some(action_claims()), + &[("content-type", "application/json")], + serde_json::to_vec(&json!({"input": {"householdId": HOUSEHOLD_ID}})).unwrap(), + ) + .await, + ) + .await; + assert_eq!(condition.status, StatusCode::OK, "{}", condition.body); + let recoded = recode(Some(condition.body["preconditions"].clone()), "recode-ok").await; + assert_eq!(recoded.status, StatusCode::OK, "{}", recoded.body); + let closed = invoke_close(&app, HOUSEHOLD_ID, "close-after-recode", json!({})).await; + assert_eq!(closed.status, StatusCode::OK, "{}", closed.body); + let (code, note, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!( + (code.as_str(), note.as_deref(), revision), + ("H-NEW", Some("closed"), 3) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_current_revision_action_does_not_tell_a_hidden_record_from_a_missing_one() { + let (database, registry, identity) = install_action_registry(current_revision_registry()).await; + seed_household( + &database, + ®istry, + &identity, + HOUSEHOLD_ID, + "H-001", + "zone-a", + ) + .await; + seed_household( + &database, + ®istry, + &identity, + OTHER_HOUSEHOLD_ID, + "H-002", + "zone-b", + ) + .await; + let app = action_router(&database, registry.clone(), identity); + + let missing = invoke_close( + &app, + "00000000-0000-4000-8000-0000000009ff", + "missing", + json!({}), + ) + .await; + let outside = invoke_close(&app, OTHER_HOUSEHOLD_ID, "outside", json!({})).await; + assert_eq!( + missing.status, + StatusCode::PRECONDITION_FAILED, + "{}", + missing.body + ); + assert_eq!(outside.status, missing.status); + assert_eq!( + without_trace(outside.body.clone()), + without_trace(missing.body.clone()), + "a record outside the caller's boundary answers as a missing record does" + ); + let (_, note, revision) = + household_code_note_revision(&database, ®istry, OTHER_HOUSEHOLD_ID).await; + assert_eq!( + (note, revision), + (None, 1), + "the hidden record is untouched" + ); +} diff --git a/crates/registry-breg/tests/postgres_proposal_guard_failure.rs b/crates/registry-breg/tests/postgres_proposal_guard_failure.rs index 7cd63eb0f6..dbeff466db 100644 --- a/crates/registry-breg/tests/postgres_proposal_guard_failure.rs +++ b/crates/registry-breg/tests/postgres_proposal_guard_failure.rs @@ -51,10 +51,33 @@ fn registry(readable: &[&str]) -> registry_breg::CompiledRegistry { registry_with_current_date_offset(readable, None) } +/// `offset` names a `currentDate` guard member and its value: either +/// `currentDateOffsetDays` or `currentDateOffsetMonths`. fn registry_with_current_date_offset( readable: &[&str], - offset_days: Option, + offset: Option<(&str, i32)>, ) -> registry_breg::CompiledRegistry { + compile_source(guard_project(readable, offset)) +} + +const TARGET_NOT_OPEN_LABEL: &str = "Only an open target can be corrected."; +const BELOW_MINIMUM_LABEL: &str = "The target is below the requested capacity."; + +/// The guards of `registry` with an authored label on each. +fn registry_with_guard_labels(readable: &[&str]) -> registry_breg::CompiledRegistry { + let mut source = guard_project(readable, None); + let guards = &mut source["actions"]["correct-name"]["commitGuards"]["targets"]; + guards[1]["label"] = json!(TARGET_NOT_OPEN_LABEL); + guards[2]["label"] = json!(BELOW_MINIMUM_LABEL); + compile_source(source) +} + +fn compile_source(source: Value) -> registry_breg::CompiledRegistry { + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + compile_project(&project, &[], CompileProfile::Authoring).expect("guard project compiles") +} + +fn guard_project(readable: &[&str], offset: Option<(&str, i32)>) -> Value { let mut source = json!({"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", "project":{"id":"guard-failure-test","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://guard.example.test"}, "datasets":{"directory": {}}, @@ -84,7 +107,7 @@ fn registry_with_current_date_offset( "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], "ownership":"caller","targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); - if let Some(offset_days) = offset_days { + if let Some((member, offset)) = offset { source["project"]["timezone"] = json!("UTC"); source["recordTypes"]["target"]["fields"] .as_array_mut() @@ -97,11 +120,10 @@ fn registry_with_current_date_offset( .unwrap() .push(json!({ "input":"target", "field":"eligible-on", "currentDate":"on-or-after", - "currentDateOffsetDays":offset_days, "reason":"outside-date-window" + member:offset, "reason":"outside-date-window" })); } - let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); - compile_project(&project, &[], CompileProfile::Authoring).expect("guard project compiles") + source } /// A draft over a fresh target Record whose status is `status` and whose @@ -297,7 +319,7 @@ async fn proposal_apply_reevaluates_the_configured_current_date_offset() { let fixture = client_http::ClientFixture::start( registry_with_current_date_offset( &["name", "status", "capacity", "eligible-on", "jurisdiction"], - Some(30), + Some(("currentDateOffsetDays", 30)), ), claims(), ) @@ -326,6 +348,66 @@ async fn proposal_apply_reevaluates_the_configured_current_date_offset() { fixture.finish().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn proposal_apply_reevaluates_the_configured_current_date_month_offset() { + let fixture = client_http::ClientFixture::start( + registry_with_current_date_offset( + &["name", "status", "capacity", "eligible-on", "jurisdiction"], + Some(("currentDateOffsetMonths", 1)), + ), + claims(), + ) + .await; + let today = fixture + .registry + .local_date_at(time::OffsetDateTime::now_utc()) + .unwrap(); + let threshold = today.checked_add_months(chrono::Months::new(1)).unwrap(); + let (draft, target_id) = draft(&fixture, "open", 10, "month-guard-apply").await; + set_eligible_on(&fixture, &target_id, threshold).await; + let submitted = submit(&fixture, &draft, "month-guard-submit") + .await + .unwrap(); + + // Change only the guarded date. Apply reads current state and enforces the + // same month offset again. + set_eligible_on(&fixture, &target_id, today).await; + let refusal = apply(&fixture, &submitted, "month-guard-apply-key") + .await + .unwrap_err(); + assert_eq!( + refusal.problem_code(), + Some(BRegProblemCode::ActionGuardFailed) + ); + assert_eq!(refusal.guard_reason(), Some("outside-date-window")); + fixture.finish().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn submit_and_apply_carry_the_guard_label_only_where_the_reason_rides() { + let fixture = client_http::ClientFixture::start( + registry_with_guard_labels(&["name", "status", "capacity", "jurisdiction"]), + claims(), + ) + .await; + let (retired, _) = draft(&fixture, "retired", 10, "label-submit").await; + let refusal = submit(&fixture, &retired, "label-submit-key") + .await + .unwrap_err(); + assert_eq!(refusal.guard_reason(), Some("target-not-open")); + + // Apply holds its guards without labels, so a reworded label never + // strands a frozen Proposal, and the refusal names the current label. + let (open, open_id) = draft(&fixture, "open", 10, "label-apply").await; + let submitted = submit(&fixture, &open, "label-apply-submit").await.unwrap(); + set_status(&fixture, &open_id, "retired").await; + let refusal = apply(&fixture, &submitted, "label-apply-key") + .await + .unwrap_err(); + assert_eq!(refusal.guard_reason(), Some("target-not-open")); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn submit_names_a_failed_input_comparison_guard() { let fixture = client_http::ClientFixture::start( diff --git a/crates/registry-breg/tests/refactor_contract.rs b/crates/registry-breg/tests/refactor_contract.rs index 2e8db19304..4be44cca0d 100644 --- a/crates/registry-breg/tests/refactor_contract.rs +++ b/crates/registry-breg/tests/refactor_contract.rs @@ -898,7 +898,9 @@ fn immediate_mode_cannot_bypass_target_proposal_policy() { .iter_mut() .find(|action| action.id == "deactivate-facility") .unwrap() - .execution = registry_breg::contract::ActionExecutionSource::Immediate {}; + .execution = registry_breg::contract::ActionExecutionSource::Immediate { + concurrency: Default::default(), + }; for profile in &mut project.access_profiles { profile .permissions diff --git a/crates/registry-breg/tests/row_boundary_sets.rs b/crates/registry-breg/tests/row_boundary_sets.rs new file mode 100644 index 0000000000..9c3be43cd1 --- /dev/null +++ b/crates/registry-breg/tests/row_boundary_sets.rs @@ -0,0 +1,319 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Named row-boundary sets: `rowBoundarySets` declares a reusable list of +//! boundaries once, and `rowBoundaries: {rowBoundarySet: }` reaches it +//! wherever a row reach is written. A grant still writes its own +//! `rowBoundaries`, so reach stays visible at every grant. A reference is +//! expanded when the file is read, and an empty list means every row, so a +//! reference never resolves to an empty list. + +use registry_breg::contract::{parse_module_yaml, parse_project_yaml, RegistryProject}; +use registry_breg::{compile_project, CompileFailure, CompileProfile, CompiledRegistry}; +use serde_json::{json, Value}; + +const SET: &str = "same-district"; +const REFERENCE_CODE: &str = "breg.row-boundary-set.reference-invalid"; + +fn boundary() -> Value { + json!({"field":"district","claim":"districts","operator":"in"}) +} + +fn reference() -> Value { + json!({"rowBoundarySet": SET}) +} + +/// A project that writes its row reach inline at every site: a record +/// permission, an Action target, a Proposal target and a record type's +/// access requirement. +fn inline() -> Value { + json!({ + "datasets":{"test-dataset": {}}, + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", "kind":"BRegProject", + "project":{"id":"access-example","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://access-example.example.test"}, + "recordTypes":{"entry": {"primaryDataset":"test-dataset","route":"entries","mutationMode":"mutable","classification":"internal", + "accessRequirements":{"rowBoundaries":[boundary()]}, + "fields":[{"id":"code","type":"string","maximumLength":32,"classification":"internal"}, + {"id":"district","type":"string","maximumLength":32,"classification":"internal"}]}}, + "accessProfiles":{"reader": {"principalClaim":"registry_principal","requiredScopes":["entry:read"], + "permissions":{ + "records":[{"recordType":"entry","operations":["get","list"], + "readableFields":["code","district"],"filterableFields":["district"], + "rowBoundaries":[boundary()]}], + "actions":[{"action":"register","operations":["invoke"], + "targets":[{"recordType":"entry","rowBoundaries":[boundary()]}]}], + "proposals":[{"action":"register","operations":["get"],"ownership":"caller", + "targets":[{"recordType":"entry","rowBoundaries":[boundary()]}]}] + }}} + }) +} + +const SITES: [&str; 4] = [ + "/accessProfiles/reader/permissions/records/0/rowBoundaries", + "/accessProfiles/reader/permissions/actions/0/targets/0/rowBoundaries", + "/accessProfiles/reader/permissions/proposals/0/targets/0/rowBoundaries", + "/recordTypes/entry/accessRequirements/rowBoundaries", +]; + +/// `inline()` with the set declared once and every site referencing it. +fn by_reference() -> Value { + let mut value = inline(); + value["rowBoundarySets"] = json!({ SET: [boundary()] }); + for site in SITES { + set(&mut value, site, reference()); + } + value +} + +fn set(value: &mut Value, pointer: &str, written: Value) { + *value + .pointer_mut(pointer) + .unwrap_or_else(|| panic!("{pointer} exists")) = written; +} + +fn read(value: &Value) -> Result { + parse_project_yaml(&serde_json::to_vec(value).unwrap()) +} + +fn compile(value: &Value) -> Result { + compile_project(&read(value)?, &[], CompileProfile::Authoring) +} + +/// The one refusal a read answers with, as its code, path, and message. +fn refusal(value: &Value) -> (String, String, String) { + let failure = read(value).expect_err("the project is refused when it is read"); + let [diagnostic] = failure.diagnostics() else { + panic!("one diagnostic refuses the project: {failure:?}"); + }; + ( + diagnostic.code.clone(), + diagnostic.path.clone(), + diagnostic.message.clone(), + ) +} + +/// Compiling needs the Actions the grants name, so a compiled comparison keeps +/// the record permission and the record type's requirement. +fn compilable(mut value: Value) -> Value { + let permissions = value["accessProfiles"]["reader"]["permissions"] + .as_object_mut() + .unwrap(); + permissions.remove("actions"); + permissions.remove("proposals"); + value +} + +#[test] +fn a_reference_reads_as_the_inline_list_at_every_site() { + let referenced = read(&by_reference()).expect("a reference is accepted at every site"); + let written = read(&inline()).expect("the inline form is accepted"); + assert_eq!( + serde_json::to_value(&referenced).unwrap(), + serde_json::to_value(&written).unwrap(), + "a reference expands to the boundaries the set lists, and the set is not part of the read project" + ); + let compiled = compile(&compilable(by_reference())).expect("the referenced project compiles"); + let inline_compiled = compile(&compilable(inline())).expect("the inline project compiles"); + assert_eq!( + serde_json::to_value(&compiled).unwrap(), + serde_json::to_value(&inline_compiled).unwrap(), + "the compiled model does not record where a boundary was written" + ); + let permission = &referenced.access_profiles[0].permissions; + assert_eq!(permission.entities[0].row_boundaries.len(), 1); + assert_eq!(permission.actions[0].targets[0].row_boundaries.len(), 1); + assert_eq!(permission.proposals[0].targets[0].row_boundaries.len(), 1); + assert_eq!( + referenced.entities[0] + .access_requirements + .as_ref() + .expect("the record type carries its requirement") + .row_boundaries + .len(), + 1 + ); +} + +#[test] +fn each_site_takes_the_reference_on_its_own() { + for site in SITES { + let mut value = inline(); + value["rowBoundarySets"] = json!({ SET: [boundary()] }); + set(&mut value, site, reference()); + let project = read(&value).unwrap_or_else(|failure| panic!("{site}: {failure:?}")); + assert_eq!( + serde_json::to_value(&project).unwrap(), + serde_json::to_value(read(&inline()).unwrap()).unwrap(), + "{site}" + ); + } +} + +#[test] +fn an_unknown_set_is_refused_at_the_reference() { + let mut value = by_reference(); + set( + &mut value, + SITES[0], + json!({"rowBoundarySet": "no-such-set"}), + ); + let (code, path, message) = refusal(&value); + assert_eq!(code, REFERENCE_CODE, "{message}"); + assert!( + path.ends_with("permissions.records[0].rowBoundaries.rowBoundarySet"), + "{path}" + ); + + // No declaration at all is the same refusal, never an unrestricted read. + let mut undeclared = inline(); + set(&mut undeclared, SITES[0], reference()); + let (code, _, message) = refusal(&undeclared); + assert_eq!(code, REFERENCE_CODE, "{message}"); +} + +#[test] +fn a_reference_is_a_mapping_with_one_string_member() { + for written in [ + json!({"rowBoundarySet": SET, "field": "district"}), + json!({"rowBoundarySet": ["a"]}), + json!({"rowBoundarySet": 3}), + ] { + let mut value = by_reference(); + set(&mut value, SITES[0], written); + let (code, _, message) = refusal(&value); + assert_eq!(code, REFERENCE_CODE, "{message}"); + } +} + +#[test] +fn a_set_lists_at_least_one_boundary_and_is_never_unrestricted() { + for written in [json!([]), json!("unrestricted")] { + let mut value = by_reference(); + value["rowBoundarySets"][SET] = written; + let (code, path, message) = refusal(&value); + assert_eq!(code, "config.invalid-value", "{message}"); + assert_eq!(path, format!("project.rowBoundarySets.{SET}")); + assert!( + message.contains("at least one row boundary"), + "the refusal says what a set holds: {message}" + ); + } +} + +#[test] +fn an_unresolved_reference_never_decodes_to_an_empty_list() { + // The reader expands references before typed decoding. A path that + // reaches the typed model without it must be refused, because an empty + // list means every row. + let value = by_reference(); + let decoded = serde_json::from_value::(value); + assert!( + decoded.is_err(), + "a reference that reaches the typed model is refused" + ); +} + +#[test] +fn a_set_field_missing_on_the_record_type_is_refused_as_an_inline_boundary_is() { + let mut referenced = compilable(by_reference()); + referenced["rowBoundarySets"][SET][0]["field"] = json!("missing"); + let mut written = compilable(inline()); + for site in [SITES[0], SITES[3]] { + written.pointer_mut(site).unwrap()[0]["field"] = json!("missing"); + } + let by_set = compile(&referenced).expect_err("a boundary on a missing field is refused"); + let by_hand = compile(&written).expect_err("a boundary on a missing field is refused"); + let summarize = |failure: &CompileFailure| { + failure + .diagnostics() + .iter() + .map(|diagnostic| (diagnostic.code.clone(), diagnostic.message.clone())) + .collect::>() + }; + assert_eq!(summarize(&by_set), summarize(&by_hand)); + let codes: Vec<_> = summarize(&by_set) + .into_iter() + .map(|(code, _)| code) + .collect(); + for expected in [ + "breg.access-profile.field-unknown", + "breg.access.requirements-row-boundary-invalid", + ] { + assert!( + codes.iter().any(|code| code == expected), + "the refusal carries {expected}: {codes:?}" + ); + } +} + +#[test] +fn unrestricted_inline_lists_and_omission_keep_their_meaning() { + let mut value = by_reference(); + set(&mut value, SITES[0], json!("unrestricted")); + set(&mut value, SITES[1], json!([boundary()])); + let project = read(&value).expect("the three forms sit beside each other"); + let permissions = &project.access_profiles[0].permissions; + assert!(permissions.entities[0].row_boundaries.is_empty()); + assert_eq!(permissions.actions[0].targets[0].row_boundaries.len(), 1); + assert_eq!(permissions.proposals[0].targets[0].row_boundaries.len(), 1); + + let mut omitted = by_reference(); + omitted + .pointer_mut("/accessProfiles/reader/permissions/records/0") + .and_then(Value::as_object_mut) + .unwrap() + .remove("rowBoundaries"); + let (code, _, message) = refusal(&omitted); + assert_eq!(code, "config.invalid-value", "{message}"); + assert!( + message.contains("write unrestricted to reach every row"), + "{message}" + ); +} + +#[test] +fn a_module_resolves_its_own_sets_and_never_the_projects() { + let module = |set_declared: bool| { + let mut module = json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule", + "id":"extra","version":"1", + "extendRecordTypes":{"entry": {"accessRequirements":{"rowBoundaries": reference()}}} + }); + if set_declared { + module["rowBoundarySets"] = json!({ SET: [boundary()] }); + } + serde_json::to_vec(&module).unwrap() + }; + let parsed = parse_module_yaml(&module(true)).expect("a module reaches its own set"); + let written = serde_json::to_value(&parsed).unwrap(); + assert_eq!( + written.pointer("/extendRecordTypes/entry/accessRequirements/rowBoundaries"), + Some(&json!([boundary()])) + ); + assert!(written.get("rowBoundarySets").is_none()); + + let failure = parse_module_yaml(&module(false)) + .expect_err("a module does not see a set its project declares"); + let [diagnostic] = failure.diagnostics() else { + panic!("one diagnostic refuses the module: {failure:?}"); + }; + assert_eq!(diagnostic.code, REFERENCE_CODE); +} + +#[test] +fn the_authoring_schema_accepts_the_reference_and_the_set_declaration() { + let schema = std::fs::read_to_string( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/breg/generated/authoring/registry-project.schema.json"), + ) + .expect("the generated authoring schema is committed"); + let schema: Value = serde_json::from_str(&schema).unwrap(); + assert!( + schema.pointer("/properties/rowBoundarySets").is_some(), + "the project schema declares rowBoundarySets" + ); + let text = schema.to_string(); + assert!( + text.contains("\"rowBoundarySet\""), + "the schema describes the reference mapping" + ); +} diff --git a/crates/registry-bregctl/src/explain_report.rs b/crates/registry-bregctl/src/explain_report.rs index 0d3b74d036..51cef5e916 100644 --- a/crates/registry-bregctl/src/explain_report.rs +++ b/crates/registry-bregctl/src/explain_report.rs @@ -167,12 +167,20 @@ pub(crate) fn actions(value: &Value, lines: &mut Lines) { } } if let Some(comparison) = guard.get("currentDate") { - let offset = guard["currentDateOffsetDays"] - .as_i64() - .filter(|days| *days != 0); + let offset = [ + ("currentDateOffsetDays", "days"), + ("currentDateOffsetMonths", "months"), + ] + .into_iter() + .find_map(|(key, unit)| { + guard[key] + .as_i64() + .filter(|amount| *amount != 0) + .map(|amount| (amount, unit)) + }); terms.push(match (comparison.as_str(), offset) { - (Some(comparison), Some(days)) => { - format!("current date {comparison} ({days:+} days)") + (Some(comparison), Some((amount, unit))) => { + format!("current date {comparison} ({amount:+} {unit})") } _ => format!("current date {comparison}"), }); @@ -639,6 +647,27 @@ mod tests { ); } + #[test] + fn action_summary_names_a_current_date_month_offset() { + let value = json!([{ + "id":"renew", "execution":{"mode":"immediate"}, "inputs":[], + "plan":{"effects":[]}, + "commitGuards":[{ + "input":"licence", "field":"valid-through", "revisionUnchanged":false, + "currentDate":"on-or-before", "currentDateOffsetMonths":-3 + }], + "permissions":[] + }]); + let mut lines = Lines::new(); + actions(&value, &mut lines); + let rendered = lines.finish(); + let text = rendered.split_whitespace().collect::>().join(" "); + assert!( + text.contains("current date on-or-before (-3 months)"), + "{rendered}" + ); + } + #[test] fn permission_gates_quote_literal_identifiers_and_label_empty_lists() { for identifiers in [ diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 52315a9ea4..66e254f5ad 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -59,6 +59,7 @@ mod identity_facts; mod import_authority_lifecycle; mod init_from_model; mod instance_claim_lifecycle; +mod migration_draft; mod module_lock_patch; mod package_inspection; mod package_lifecycle; @@ -1593,6 +1594,16 @@ enum MigrationCommand { /// Assess a Registry pinned by a failed activation, and execute only the safe transition it names. Reconcile(MigrationReconcileArgs), + + /// Write the reviewed migration directory for a successor whose changes need no SQL. + /// + /// Covers every access or disclosure change against the baseline package, + /// measures the candidate on the disposable database the runtime + /// configuration names, and writes descriptor.json and rehearsal.json + /// under /modules//migrations/. Pass as + /// --reviewed-migrations to test and package. Never overwrites an existing + /// migration. + Draft(MigrationDraftArgs), } #[derive(Debug, Subcommand)] @@ -1630,6 +1641,33 @@ struct MigrationReconcileArgs { execute: bool, } +#[derive(Debug, Args)] +struct MigrationDraftArgs { + /// Base Registry Engine project directory. + #[arg(value_name = "PROJECT")] + project: PathBuf, + + /// Absolute directory of the chain tip package the successor follows. + #[arg(long, value_name = "ABSOLUTE_DIRECTORY")] + baseline_package: PathBuf, + + /// Runtime configuration file of the disposable schema-test database. + #[arg(long, value_name = "ABSOLUTE_FILE")] + runtime_config: PathBuf, + + /// Absolute reviewed-migrations directory the draft is written under. + #[arg(long, value_name = "ABSOLUTE_DIRECTORY")] + output: PathBuf, + + /// Module the migration directory belongs to. + #[arg(long, value_name = "LOCAL_ID")] + module: String, + + /// Identifier of the migration, also its directory name. + #[arg(long, value_name = "LOCAL_ID")] + id: String, +} + #[derive(Debug, Args)] struct HistoryEraseArgs { /// Runtime configuration file. @@ -2185,6 +2223,21 @@ struct MigrationExplainSuccessReport { plan: MigrationInspectionSummary, } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct MigrationDraftSuccessReport { + ok: bool, + command: &'static str, + /// The migration directory, relative to --output. + directory: String, + change_class: registry_breg::package::CompiledRegistryChangeClass, + covers: Vec, + plan_digest: String, + prior_package_digest: String, + final_schema_fingerprint: String, + postgres_major: u16, +} + #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct MigrationReconcileSuccessReport { @@ -3164,6 +3217,12 @@ where Err(failure) => write_failure(&failure, format, stdout, stderr), }; } + MigrationCommand::Draft(args) => { + return match migration_draft(&args) { + Ok(report) => write_migration_draft_success(&report, format, stdout, stderr), + Err(refusal) => write_refusal(&refusal, format, stdout, stderr), + }; + } }, Command::History(args) => match args.command { HistoryCommand::Erase(args) => { @@ -7864,6 +7923,28 @@ fn migration_explain( }) } +fn migration_draft(args: &MigrationDraftArgs) -> Result { + let drafted = migration_draft::run(&migration_draft::DraftRequest { + project: &args.project, + baseline_package: &args.baseline_package, + runtime_config: &args.runtime_config, + output: &args.output, + module: &args.module, + id: &args.id, + })?; + Ok(MigrationDraftSuccessReport { + ok: true, + command: migration_draft::COMMAND, + directory: drafted.directory, + change_class: registry_breg::package::CompiledRegistryChangeClass::AccessOrDisclosureChange, + covers: drafted.covers, + plan_digest: drafted.plan_digest, + prior_package_digest: drafted.prior_package_digest, + final_schema_fingerprint: drafted.final_schema_fingerprint, + postgres_major: drafted.postgres_major, + }) +} + fn migration_reconcile( args: &MigrationReconcileArgs, ) -> Result { @@ -14205,6 +14286,58 @@ fn write_migration_explain_success( } } +fn write_migration_draft_success( + report: &MigrationDraftSuccessReport, + format: OutputFormat, + stdout: &mut dyn Write, + stderr: &mut dyn Write, +) -> ExitCode { + let result = if format == OutputFormat::Json { + write_ctl_report(&mut *stdout, report) + .map_err(io::Error::other) + .and_then(|()| writeln!(stdout)) + } else { + write_migration_draft_human(report, stdout) + }; + write_result(result, stderr) +} + +fn write_migration_draft_human( + report: &MigrationDraftSuccessReport, + stdout: &mut dyn Write, +) -> io::Result<()> { + let mut lines = report::Lines::new(); + lines.lead(&format!( + "Drafted a reviewed migration covering {}.", + report::counted(report.covers.len(), "change") + )); + lines.pairs(&[ + ("directory", report.directory.clone()), + ("plan digest", report.plan_digest.clone()), + ("prior package digest", report.prior_package_digest.clone()), + ( + "final schema fingerprint", + report.final_schema_fingerprint.clone(), + ), + ("postgres major", report.postgres_major.to_string()), + ]); + for cover in &report.covers { + let target = [ + cover.target.record_type_id.as_deref(), + cover.target.member_id.as_deref(), + ] + .into_iter() + .flatten() + .collect::>() + .join("."); + lines.pairs(&[( + "covers", + format!("{} at {target}", change_code_name(cover.code)), + )]); + } + stdout.write_all(lines.finish().as_bytes()) +} + fn write_migration_reconcile_success( report: &MigrationReconcileSuccessReport, format: OutputFormat, diff --git a/crates/registry-bregctl/src/migration_draft.rs b/crates/registry-bregctl/src/migration_draft.rs new file mode 100644 index 0000000000..556e4bf939 --- /dev/null +++ b/crates/registry-bregctl/src/migration_draft.rs @@ -0,0 +1,613 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `bregctl migration draft`: write the reviewed migration directory for a +//! successor whose changes need no SQL. +//! +//! The descriptor covers exactly the changes that are not compatible-additive, +//! and the rehearsal receipt binds the predecessor package, the descriptor's +//! digest, and the fingerprint and PostgreSQL major the candidate measures on +//! the disposable database. The package validator still decides coverage and +//! evidence when the directory is passed as `--reviewed-migrations`. +//! +//! Every refusal that depends only on the arguments, the project, and the +//! baseline package happens before the runtime configuration is read or any +//! database is opened. + +use std::collections::BTreeSet; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use registry_breg::migration_plan::{ + covers_are_metadata_only, read_migration_descriptor, read_rehearsal_receipt, + MigrationRehearsalReceipt, ReviewedChangeCover, ReviewedMigrationDescriptor, + ReviewedMigrationRecovery, +}; +use registry_breg::package::{CompiledRegistryChange, CompiledRegistryChangeClass}; +use registry_platform_canonical_json::canonicalize_json; +use registry_platform_yaml::LocalId; +use sha2::{Digest, Sha256}; + +use crate::safe_path::{SafeDir, SafeEntry, SafePathError}; +use crate::{ + baseline_package_failure, candidate_failure, canonicalize_project_path, + capture_resolved_project_source, compile_captured_project, has_parent_component, + inspect_baseline_package, rendered_changes, test_lifecycle, DiagnosticArtifact, FailureReport, + PackageCandidateArgs, ProfileArg, Refusal, SuggestedAction, +}; + +pub(crate) const COMMAND: &str = "migration draft"; + +const DESCRIPTOR_FILE: &str = "descriptor.json"; +const RECEIPT_FILE: &str = "rehearsal.json"; +const LOCK_TIMEOUT_MILLISECONDS: u64 = 1_000; +const STATEMENT_TIMEOUT_MILLISECONDS: u64 = 60_000; + +pub(crate) struct DraftRequest<'a> { + pub project: &'a Path, + pub baseline_package: &'a Path, + pub runtime_config: &'a Path, + pub output: &'a Path, + pub module: &'a str, + pub id: &'a str, +} + +/// What was written, for the success report. +#[derive(Debug)] +pub(crate) struct Drafted { + pub directory: String, + pub covers: Vec, + pub plan_digest: String, + pub prior_package_digest: String, + pub final_schema_fingerprint: String, + pub postgres_major: u16, +} + +/// Why the changes cannot be drafted. +#[derive(Debug, Eq, PartialEq)] +enum CoverRefusal { + NothingToReview, + Unsupported(String), + SqlRequired(String), +} + +/// The two documents of one drafted migration, as canonical JSON. +#[derive(Debug)] +struct Documents { + descriptor: Vec, + receipt: Vec, + plan_digest: String, +} + +struct Measured<'a> { + prior_package_digest: &'a str, + prior_schema_fingerprint: &'a str, + final_schema_fingerprint: &'a str, + postgres_major: u16, +} + +pub(crate) fn run(request: &DraftRequest<'_>) -> Result { + let (module, id) = checked_identifiers(request)?; + let output = preflight_output(request.output, &module, &id)?; + let selected_project = canonicalize_project_path(request.project).map_err(|diagnostic| { + crate::source_failure( + COMMAND, + diagnostic, + DiagnosticArtifact::RegistryProject, + SuggestedAction::CorrectAuthoringSource, + ) + })?; + let source = capture_resolved_project_source(&selected_project).map_err(|diagnostic| { + crate::source_failure( + COMMAND, + diagnostic, + DiagnosticArtifact::RegistryProject, + SuggestedAction::CorrectAuthoringSource, + ) + })?; + let compiled = compile_captured_project(&source, ProfileArg::Production, COMMAND)?; + if !source + .modules + .iter() + .any(|captured| captured.id.as_str() == module) + { + return Err(candidate_failure( + COMMAND, + "migration.draft.module-unknown", + "module", + &format!("the project has no module `{module}`; name one of its modules with --module"), + DiagnosticArtifact::CommandArguments, + SuggestedAction::CorrectCommandUsage, + ) + .into()); + } + let baseline = inspect_baseline_package(request.baseline_package) + .map_err(|error| baseline_package_failure(COMMAND, error))?; + if baseline.package_id() != compiled.registry_id() { + return Err(candidate_failure( + COMMAND, + "package.baseline.identity", + "baselinePackage", + "the baseline package belongs to another registry; name this registry's chain tip package directory with --baseline-package", + DiagnosticArtifact::VerifiedPackage, + SuggestedAction::CorrectPackageBuild, + ) + .into()); + } + let changes = registry_breg::package::compiled_registry_change_set_from_baseline( + baseline.migration_baseline(), + &compiled, + baseline.package_digest(), + ); + let covers = plan_covers(&changes.changes).map_err(|refusal| cover_failure(&refusal))?; + + // A fresh install of the same project measures the fingerprint and + // PostgreSQL major the receipt records, the way `test --fingerprint-only` + // does. + let candidate = crate::capture_candidate( + &PackageCandidateArgs { + project: request.project.to_path_buf(), + baseline_package: None, + reviewed_migrations: None, + }, + COMMAND, + false, + false, + )?; + if candidate.registry().revision() != compiled.revision() { + return Err(candidate_failure( + COMMAND, + "migration.draft.project-changed", + "project", + "the project changed while the draft was being prepared; run the command again", + DiagnosticArtifact::RegistryProject, + SuggestedAction::CorrectAuthoringSource, + ) + .into()); + } + let measurement = + test_lifecycle::measure(candidate, request.runtime_config).map_err(|error| { + let mut failure = crate::test_lifecycle_failure(error); + failure.command = COMMAND; + failure + })?; + + let documents = build_documents( + &module, + &id, + &covers, + &Measured { + prior_package_digest: baseline.package_digest(), + prior_schema_fingerprint: baseline.schema_fingerprint(), + final_schema_fingerprint: &measurement.schema_fingerprint, + postgres_major: measurement.postgres_major, + }, + ) + .map_err(|message| { + candidate_failure( + COMMAND, + "migration.draft.document-refused", + "output", + &message, + DiagnosticArtifact::DatabaseMigration, + SuggestedAction::CorrectPackageBuild, + ) + })?; + publish(&output, &module, &id, &documents)?; + Ok(Drafted { + directory: relative_directory(&module, &id), + covers, + plan_digest: documents.plan_digest, + prior_package_digest: baseline.package_digest().to_owned(), + final_schema_fingerprint: measurement.schema_fingerprint, + postgres_major: measurement.postgres_major, + }) +} + +fn relative_directory(module: &str, id: &str) -> String { + format!("modules/{module}/migrations/{id}") +} + +fn checked_identifiers(request: &DraftRequest<'_>) -> Result<(String, String), FailureReport> { + let local_id = |value: &str, path: &str, flag: &str| { + LocalId::new(value).map(LocalId::into_string).map_err(|_| { + candidate_failure( + COMMAND, + "migration.draft.id-invalid", + path, + &format!( + "{flag} must be a local identifier: lowercase letters, digits, `-` and `_`, starting with a letter, at most 64 characters" + ), + DiagnosticArtifact::CommandArguments, + SuggestedAction::CorrectCommandUsage, + ) + }) + }; + Ok(( + local_id(request.module, "module", "--module")?, + local_id(request.id, "id", "--id")?, + )) +} + +/// The changes the descriptor covers, or the reason they cannot be drafted. +/// A draft has no steps, no assertions, and no backup binding, so it can only +/// review access and disclosure changes that alter no table, column, or +/// index. +fn plan_covers( + changes: &[CompiledRegistryChange], +) -> Result, CoverRefusal> { + let describe = + |change: &CompiledRegistryChange| rendered_changes(std::slice::from_ref(change), |_| true); + if let Some(change) = changes + .iter() + .find(|change| change.class == CompiledRegistryChangeClass::Unsupported) + { + return Err(CoverRefusal::Unsupported(describe(change))); + } + let reviewable = changes + .iter() + .filter(|change| change.class != CompiledRegistryChangeClass::CompatibleAdditive) + .collect::>(); + if reviewable.is_empty() { + return Err(CoverRefusal::NothingToReview); + } + for change in &reviewable { + let needs_more = change.class != CompiledRegistryChangeClass::AccessOrDisclosureChange + || !covers_are_metadata_only(&[ReviewedChangeCover::from(*change)]); + if needs_more { + return Err(CoverRefusal::SqlRequired(describe(change))); + } + } + Ok(reviewable + .into_iter() + .map(ReviewedChangeCover::from) + .collect::>() + .into_iter() + .collect()) +} + +fn cover_failure(refusal: &CoverRefusal) -> FailureReport { + match refusal { + CoverRefusal::NothingToReview => candidate_failure( + COMMAND, + "migration.draft.nothing-to-review", + "candidate", + "every change against the baseline is compatible-additive, so no reviewed migration is needed; run test and package without --reviewed-migrations", + DiagnosticArtifact::CompiledDiff, + SuggestedAction::ReviewCompiledDiff, + ), + CoverRefusal::Unsupported(change) => candidate_failure( + COMMAND, + "migration.change.unsupported", + "candidate", + &format!( + "the migration planner does not support this successor change: {change}. Inspect diff and revise the candidate. Reviewed artifacts cannot authorize unsupported changes" + ), + DiagnosticArtifact::DatabaseMigration, + SuggestedAction::CorrectPackageBuild, + ), + CoverRefusal::SqlRequired(change) => candidate_failure( + COMMAND, + "migration.draft.sql-required", + "candidate", + &format!( + "this change needs a migration written by hand, with authored SQL, a backup binding, or a descriptor of its own class: {change}. A draft only covers access and disclosure changes that alter no table, column, or index" + ), + DiagnosticArtifact::DatabaseMigration, + SuggestedAction::ReviewCompiledDiff, + ), + } +} + +fn build_documents( + module: &str, + id: &str, + covers: &[ReviewedChangeCover], + measured: &Measured<'_>, +) -> Result { + let directory = relative_directory(module, id); + let descriptor = ReviewedMigrationDescriptor { + id: id.to_owned(), + change_class: CompiledRegistryChangeClass::AccessOrDisclosureChange, + covers: covers.to_vec(), + recovery: ReviewedMigrationRecovery::ExactTargetResume, + lock_timeout_ms: LOCK_TIMEOUT_MILLISECONDS, + statement_timeout_ms: STATEMENT_TIMEOUT_MILLISECONDS, + steps: Vec::new(), + pre_assertions: Vec::new(), + post_assertions: Vec::new(), + rehearsal_receipt_path: format!("{directory}/{RECEIPT_FILE}"), + backup_binding_path: None, + history: None, + }; + let descriptor_bytes = canonical_bytes(&descriptor)?; + let plan_digest = sha256_digest(&descriptor_bytes); + let receipt = MigrationRehearsalReceipt { + prior_package_digest: measured.prior_package_digest.to_owned(), + prior_schema_fingerprint: measured.prior_schema_fingerprint.to_owned(), + plan_sha256: plan_digest.clone(), + sql_sha256: Vec::new(), + assertion_sha256: Vec::new(), + fixture_inventory: Vec::new(), + postgres_major: measured.postgres_major, + row_assertions: Vec::new(), + final_schema_fingerprint: measured.final_schema_fingerprint.to_owned(), + }; + let receipt_bytes = canonical_bytes(&receipt)?; + // The drafted files are read back through the readers the package + // validator uses, so a draft that would be refused is never written. + read_migration_descriptor(&format!("{directory}/{DESCRIPTOR_FILE}"), &descriptor_bytes) + .map_err(|_| "the drafted descriptor was refused by the descriptor reader".to_owned())?; + read_rehearsal_receipt(&format!("{directory}/{RECEIPT_FILE}"), &receipt_bytes) + .map_err(|_| "the drafted receipt was refused by the receipt reader".to_owned())?; + Ok(Documents { + descriptor: descriptor_bytes, + receipt: receipt_bytes, + plan_digest, + }) +} + +fn canonical_bytes(document: &impl serde::Serialize) -> Result, String> { + let value = serde_json::to_value(document) + .map_err(|_| "the drafted document does not serialize".to_owned())?; + canonicalize_json(&value).map_err(|_| "the drafted document does not canonicalize".to_owned()) +} + +fn sha256_digest(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + let mut text = String::with_capacity(71); + text.push_str("sha256:"); + for byte in digest { + text.push_str(&format!("{byte:02x}")); + } + text +} + +/// The migration directory's path under `output`, checked before anything is +/// measured: an unsafe or relative output, or an existing migration of the +/// same id, is refused with nothing written. +fn preflight_output(output: &Path, module: &str, id: &str) -> Result { + let invalid = |detail: &str| { + candidate_failure( + COMMAND, + "migration.draft.output-invalid", + "output", + &format!( + "--output must be an absolute directory path without parent traversal or symbolic links: {detail}" + ), + DiagnosticArtifact::SchemaTestOutput, + SuggestedAction::ChooseSafeOutputDirectory, + ) + }; + if !output.is_absolute() || has_parent_component(output) { + return Err(invalid("the path is relative or traverses a parent")); + } + let exists = candidate_failure( + COMMAND, + "migration.draft.output-exists", + "output", + &format!( + "{} already exists under --output; a draft never overwrites a reviewed migration. Choose another --id or review the existing directory", + relative_directory(module, id) + ), + DiagnosticArtifact::SchemaTestOutput, + SuggestedAction::ChooseSafeOutputDirectory, + ); + let mut directory = match SafeDir::resolve(output) { + Ok(directory) => directory, + // Nothing exists yet, so nothing can collide. Publication creates the + // missing directories. + Err(SafePathError::NotFound) => return Ok(output.to_path_buf()), + Err(_) => return Err(invalid("the path cannot be resolved safely")), + }; + for name in ["modules", module, "migrations"] { + match directory.open_directory(name.as_ref()) { + Ok(next) => directory = next, + Err(SafePathError::NotFound) => return Ok(output.to_path_buf()), + Err(_) => return Err(invalid("a component is not a plain directory")), + } + } + match directory.entry_exists(id.as_ref()) { + Ok(true) => Err(exists), + Ok(false) => Ok(output.to_path_buf()), + Err(_) => Err(invalid("the migration directory cannot be inspected")), + } +} + +/// Create `modules//migrations/` under `output` and write both +/// documents into it. The final directory is created exclusively, so a +/// concurrent draft of the same id is refused rather than overwritten. +fn publish( + output: &Path, + module: &str, + id: &str, + documents: &Documents, +) -> Result<(), FailureReport> { + let unwritable = |detail: &str| { + candidate_failure( + COMMAND, + "migration.draft.output-unavailable", + "output", + &format!( + "the drafted migration could not be written ({detail}). Remove {} if it was partly written, then run the command again", + relative_directory(module, id) + ), + DiagnosticArtifact::SchemaTestOutput, + SuggestedAction::ChooseSafeOutputDirectory, + ) + }; + let entry = SafeEntry::resolve(output).map_err(|_| unwritable("the output path"))?; + let mut directory = entry + .parent() + .open_or_create_directory(entry.name(), 0o777) + .map_err(|_| unwritable("the output directory"))?; + for name in ["modules", module, "migrations"] { + directory = directory + .open_or_create_directory(name.as_ref(), 0o777) + .map_err(|_| unwritable("a parent directory"))?; + } + match directory.create_directory(id.as_ref(), 0o777) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + return Err(candidate_failure( + COMMAND, + "migration.draft.output-exists", + "output", + &format!( + "{} already exists under --output; a draft never overwrites a reviewed migration", + relative_directory(module, id) + ), + DiagnosticArtifact::SchemaTestOutput, + SuggestedAction::ChooseSafeOutputDirectory, + )); + } + Err(_) => return Err(unwritable("the migration directory")), + } + let migration = directory + .open_directory(id.as_ref()) + .map_err(|_| unwritable("the migration directory"))?; + for (name, bytes) in [ + (DESCRIPTOR_FILE, &documents.descriptor), + (RECEIPT_FILE, &documents.receipt), + ] { + let mut file = migration + .create_new(name.as_ref(), 0o666) + .map_err(|_| unwritable(name))?; + file.write_all(bytes) + .and_then(|()| file.sync_all()) + .map_err(|_| unwritable(name))?; + } + migration.sync().map_err(|_| unwritable("the directory")) +} + +#[cfg(test)] +mod tests { + use super::*; + use registry_breg::package::{ + CompiledRegistryChangeCode, CompiledRegistryChangeTarget, CompiledRegistryChangeTargetKind, + }; + + const PRIOR_DIGEST: &str = + "sha256:1111111111111111111111111111111111111111111111111111111111111111"; + const PRIOR_FINGERPRINT: &str = + "sha256:2222222222222222222222222222222222222222222222222222222222222222"; + const FINAL_FINGERPRINT: &str = + "sha256:3333333333333333333333333333333333333333333333333333333333333333"; + + fn change( + class: CompiledRegistryChangeClass, + code: CompiledRegistryChangeCode, + member: &str, + ) -> CompiledRegistryChange { + CompiledRegistryChange { + class, + code, + target: CompiledRegistryChangeTarget { + kind: CompiledRegistryChangeTargetKind::RecordType, + record_type_id: Some("record".to_owned()), + member_id: Some(member.to_owned()), + }, + } + } + + fn access_change(member: &str) -> CompiledRegistryChange { + change( + CompiledRegistryChangeClass::AccessOrDisclosureChange, + CompiledRegistryChangeCode::AccessProfileChanged, + member, + ) + } + + fn measured() -> Measured<'static> { + Measured { + prior_package_digest: PRIOR_DIGEST, + prior_schema_fingerprint: PRIOR_FINGERPRINT, + final_schema_fingerprint: FINAL_FINGERPRINT, + postgres_major: 17, + } + } + + #[test] + fn covers_are_the_sorted_changes_that_are_not_compatible_additive() { + let additive = change( + CompiledRegistryChangeClass::CompatibleAdditive, + CompiledRegistryChangeCode::FieldAddedOptional, + "extra", + ); + let covers = plan_covers(&[access_change("zeta"), additive, access_change("alpha")]) + .expect("access changes are draftable"); + let members = covers + .iter() + .map(|cover| cover.target.member_id.as_deref().expect("member")) + .collect::>(); + assert_eq!(members, ["alpha", "zeta"]); + } + + #[test] + fn a_change_set_without_reviewable_changes_has_nothing_to_review() { + let additive = change( + CompiledRegistryChangeClass::CompatibleAdditive, + CompiledRegistryChangeCode::FieldAddedOptional, + "extra", + ); + assert_eq!(plan_covers(&[additive]), Err(CoverRefusal::NothingToReview)); + assert_eq!(plan_covers(&[]), Err(CoverRefusal::NothingToReview)); + } + + #[test] + fn a_change_outside_the_access_class_needs_a_handwritten_migration() { + let removed = change( + CompiledRegistryChangeClass::DestructiveOrIrreversible, + CompiledRegistryChangeCode::FieldRemoved, + "code", + ); + let Err(CoverRefusal::SqlRequired(named)) = plan_covers(&[access_change("alpha"), removed]) + else { + panic!("a removed field needs a hand-written migration"); + }; + assert!(named.contains("field-removed"), "{named}"); + } + + #[test] + fn descriptor_bytes_are_canonical_and_the_receipt_binds_their_digest() { + let covers = plan_covers(&[access_change("alpha")]).expect("draftable"); + let documents = + build_documents("core", "widen", &covers, &measured()).expect("documents build"); + + let descriptor: serde_json::Value = + serde_json::from_slice(&documents.descriptor).expect("descriptor is JSON"); + assert_eq!( + canonicalize_json(&descriptor).expect("canonicalizes"), + documents.descriptor, + "the descriptor file is its own canonical form" + ); + assert_eq!(documents.plan_digest, sha256_digest(&documents.descriptor)); + assert_eq!(descriptor["changeClass"], "access-or-disclosure-change"); + assert_eq!(descriptor["steps"], serde_json::json!([])); + assert_eq!(descriptor["preAssertions"], serde_json::json!([])); + assert_eq!(descriptor["postAssertions"], serde_json::json!([])); + assert_eq!( + descriptor["rehearsalReceiptPath"], + "modules/core/migrations/widen/rehearsal.json" + ); + + let receipt: serde_json::Value = + serde_json::from_slice(&documents.receipt).expect("receipt is JSON"); + assert_eq!(receipt["planDigest"], documents.plan_digest.as_str()); + assert_eq!(receipt["priorPackageDigest"], PRIOR_DIGEST); + assert_eq!(receipt["priorSchemaFingerprint"], PRIOR_FINGERPRINT); + assert_eq!(receipt["finalSchemaFingerprint"], FINAL_FINGERPRINT); + assert_eq!(receipt["postgresMajor"], 17); + assert_eq!( + canonicalize_json(&receipt).expect("canonicalizes"), + documents.receipt + ); + } + + #[test] + fn a_draft_is_deterministic() { + let covers = plan_covers(&[access_change("alpha")]).expect("draftable"); + let first = build_documents("core", "widen", &covers, &measured()).expect("first builds"); + let second = build_documents("core", "widen", &covers, &measured()).expect("second builds"); + assert_eq!(first.descriptor, second.descriptor); + assert_eq!(first.receipt, second.receipt); + } +} diff --git a/crates/registry-bregctl/src/reviewed_migrations.rs b/crates/registry-bregctl/src/reviewed_migrations.rs index a5496dfd02..07908e73d7 100644 --- a/crates/registry-bregctl/src/reviewed_migrations.rs +++ b/crates/registry-bregctl/src/reviewed_migrations.rs @@ -137,7 +137,7 @@ pub(crate) fn capture(root: &Path) -> Result { }); } let declared_schema_fingerprint = declared_schema_fingerprint.ok_or_else(|| - refusal("migration.review.receipt", "reviewedMigrations", "provide the referenced rehearsal.json; the CLI does not manufacture migration evidence"))?; + refusal("migration.review.receipt", "reviewedMigrations", "provide the referenced rehearsal.json; the CLI does not manufacture migration evidence for a migration with SQL. For a change that needs no SQL, `bregctl migration draft` writes the descriptor and its measured rehearsal receipt"))?; // Grouped by the bare directory, which can disagree with descriptor-path // order when one directory name is a strict prefix of another (`m0002` // and `m0002-funding-source`): `prepare_reviewed_migration_plan` requires @@ -355,4 +355,25 @@ mod ordering_tests { the key prepare_reviewed_migration_plan checks" ); } + + #[test] + fn a_missing_receipt_names_the_draft_command_for_changes_without_sql() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().canonicalize().unwrap(); + let dir = root.join("modules/core/migrations/m0001"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("descriptor.json"), minimal_descriptor("m0001")).unwrap(); + + let CaptureRefusal::Tool(refused) = + capture(&root).expect_err("a descriptor without its receipt is refused") + else { + panic!("a missing receipt is the command's own diagnostic"); + }; + assert_eq!(refused.code, "migration.review.receipt"); + assert!( + refused.message.contains("bregctl migration draft"), + "{}", + refused.message + ); + } } diff --git a/crates/registry-bregctl/src/test_lifecycle.rs b/crates/registry-bregctl/src/test_lifecycle.rs index 8b19d5136a..1e499070d0 100644 --- a/crates/registry-bregctl/src/test_lifecycle.rs +++ b/crates/registry-bregctl/src/test_lifecycle.rs @@ -75,6 +75,7 @@ pub(crate) struct TestLifecycleOutcome { pub(crate) struct SchemaMeasurement { pub registry_revision: String, pub schema_fingerprint: String, + pub postgres_major: u16, } /// The receipt destination, held as its resolved parent descriptor plus the @@ -341,11 +342,12 @@ pub(crate) fn measure( .enable_all() .build() .map_err(|_| TestLifecycleError::Runtime)?; - let schema_fingerprint = runtime.block_on(async { - startup::rehearse_schema_fingerprint(&config, candidate.registry()) + let installed = runtime.block_on(async { + startup::measure_schema_install(&config, candidate.registry()) .await .map_err(schema_preparation_error) })?; + let schema_fingerprint = installed.fingerprint; let prepared = candidate .prepare(schema_fingerprint.clone()) .map_err(|error| TestLifecycleError::Candidate { @@ -355,6 +357,7 @@ pub(crate) fn measure( Ok(SchemaMeasurement { registry_revision: prepared.registry().revision().to_owned(), schema_fingerprint, + postgres_major: installed.postgres_major, }) } diff --git a/crates/registry-bregctl/tests/cli.rs b/crates/registry-bregctl/tests/cli.rs index 729f89caea..467eef98e5 100644 --- a/crates/registry-bregctl/tests/cli.rs +++ b/crates/registry-bregctl/tests/cli.rs @@ -2883,7 +2883,18 @@ fn facility_starter_checks_clean_with_warnings_denied() { .unwrap() .iter() .any(|operation| operation == "get")); - assert_eq!(operator["rowBoundaries"].as_array().unwrap().len(), 1); + // The template writes the boundary once, as a set, and the grant refers to it. + assert_eq!( + operator["rowBoundaries"], + json!({"rowBoundarySet": "same-jurisdiction"}) + ); + assert_eq!( + registry["rowBoundarySets"]["same-jurisdiction"] + .as_array() + .unwrap() + .len(), + 1 + ); let checked = bregctl(&[ "--format", diff --git a/crates/registry-bregctl/tests/migration_draft.rs b/crates/registry-bregctl/tests/migration_draft.rs new file mode 100644 index 0000000000..42729172d9 --- /dev/null +++ b/crates/registry-bregctl/tests/migration_draft.rs @@ -0,0 +1,341 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `bregctl migration draft` refuses before it opens any database, and never +//! overwrites a reviewed migration it already wrote. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use registry_breg::compiler::module_digest; +use registry_breg::contract::parse_module_json; +use registry_breg::fixtures::validate_fixture_journeys; +use registry_breg::package::{ + prepare_package, PackageBuildRequest, PackageMigrationPlanInput, PackageModuleSource, + PackageSourceFile, +}; +use serde_json::Value; + +const SOURCE_REVISION: &str = "compiler-source-revision"; +const FIXTURE_JOURNEYS: &[u8] = br#"apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: draft-record-list + steps: + - id: list-records + recordType: record + accessProfile: reader + claims: {principal: draft-reader} + request: {type: list} + expect: {outcome: success, status: 200, count: 0} +"#; +// Refusals happen before the runtime configuration is read, so a path that +// does not exist proves no refusal opened a database. +const UNREAD_RUNTIME_CONFIG: &str = "/nonexistent-runtime-config-is-never-read.yaml"; +static TEMPORARY_COUNTER: AtomicU64 = AtomicU64::new(0); + +struct TestDirectory { + path: PathBuf, +} + +impl TestDirectory { + fn create() -> Self { + let path = std::env::current_dir() + .expect("current directory is available") + .join(format!( + "bregctl-draft-test-{}-{}", + std::process::id(), + TEMPORARY_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).expect("test directory is created"); + Self { path } + } +} + +impl Drop for TestDirectory { + fn drop(&mut self) { + if self + .path + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("bregctl-draft-test-")) + && self.path.exists() + { + fs::remove_dir_all(&self.path).expect("test directory is removed"); + } + } +} + +fn publish_package(parent: &Path, name: &str, classification: &str) -> PublishedPackage { + let module_bytes = module_bytes(classification); + let module = parse_module_json(&module_bytes).expect("package module parses"); + let project_bytes = project_bytes(&module_digest(&module)); + let prepared = prepare_package(PackageBuildRequest { + from_package_digest: None, + compiler_source_revision: SOURCE_REVISION.to_owned(), + schema_fingerprint: + "sha256:2222222222222222222222222222222222222222222222222222222222222222".to_owned(), + project: PackageSourceFile { + path: "source/registry.yaml".to_owned(), + bytes: project_bytes, + }, + modules: vec![PackageModuleSource { + id: "core".to_owned(), + path: "source/modules/core/module.yaml".to_owned(), + bytes: module_bytes, + assets: Vec::new(), + }], + fixture_journeys: PackageSourceFile { + path: "tests/journeys.yaml".to_owned(), + bytes: FIXTURE_JOURNEYS.to_vec(), + }, + migration_plan: PackageMigrationPlanInput::InitialCompiledDdl, + }) + .expect("package prepares"); + validate_fixture_journeys(FIXTURE_JOURNEYS, prepared.registry()) + .expect("diff fixture journeys resolve against the packaged registry"); + let package = parent.join(name); + prepared + .publish_to_directory(&package) + .expect("package publishes"); + PublishedPackage { package } +} + +fn write_project(parent: &Path, name: &str, classification: &str) -> PathBuf { + write_project_with_module(parent, name, module_bytes(classification)) +} + +fn write_project_with_module(parent: &Path, name: &str, module: Vec) -> PathBuf { + let root = parent.join(name); + let parsed = parse_module_json(&module).expect("candidate module parses"); + fs::create_dir_all(root.join("modules/core")).expect("candidate directories create"); + fs::write( + root.join("registry.yaml"), + project_bytes(&module_digest(&parsed)), + ) + .expect("candidate project writes"); + fs::write(root.join("modules/core/module.yaml"), module).expect("candidate module writes"); + root +} + +fn project_bytes(module_digest: &str) -> Vec { + format!( + r#"{{"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject","project":{{"id":"neutral-registry","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://package.example.test"}},"package":{{"sourceRevision":"{SOURCE_REVISION}"}},"datasets":{{"neutral-registry": {{}}}},"manifestProjection":{{"accessProfile":"reader","classificationCeiling":"restricted","catalog":{{"baseUrl":"https://package.example.test","title":"Neutral Registry Catalog","publisher":{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}}},"authorities":[{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}],"publicService":{{"id":"neutral-registry-service","title":"Neutral Registry Catalog","competentAuthority":"neutral-registry-authority"}},"datasets":[{{"id":"neutral-registry","title":"Neutral Registry Dataset","owner":"Package Test Publisher","status":"active"}}],"dataServices":[{{"id":"neutral-registry-data-service","title":"Neutral Registry Catalog","endpointUrl":"https://package.example.test","servesDatasets":["neutral-registry"]}}]}},"modules":{{"core":{{"version":"1","digest":"{module_digest}"}}}}}}"# + ) + .into_bytes() +} + +fn module_bytes(classification: &str) -> Vec { + format!( + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"record":{{"primaryDataset":"neutral-registry","route":"records","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"{classification}"}}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["get","list"],"readableFields":["code"]}}}}}}}}}}"# + ) + .into_bytes() +} + +fn run(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(arguments) + .output() + .expect("bregctl starts") +} + +fn json_stdout(output: &Output) -> Value { + serde_json::from_slice(&output.stdout).expect("stdout is JSON") +} + +fn path(path: &Path) -> &str { + path.to_str().expect("test path is UTF-8") +} + +struct PublishedPackage { + package: PathBuf, +} + +fn draft(arguments: &[&str]) -> Output { + let mut command = vec!["--format", "json", "migration", "draft"]; + command.extend_from_slice(arguments); + run(&command) +} + +fn refusal_code(output: &Output) -> String { + assert!(!output.status.success(), "{output:?}"); + json_stdout(output)["diagnostics"][0]["code"] + .as_str() + .expect("the refusal names a code") + .to_owned() +} + +#[test] +fn a_change_that_needs_sql_is_refused_before_any_database_access() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let module = String::from_utf8(module_bytes("internal")) + .expect("module is UTF-8") + .replacen(r#""id":"code""#, r#""id":"label""#, 1) + .replacen( + r#""readableFields":["code"]"#, + r#""readableFields":["label"]"#, + 1, + ); + let removal = write_project_with_module(&directory.path, "removal", module.into_bytes()); + let output = directory.path.join("reviewed"); + + let refused = draft(&[ + path(&removal), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + "--id", + "label-rename", + ]); + assert_eq!(refusal_code(&refused), "migration.draft.sql-required"); + let message = json_stdout(&refused)["diagnostics"][0]["message"] + .as_str() + .expect("message is text") + .to_owned(); + assert!(message.contains("field-removed"), "{message}"); + assert!(!output.exists(), "a refusal writes nothing"); +} + +#[test] +fn a_project_with_nothing_to_review_is_refused() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let unchanged = write_project(&directory.path, "unchanged", "internal"); + let output = directory.path.join("reviewed"); + + let refused = draft(&[ + path(&unchanged), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + "--id", + "nothing", + ]); + assert_eq!(refusal_code(&refused), "migration.draft.nothing-to-review"); + assert!(!output.exists(), "a refusal writes nothing"); +} + +#[test] +fn an_unknown_module_is_refused() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let widening = write_project(&directory.path, "widening", "public"); + let output = directory.path.join("reviewed"); + + let refused = draft(&[ + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "no-such-module", + "--id", + "widen", + ]); + assert_eq!(refusal_code(&refused), "migration.draft.module-unknown"); + assert!(!output.exists(), "a refusal writes nothing"); +} + +#[test] +fn an_existing_reviewed_migration_is_never_overwritten() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let widening = write_project(&directory.path, "widening", "public"); + let output = directory.path.join("reviewed"); + let existing = output.join("modules/core/migrations/widen"); + fs::create_dir_all(&existing).expect("the earlier migration directory creates"); + fs::write(existing.join("descriptor.json"), b"reviewed by hand") + .expect("the earlier descriptor writes"); + + let refused = draft(&[ + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + "--id", + "widen", + ]); + assert_eq!(refusal_code(&refused), "migration.draft.output-exists"); + assert_eq!( + fs::read(existing.join("descriptor.json")).expect("the descriptor still reads"), + b"reviewed by hand" + ); + assert!(!existing.join("rehearsal.json").exists()); +} + +#[test] +fn identifiers_and_paths_are_checked_before_the_project_is_read() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let widening = write_project(&directory.path, "widening", "public"); + let output = directory.path.join("reviewed"); + + let bad_id = draft(&[ + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + "--id", + "Not A Local Id", + ]); + assert_eq!(refusal_code(&bad_id), "migration.draft.id-invalid"); + + let relative_output = draft(&[ + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + "reviewed", + "--module", + "core", + "--id", + "widen", + ]); + assert_eq!( + refusal_code(&relative_output), + "migration.draft.output-invalid" + ); + + // Every input is required: a missing --id is a usage error. + let usage = run(&[ + "migration", + "draft", + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + ]); + assert_eq!(usage.status.code(), Some(2), "{usage:?}"); +} diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 8c07a8f4f7..7138f6b15c 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -6431,6 +6431,96 @@ ], "constraints": [], "subcommands": [] + }, + { + "name": "draft", + "invocation": "bregctl migration draft", + "about": "Write the reviewed migration directory for a successor whose changes need no SQL", + "long_about": "Write the reviewed migration directory for a successor whose changes need no SQL. Covers every access or disclosure change against the baseline package, measures the candidate on the disposable database the runtime configuration names, and writes descriptor.json and rehearsal.json under /modules//migrations/. Pass as --reviewed-migrations to test and package. Never overwrites an existing migration.", + "usage": "bregctl migration draft [OPTIONS] --baseline-package --runtime-config --output --module --id ", + "arguments": [ + { + "display": "", + "description": "Base Registry Engine project directory. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--baseline-package ", + "description": "Absolute directory of the chain tip package the successor follows. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--runtime-config ", + "description": "Runtime configuration file of the disposable schema-test database. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--output ", + "description": "Absolute reviewed-migrations directory the draft is written under. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--module ", + "description": "Module the migration directory belongs to", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--id ", + "description": "Identifier of the migration, also its directory name", + "always_required": true, + "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 (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] } ] }, diff --git a/docs/site/src/content/docs/configure/breg-access.mdx b/docs/site/src/content/docs/configure/breg-access.mdx index 8e945811e2..dc2c7a69c9 100644 --- a/docs/site/src/content/docs/configure/breg-access.mdx +++ b/docs/site/src/content/docs/configure/breg-access.mdx @@ -65,8 +65,7 @@ accessProfiles: operations: [create, get, list, patch] readableFields: [operator-code, status, jurisdiction] writableFields: [operator-code, status, jurisdiction] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} ``` When the token fails any of these checks, or the profile does not grant the operation, BReg @@ -125,6 +124,29 @@ under an `in` boundary can move a row between the caller's allowed values, which points out. Write `rowBoundaries: unrestricted` only for deliberately registry-wide authority. +When many grants reach rows the same way, declare the boundaries once under `rowBoundarySets` and +reference the set wherever `rowBoundaries` is written. The facility template declares one set, and +every grant above refers to it: + +```yaml title="registry.yaml" test-excerpt="facility/registry.yaml" +rowBoundarySets: + same-jurisdiction: + - {field: jurisdiction, claim: jurisdiction, operator: equals} +``` + +A reference is the whole value of `rowBoundaries`. It works on record permissions, on Action and +Proposal targets, and in a Record type's `accessRequirements`. Each grant still writes its own +`rowBoundaries`, so the reach of a grant stays visible where it is granted, and a grant that omits +`rowBoundaries` is still refused. References, inline lists, and `unrestricted` can sit side by side +in one profile. + +A set holds at least one boundary. An empty list and `unrestricted` are both refused as a set, +because an empty list would read as every row. Write `unrestricted` on the grant instead. A set is +local to the file that declares it, so a module cannot reference a set from its project. A +reference to a set the file does not declare is refused with +`breg.row-boundary-set.reference-invalid`. BReg expands every reference when it reads the file, so +the compiled package is the same as one that writes each list inline. + A derived field is computed under the same boundaries. A profile that reads one needs a read grant with the same `rowBoundaries` on every other Record type its SQL reads. See [Grant the Record types the SQL reads](../breg/#grant-the-record-types-the-sql-reads). @@ -164,8 +186,7 @@ and the facility grant has no `readPaths` entry: - recordType: facility operations: [get, list] readableFields: [facility-code, name, address-line, city, postal-code, status, jurisdiction] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} ``` Direct operator reads apply the operator permission's jurisdiction boundary. A related read uses @@ -176,8 +197,7 @@ the facility permission's authority instead. Add the optional path grant to see readableFields: [facility-code, name, address-line, city, postal-code, status, jurisdiction] + readPaths: + - {path: operators, readableFields: [operator-code, status, jurisdiction]} - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} ``` Check the edited project: @@ -187,7 +207,7 @@ bregctl check facility ``` ```text test-excerpt -warning[breg.access.profile-related-disclosure] /registry.yaml:237:15 /accessProfiles/facility-reader/permissions/records/1/readPaths/0 +warning[breg.access.profile-related-disclosure] /registry.yaml:241:15 /accessProfiles/facility-reader/permissions/records/1/readPaths/0 profile `facility-reader` can read `operator` records linked to `facility` through `facility-assignment` on read path `operators`; it sees fields jurisdiction, operator-code, status under its own `facility` row boundaries, and access profiles declared for `operator` do not apply next: Remove fields that these readers should not see from this read path's readableFields, or remove the read path; use a direct permission on the related record type when its own row boundaries should apply. 0 errors, 1 warning in 3 files @@ -242,8 +262,7 @@ entry is an alternative set of fields, and a list must pin every field of at lea + requiredFilters: + - fields: [facility-code] + - fields: [city, status] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} ``` With this grant, `GET /v1/records/facilities?$filter=facilityCode eq 'F-001'` runs, and so does diff --git a/docs/site/src/content/docs/configure/breg-actions.mdx b/docs/site/src/content/docs/configure/breg-actions.mdx index 41cd0c4d25..656a97f818 100644 --- a/docs/site/src/content/docs/configure/breg-actions.mdx +++ b/docs/site/src/content/docs/configure/breg-actions.mdx @@ -108,6 +108,45 @@ condition input. When `requiredConditionKeys` is empty, omit `preconditions`. The [immediate Action API contract](../../reference/breg-api/#immediate-actions) gives the request rules. +### Write in one call with `concurrency: current-revision` + +An Action that declares `concurrency: current-revision` sends no condition. The caller invokes it +in one request with no `preconditions`, and the descriptor's `requiredConditionKeys` is empty. +BReg evaluates the commit guards against the Record it locks for the write, and patches that same +row, so a concurrent update is never overwritten. + +```yaml +approve-application: + execution: {mode: immediate, concurrency: current-revision} + commitGuards: + targets: + - {input: application, field: status, equals: submitted, reason: not-submitted} + plan: + type: fixed + effects: + - id: approve + target: {recordType: application, input: application} + operation: patch + set: + status: {value: approved} +``` + +The guard is the only protection against a stale write, so `bregctl check` holds the Action to +these rules: + +- Every Record the Action patches needs an `equals` or `isNull` guard that the Action's own write + makes false. Here the guard wants `submitted` and the write sets `approved`, so a second call + finds the guard false and answers `412`. +- A patch sets constants with `value` or clears a field. It cannot write a value from `fromInput` + or `fromEffect` into an existing Record, because a value the caller chose from a stale view would + overwrite a concurrent update. A create effect can still take caller values. +- A `revision: unchanged` guard is refused, because it needs the condition this mode removes. +- A function plan that writes an existing Record is refused. +- A Proposal cannot declare `concurrency`. + +Omit `concurrency` for the default, which asks the caller for a condition. Turning `current-revision` +on for an existing Action is a reviewed change, because it alters what protects the Record. + A Record type can require a Proposal for an operation: ```yaml title="registry.yaml" test-excerpt="facility/registry.yaml" @@ -395,7 +434,7 @@ The webhook receiver example shows durable acceptance and deduplication for an a ### Shift a date guard by an offset -A date guard may shift the registry-local date by a signed whole-day offset: +A date guard may shift the registry-local date by a signed whole-day offset, or by a signed whole number of calendar months: ```yaml commitGuards: @@ -407,6 +446,20 @@ commitGuards: ``` An absent or zero `currentDateOffsetDays` compares with today. +Use `currentDateOffsetMonths` instead when the window is a calendar span, such as a licence that must be valid for three more months: + +```yaml +commitGuards: + targets: + - input: licence + field: valid-through + currentDate: on-or-after + currentDateOffsetMonths: 3 +``` + +A month offset keeps the day of the month and clamps to the last day of a shorter month, so January 31 plus one month is February 28, or February 29 in a leap year. +`currentDateOffsetMonths` requires `currentDate`, accepts -12000 through 12000, and cannot be combined with `currentDateOffsetDays` on the same guard. +A shift that leaves the years 1 through 9999 fails the guard closed. The bounded offset applies to the same local date for advisory availability and for commit or Proposal Apply re-evaluation. A Proposal Plan evaluates `today()` once, when the Proposal starts. @@ -414,9 +467,10 @@ Its commit guards check `currentDate` again when the Proposal is applied. If approval crosses midnight or takes days, the date the Plan used and the date the guard compares against are different days. Write the guard offset with that gap in mind. -{/* Evidence: crates/registry-breg/src/model.rs current_date_offset_days; - crates/registry-breg/src/immediate_actions.rs current_date_offset_days; - crates/registry-breg/tests/immediate_action_requirements.rs current_date_offset_days. */} +{/* Evidence: crates/registry-breg/src/model.rs current_date_offset_days and current_date_offset_months; + crates/registry-breg/src/immediate_actions.rs current_date_offset_days and current_date_offset_months; + crates/registry-breg/src/commit_guard.rs shift_date; + crates/registry-breg/tests/immediate_action_requirements.rs current_date_offset_days and current_date_offset_months. */} ### Compare a stored field with an input @@ -483,9 +537,26 @@ It returns the observed target revision with `available: true`, or with `availab A guard may declare an optional, stable LocalId `reason` of at most 64 characters. The response exposes it as `guardReason` only when every guard fact and every row-boundary fact for the selected target is readable. The generic `reason` remains `guard-not-satisfied`. +A guard with a `reason` may also declare a `label`, the sentence a person sees when that guard refuses. +`label` is constant display text of at most 256 bytes and is refused without a `reason`: + +```yaml +commitGuards: + targets: + - input: application + field: status + equals: submitted + reason: not-submitted + label: Only a submitted application can be approved. +``` + +The label travels exactly where `guardReason` travels, and nowhere else. +An immediate Action refusal and a Proposal Submit or Apply refusal answer `412 action.guard_failed` with the label as `detail`, and the availability response carries it as `guardLabel`. +The answer for a guard whose facts the caller cannot read stays the fixed `precondition.failed` body, so a label never discloses a hidden guard. +A label is presentation copy: rewording one needs no reviewed migration and does not change the Action revision a frozen Proposal binds. If a declared input needed by a guard is absent, `available` is `null`, the reason is `input-required`, and `missingInputs` names only declared API input names. -If a guard or row boundary depends on a fact the caller cannot read, or the profile lacks Get authority for the target Record type, the answer is `available: null` with `observedRevision: null`, `not-disclosed`, and no `guardReason` or `missingInputs`: +If a guard or row boundary depends on a fact the caller cannot read, or the profile lacks Get authority for the target Record type, the answer is `available: null` with `observedRevision: null`, `not-disclosed`, and no `guardReason`, `guardLabel`, or `missingInputs`: ```json { diff --git a/docs/site/src/content/docs/operate/breg-changes.mdx b/docs/site/src/content/docs/operate/breg-changes.mdx index 880f167012..a7598b6df2 100644 --- a/docs/site/src/content/docs/operate/breg-changes.mdx +++ b/docs/site/src/content/docs/operate/breg-changes.mdx @@ -144,7 +144,9 @@ require a frozen Proposal to be rebased even when the migration needs no review. crates/registry-breg/src/package.rs, compare_actions(); crates/registry-breg/tests/refactor_contract.rs. */} -A reviewed migration is a directory you write and keep beside the project. Each migration lives at +A reviewed migration is a directory you keep beside the project. When every change is an access or +disclosure change that touches no table, column, or index, [draft it with `bregctl`](#draft-a-migration-that-needs-no-sql). +Otherwise you write it. Each migration lives at `modules//migrations//` and holds a `descriptor.json`, a `rehearsal.json`, and any SQL steps, assertions, or fixtures the descriptor names. Every path inside it is relative to the directory root. The descriptor covers exactly the changes `diff` reported that are not compatible @@ -180,8 +182,8 @@ lists every key with its values and bounds. The rehearsal receipt, `rehearsal.json`, binds the migration to the exact baseline and candidate: the prior package digest and schema fingerprint, the descriptor's `planDigest`, the digest of every SQL file and fixture, the PostgreSQL major version, the row counts your rehearsal observed, and the -candidate's final schema fingerprint. You write it from your own rehearsal; `bregctl` checks it and -does not generate it. Two commands give you the values it needs: +candidate's final schema fingerprint. For a migration with SQL you write it from your own +rehearsal, and `bregctl` checks it. Two commands give you the values it needs: ```sh test-skip="needs the reader's reviewed migration directory and disposable database" jq -jcS . descriptor.json | shasum -a 256 @@ -198,6 +200,40 @@ fingerprint, and rolls back without writing a receipt. crates/registry-bregctl/src/test_lifecycle.rs, measure(). Refusal and descriptor observed with bregctl 0.42.0 on a disposable PostgreSQL 17. */} +## Draft a migration that needs no SQL + +`bregctl migration draft` writes the descriptor and the rehearsal receipt for a successor whose +changes are all access or disclosure changes that alter no table, column, or index, such as an +access profile, a route, a query, or an Action. It covers every change that is not compatible +additive, installs the candidate on the disposable database to measure its schema fingerprint and +the PostgreSQL major version, and binds both to the verified baseline package: + +```sh test-skip="needs the reader's baseline package and disposable database" +bregctl migration draft ./directory \ + --baseline-package /srv/registry/build-1/package \ + --runtime-config /srv/registry/runtime-test.yaml \ + --output ./reviewed-migrations \ + --module directory --id describe-email-update +``` + +It prints the covers it wrote and the directory, +`modules/directory/migrations/describe-email-update/`, under `--output`. Read the covers against +`diff`, then pass `--output` as `--reviewed-migrations`. The package validator still checks the +coverage and the evidence when you run `test` and `package`. + +The command refuses before it reads the runtime configuration or opens a database when: + +- `migration.draft.nothing-to-review`: every change is compatible additive, so no migration is needed. +- `migration.draft.sql-required`: a change needs authored SQL, a backup binding, or a descriptor of + another class. Write that migration by hand as above. The refusal names the first such change. +- `migration.draft.module-unknown`: the project has no module with that identifier. +- `migration.draft.output-exists`: the migration directory already exists. A draft never overwrites + one, so choose another `--id` or review the existing directory. + +{/* Evidence: crates/registry-bregctl/src/migration_draft.rs, run() and plan_covers(); + crates/registry-bregctl/tests/migration_draft.rs; + products/breg/scripts/test-adopter-workflow.sh, the drafted review of the readable-field successor. */} + ## Test and package the successor Pass the active package directory as `--baseline-package` to both `test` and `package`, and the diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 2c841dfc9c..24d5ff954b 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -336,6 +336,39 @@ The link has these known limits: an_applied_proposal_stays_bounded_by_a_record_whose_revision_was_erased; products/breg/contracts/security-invariant-matrix.yaml, BREG-SEC-217. */} +### One-call writes + +An immediate Action that patches an existing Record normally asks the caller for a condition: +a token that proves which revision the caller saw. +An Action that declares `concurrency: current-revision` sends no condition. +BReg then evaluates the Action's commit guards against the Record it has locked for the write, +and applies the patch to that same locked row. + +On such an Action the guard is the only protection against a stale write. +The author owns choosing a guard that the Action's own write makes false, so a second, stale call +finds the guard false and answers `412`. +`bregctl check` refuses the Action unless every Record it patches has an `equals` or `isNull` guard +that its write falsifies. +It also refuses a `revision: unchanged` guard, a function plan that writes an existing Record, and +any value from `fromInput` or `fromEffect` written into an existing Record, because a value the caller chose +from a stale view would silently overwrite a concurrent update. +A create effect may still take caller values. +A Proposal cannot declare the setting. + +A missing Record and a Record outside the caller's row boundary answer with the same body, as they do for a conditioned Action. +A caller who holds no read grant on the guarded field gets the generic `412 precondition.failed`. + +{/* Evidence: crates/registry-breg/src/immediate_actions.rs, validate_current_revision; + crates/registry-breg/src/mutation/action.rs, lock_action_patch_targets; + crates/registry-breg/tests/immediate_action_requirements.rs, + current_revision_refuses_a_revision_guard, + current_revision_refuses_caller_values_written_into_an_existing_record, + current_revision_needs_a_guard_the_write_falsifies; + crates/registry-breg/tests/postgres_immediate_actions.rs, + two_concurrent_current_revision_invocations_commit_exactly_once, + a_current_revision_action_does_not_tell_a_hidden_record_from_a_missing_one; + products/breg/contracts/security-invariant-matrix.yaml, BREG-SEC-224. */} + ### Record files A Record type's file slot is written once. diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index f5b3ae7ff0..af309ed08e 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,52 @@ ## Unreleased +- A `rowBoundarySets` member declares a named list of row boundaries once + per project or module file. A grant, an Action or Proposal target, or a + Record type's `accessRequirements` writes + `rowBoundaries: {rowBoundarySet: }` and gets the list. Each grant still writes its own `rowBoundaries`, + and omitting it is still refused. A set holds at least one boundary and is + never `unrestricted`. A reference to an undeclared set is refused with + `breg.row-boundary-set.reference-invalid`. The compiled package is the + same as one that writes each list inline. + +- A date guard can shift the registry-local date by whole calendar months + with `currentDateOffsetMonths` (-12000 to 12000), beside + `currentDateOffsetDays`. It requires `currentDate` and cannot be combined + with the day offset. The day of the month is kept and clamps to the last + day of a shorter month. A shift outside years 1 to 9999 fails the guard + closed. + +- A commit guard with a `reason` can carry a `label`, constant display text + of at most 256 bytes. It is returned where `guardReason` is: as `detail` + of `412 action.guard_failed` for an Action or a Proposal Submit or Apply, + and as `guardLabel` in the availability response. A guard the caller + cannot read still answers the fixed `precondition.failed`. + +- An immediate Action can declare + `execution: {mode: immediate, concurrency: current-revision}`. The caller then sends no condition and no + `preconditions`. BReg evaluates the commit guards against the Record it + locks and patches that row. `bregctl check` refuses the Action unless + every Record it patches has an `equals` or `isNull` guard its own write + makes false, and refuses a `revision: unchanged` guard, a function plan + that writes an existing Record, and caller-supplied values written into an + existing Record. A Proposal cannot declare `concurrency`. + +- `bregctl migration draft` writes `descriptor.json` and `rehearsal.json` + under `/modules//migrations/` for a successor whose + changes are all access or disclosure changes that alter no table, column + or index. It measures the schema fingerprint and PostgreSQL major on the + disposable database and binds them to the verified baseline package. It + refuses, before reading the runtime configuration, when nothing needs + review (`migration.draft.nothing-to-review`), a change needs SQL + (`migration.draft.sql-required`), the module is unknown + (`migration.draft.module-unknown`), or the directory exists + (`migration.draft.output-exists`). It never overwrites. + +- Migration note: registry revisions change on upgrade because the + availability response schema gained `guardLabel`. A package built before + this release is a new revision, so rebuild, test and package successors. + - A secret file BReg refuses at startup reports the check that failed and its fix under `breg.runtime.secret`, instead of one fixed sentence. diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index ef0cf4cbe4..0673372bc7 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -192,7 +192,8 @@ invariants: - {"id": "BREG-SEC-185", "state": "enforced", "targetWave": "W5", "threat": "A withdrawn Review or closed application regains authority after activation or rollback, or a retained late approval hides the Proposal from its requester.", "enforcementPoint": "mark_incompatible_proposals and withdraw_blocked_proposals close work atomically; reconcile_result and recovery preserve withdrawal; proposal_application_status validates the retained binding before projecting closure and review_progress checks withdrawal before results.", "refusal": "Never deliver fresh blocked work, enqueue from a withdrawn result, or reopen a closed round or job after rollback. Keep authorized Get, List, Cancel and Rebase available without turning historical approval into Apply authority.", "negativeId": "BREG-NEG-185", "negativeTest": {"path": "crates/registry-breg/tests/support/review_go_live.rs", "name": "late_approval_after_rollback_cannot_reopen_a_withdrawn_round_without_a_job"}} # Producer metadata proof: crates/registry-casework/tests/breg_review_journey.rs::native_pairing_reports_explicit_producer_identity_mismatch # Proposal Submit and Apply proofs: crates/registry-breg/tests/postgres_proposal_guard_failure.rs::an_unreadable_guard_field_stays_a_generic_precondition_refusal and ::apply_names_a_failed_field_guard_and_keeps_stale_revisions_generic - - {"id": "BREG-SEC-186", "state": "enforced", "targetWave": "W5", "threat": "An Action availability observation or distinct guard refusal reveals a hidden target field, row boundary, or record existence, or is mistaken for mutation authority.", "enforcementPoint": "Selected-profile Action availability admission, ordinary Get disclosure, and commit-time guard problem mapping.", "refusal": "Conceal missing and row-denied targets as the same 404; return a closed not-disclosed result without inspecting hidden guard or boundary values; defer a failed guard until current-target admission prechecks pass and use action.guard_failed only when the same profile can safely read the failed target field; never treat that code as proof that later effect, proposed-value, or database checks would pass; retain every authoritative check before commit.", "negativeId": "BREG-NEG-186", "negativeTest": {"path": "crates/registry-breg/tests/postgres_immediate_action_requirements.rs", "name": "immediate_action_availability_preserves_disclosure_and_commit_boundaries"}} + # Guard label proofs: crates/registry-breg/tests/postgres_immediate_action_requirements.rs::a_guard_label_rides_only_the_readable_guard_refusal_and_availability and ::an_unreadable_guard_field_never_discloses_the_guard_label, crates/registry-breg/src/correlation.rs::a_guard_label_replaces_the_detail_only_beside_its_reason, and crates/registry-breg/tests/postgres_proposal_guard_failure.rs::submit_and_apply_carry_the_guard_label_only_where_the_reason_rides + - {"id": "BREG-SEC-186", "state": "enforced", "targetWave": "W5", "threat": "An Action availability observation or distinct guard refusal reveals a hidden target field, row boundary, or record existence, or is mistaken for mutation authority.", "enforcementPoint": "Selected-profile Action availability admission, ordinary Get disclosure, and commit-time guard problem mapping.", "refusal": "Conceal missing and row-denied targets as the same 404; return a closed not-disclosed result without inspecting hidden guard or boundary values; defer a failed guard until current-target admission prechecks pass and use action.guard_failed only when the same profile can safely read the failed target field; never treat that code as proof that later effect, proposed-value, or database checks would pass; retain every authoritative check before commit. An authored guard label is a constant that rides only where the guard reason rides, as the refusal detail and the availability guardLabel, and never on precondition.failed.", "negativeId": "BREG-NEG-186", "negativeTest": {"path": "crates/registry-breg/tests/postgres_immediate_action_requirements.rs", "name": "immediate_action_availability_preserves_disclosure_and_commit_boundaries"}} - {"id": "BREG-SEC-187", "state": "enforced", "targetWave": "W5", "threat": "An active Record keeps or creates a reference to a tombstoned target, including through concurrent writes or a referencing Record hidden by caller row permissions; a refusal discloses hidden records or values beyond the lifecycle eligibility inherent in an authorized link attempt.", "enforcementPoint": "Compiler-owned lifecycle key and nullable generated source lifecycle column, enforced by immediate PostgreSQL foreign keys alongside the retained UUID foreign keys.", "refusal": "Refuse inactive targets and tombstones with incoming active references atomically across all writers; keep generic value-free conflicts, independently granted Action and Proposal authority, and retained reference IDs. A caller authorized to submit a known target identifier can infer whether it is lifecycle-eligible from success versus conflict even without target read authority; disclose no target values, referring Record identifiers, or missing-versus-tombstoned detail.", "negativeId": "BREG-NEG-187", "negativeTest": {"path": "crates/registry-breg/tests/postgres_reference_integrity.rs", "name": "active_references_refuse_tombstones_and_preserve_retained_links"}} - {"id": "BREG-SEC-188", "state": "enforced", "targetWave": "W5", "threat": "A Proposal author sets or changes an Action input another role owns, or uses the fixed-input check to learn a value the grant cannot read.", "enforcementPoint": "Compile-time writableInputs validation requiring declared inputs, input-writing authority, and readable fixed inputs for Edit, Revise or Rebase; Start, Edit, Revise and Rebase compare every fixed input with the stored base inside the mutation transaction.", "refusal": "Refuse with 400 request.invalid located at the first fixed input's API name, roll back the draft, and audit the refusal without the value.", "negativeId": "BREG-NEG-188", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal.rs", "name": "writable_inputs_bound_start_edit_revise_and_rebase_to_the_named_inputs"}} - {"id": "BREG-SEC-189", "state": "enforced", "targetWave": "W5", "threat": "A caller supplies or changes a generated business identifier, allocation and retry issue the same value twice within one uniqueness scope, or the append-only reservation ledger keeps restricted values or person references after record erasure.", "enforcementPoint": "Compiled generated-field write exclusion, transactional sequence or random allocation and append-only reservation under split database roles, a public or internal classification required of every generated field, immutable scope fields limited to public or internal values that are not references, and Proposal Submit's frozen effects.", "refusal": "Refuse generated fields classified above internal and restricted or reference scope fields at compilation; reject caller and Action values for generated fields and patches to their scopes; reserve every issued value before exposure, return a conflict on exhausted code space, and reuse frozen values on replay, Apply, and Retry.", "negativeId": "BREG-NEG-189", "negativeTest": {"path": "crates/registry-breg/tests/generated_identifier_compiler.rs", "name": "sequence_scope_fields_cannot_hold_restricted_values_or_references"}} @@ -235,3 +236,4 @@ invariants: - {"id": "BREG-SEC-221", "state": "enforced", "targetWave": "W5", "threat": "Applying a Proposal promotes a file into a Record slot that does not accept it or is classified less restricted than the Proposal slot, a file verification has not approved, or bytes other than the file frozen at submission, so a record keeps a file outside its slot's bounds, under a lower classification label than it was submitted with, or one nobody verified. The label is a compile-time check only: who can download the promoted file is decided by the record grants' readableAttachments.", "enforcementPoint": "bregctl check accepts a promotion only from a Proposal slot the Action declares, into a slot the target Record type of a create or patch effect declares, when the record slot accepts every media type and size the Proposal slot accepts and is classified at least as restricted as the Proposal slot, and once per slot of one record; promotions are part of the Action definition revision; apply recomputes the attachment manifest, which refuses a file whose verification does not permit its content, and inside the apply transaction, under the content-hash lock, requires the frozen submission's live reference with the same digest, media type and size and a verdict that still permits its content before it adds a record reference to the same content hash", "refusal": "Refuse the project with breg.action.attachment-invalid. Refuse the apply with 412 precondition.failed when the frozen file is waiting for verification, was rejected or no longer matches, and roll back every effect of the apply.", "negativeId": "BREG-NEG-221", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_s3.rs", "name": "promotion_references_the_verified_s3_object_and_refuses_unverified_bytes"}} - {"id": "BREG-SEC-222", "state": "enforced", "targetWave": "W5", "threat": "Applying a Proposal fills a Record slot that already holds a file, or commits part of its effects when a promotion fails, so the file a decision rests on changes or a record exists without the file the Proposal froze.", "enforcementPoint": "the promotion inserts the record reference in the apply transaction after the effect writes its record revision; the reference key (Record type, record, slot) refuses a second write, live or erased, and any refusal rolls back the records, revisions, references, outbox and the Proposal's application", "refusal": "Refuse with 409 attachment.slot-write-once, keep the stored file, and leave no record, revision or reference from the apply.", "negativeId": "BREG-NEG-222", "negativeTest": {"path": "crates/registry-breg/tests/postgres_record_attachments.rs", "name": "promotion_into_a_filled_slot_answers_409_and_rolls_back_the_whole_apply"}} - {"id": "BREG-SEC-223", "state": "enforced", "targetWave": "W5", "threat": "Operator erasure of a Proposal deletes the bytes of a file the Proposal promoted to a Record, or keeps the bytes of a Proposal file nothing promoted.", "enforcementPoint": "promotion adds a Record reference to the content hash the Proposal file holds and copies no bytes; Proposal erasure tombstones the Proposal references and retire_unreferenced deletes a hash under the content-hash lock only when no live Proposal or Record reference remains", "refusal": "Keep promoted bytes readable through the Record download after the Proposal is erased. Remove the bytes of Proposal files nothing promoted.", "negativeId": "BREG-NEG-223", "negativeTest": {"path": "crates/registry-breg/tests/postgres_record_attachments.rs", "name": "an_applied_proposal_promotes_its_file_by_reference_and_erasure_keeps_it"}} + - {"id": "BREG-SEC-224", "state": "enforced", "targetWave": "W5", "threat": "A one-call Action loses a concurrent update, writes against a revision its guards did not see, or tells a hidden record from a missing one.", "enforcementPoint": "an immediate Action declares concurrency: current-revision; bregctl check refuses it unless every record it patches has an equals or isNull commit guard that its own write makes false, and refuses a revision: unchanged guard, a function plan that writes an existing record, and any fromInput or fromEffect value written into an existing record; at runtime the guards are evaluated against the row locked FOR UPDATE and the patch applies to that same locked row, so a second write against the same record fails the guard", "refusal": "Refuse the project with breg.action.concurrency-revision-guard, breg.action.concurrency-caller-value or breg.action.concurrency-guard-missing. Answer a stale call, a missing record and a record outside the caller's row boundary with the generic 412 precondition.failed, with identical bodies apart from traceId.", "negativeId": "BREG-NEG-224", "negativeTest": {"path": "crates/registry-breg/tests/postgres_immediate_actions.rs", "name": "two_concurrent_current_revision_invocations_commit_exactly_once"}} diff --git a/products/breg/contracts/security-test-traceability.yaml b/products/breg/contracts/security-test-traceability.yaml index 7dab96b8f5..3128387b06 100644 --- a/products/breg/contracts/security-test-traceability.yaml +++ b/products/breg/contracts/security-test-traceability.yaml @@ -194,6 +194,7 @@ traceability: # Requester recovery after closure: crates/registry-breg/tests/support/review_go_live.rs::activation_closed_application_remains_readable_and_cancellable and rollback_closed_application_remains_readable_without_reviving_work # Fresh automatic Review: crates/registry-breg/tests/support/review_go_live.rs::activation_closed_application_rebases_to_fresh_review_without_reviving_old_job # Proposal Submit and Apply proofs: crates/registry-breg/tests/postgres_proposal_guard_failure.rs::an_unreadable_guard_field_stays_a_generic_precondition_refusal and ::apply_names_a_failed_field_guard_and_keeps_stale_revisions_generic + # Guard label proofs: crates/registry-breg/tests/postgres_immediate_action_requirements.rs::a_guard_label_rides_only_the_readable_guard_refusal_and_availability and ::an_unreadable_guard_field_never_discloses_the_guard_label, crates/registry-breg/src/correlation.rs::a_guard_label_replaces_the_detail_only_beside_its_reason, and crates/registry-breg/tests/postgres_proposal_guard_failure.rs::submit_and_apply_carry_the_guard_label_only_where_the_reason_rides - {"id": "BREG-SEC-186", "state": "enforced", "negativeId": "BREG-NEG-186", "negativeTest": {"path": "crates/registry-breg/tests/postgres_immediate_action_requirements.rs", "name": "immediate_action_availability_preserves_disclosure_and_commit_boundaries"}} - {"id": "BREG-SEC-187", "state": "enforced", "negativeId": "BREG-NEG-187", "negativeTest": {"path": "crates/registry-breg/tests/postgres_reference_integrity.rs", "name": "active_references_refuse_tombstones_and_preserve_retained_links"}} - {"id": "BREG-SEC-188", "state": "enforced", "negativeId": "BREG-NEG-188", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal.rs", "name": "writable_inputs_bound_start_edit_revise_and_rebase_to_the_named_inputs"}} @@ -272,3 +273,6 @@ traceability: # Create and patch reference one stored copy: crates/registry-breg/tests/postgres_record_attachments.rs::create_and_patch_effects_reference_one_stored_copy - {"id": "BREG-SEC-222", "state": "enforced", "negativeId": "BREG-NEG-222", "negativeTest": {"path": "crates/registry-breg/tests/postgres_record_attachments.rs", "name": "promotion_into_a_filled_slot_answers_409_and_rolls_back_the_whole_apply"}} - {"id": "BREG-SEC-223", "state": "enforced", "negativeId": "BREG-NEG-223", "negativeTest": {"path": "crates/registry-breg/tests/postgres_record_attachments.rs", "name": "an_applied_proposal_promotes_its_file_by_reference_and_erasure_keeps_it"}} + # Compile rules refuse a revision guard, a caller value and a missing falsifiable guard: crates/registry-breg/tests/immediate_action_requirements.rs::current_revision_needs_a_guard_the_write_falsifies + # A missing and a hidden record answer identically: crates/registry-breg/tests/postgres_immediate_actions.rs::a_current_revision_action_does_not_tell_a_hidden_record_from_a_missing_one + - {"id": "BREG-SEC-224", "state": "enforced", "negativeId": "BREG-NEG-224", "negativeTest": {"path": "crates/registry-breg/tests/postgres_immediate_actions.rs", "name": "two_concurrent_current_revision_invocations_commit_exactly_once"}} diff --git a/products/breg/examples/facility/registry.yaml b/products/breg/examples/facility/registry.yaml index cd4a97c854..bbf78f0153 100644 --- a/products/breg/examples/facility/registry.yaml +++ b/products/breg/examples/facility/registry.yaml @@ -206,6 +206,12 @@ actions: set: status: {value: inactive} +# Every grant in this file reaches the rows of the caller's own jurisdiction. +# Each grant still writes its own rowBoundaries, here as a reference. +rowBoundarySets: + same-jurisdiction: + - {field: jurisdiction, claim: jurisdiction, operator: equals} + accessProfiles: operator-editor: principalClaim: registry_principal @@ -217,8 +223,7 @@ accessProfiles: operations: [create, get, list, patch] readableFields: [operator-code, status, jurisdiction] writableFields: [operator-code, status, jurisdiction] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} facility-reader: principalClaim: registry_principal requiredScopes: ["registry:facility:read"] @@ -228,21 +233,18 @@ accessProfiles: - recordType: operator operations: [get, list] readableFields: [operator-code, status, jurisdiction] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} - recordType: facility operations: [get, list] readableFields: [facility-code, name, address-line, city, postal-code, status, jurisdiction] readPaths: - {path: operators, readableFields: [operator-code, status, jurisdiction]} - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} - recordType: facility-assignment operations: [get, list] readableFields: [facility, operator, jurisdiction] filterableFields: [facility, operator] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} directory-editor: default: true principalClaim: registry_principal @@ -254,8 +256,7 @@ accessProfiles: operations: [create, get, list, patch] readableFields: [name, email, jurisdiction] writableFields: [name, email, jurisdiction] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} facility-registrar: principalClaim: registry_principal requiredScopes: ["registry:facility:register"] @@ -266,14 +267,11 @@ accessProfiles: operations: [invoke] targets: - recordType: facility - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} - recordType: facility-assignment - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} - recordType: operator - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} results: [facility, assignment] facility-correction-author: principalClaim: registry_principal @@ -285,14 +283,12 @@ accessProfiles: operations: [start] targets: - recordType: facility - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} - action: deactivate-facility operations: [start] targets: - recordType: facility - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} proposals: - action: correct-address operations: [get, list, edit, submit, revise, rebase, retry, cancel, get-review-status] @@ -302,16 +298,14 @@ accessProfiles: ownership: caller targets: - recordType: facility - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} - action: deactivate-facility operations: [get, list, edit, submit, revise, rebase, retry, cancel, get-review-status] readableInputs: [facility] ownership: caller targets: - recordType: facility - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} facility-correction-applier: principalClaim: registry_principal requiredScopes: ["registry:facility:correction:apply"] @@ -322,14 +316,12 @@ accessProfiles: operations: [get, list, apply] targets: - recordType: facility - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} - action: deactivate-facility operations: [get, list, apply] targets: - recordType: facility - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} proposal-reviewer: principalClaim: registry_principal requiredScopes: ["registry:proposal:review"] @@ -339,16 +331,14 @@ accessProfiles: - recordType: facility operations: [get] readableFields: [address-line, city, postal-code] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} proposals: - action: correct-address operations: [get-review-context] readableContextFields: [facilityId, currentAddressLine, changes, supportingDocument] targets: - recordType: facility - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} casework-review-status: actorKind: service diff --git a/products/breg/examples/formats/ctl-report.json b/products/breg/examples/formats/ctl-report.json index c50c91869c..5cb76735fc 100644 --- a/products/breg/examples/formats/ctl-report.json +++ b/products/breg/examples/formats/ctl-report.json @@ -16,7 +16,7 @@ "source": { "column": 15, "file": "products/breg/examples/facility/registry.yaml", - "line": 237 + "line": 241 }, "suggestedAction": "Remove fields that these readers should not see from this read path's readableFields, or remove the read path; use a direct permission on the related record type when its own row boundaries should apply." } @@ -1664,13 +1664,13 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:dca3c6da48851de9878daa19e0f15b48f867abc87bfd90a0e5ef738a75dc79bd", + "revision": "sha256:e79873067041f4addc70ab7004fcef3bb0cf5993d5af8fec884c017b3150c257", "statisticalDatasets": [] }, "kind": "BRegCtlReport", "ok": true, "profile": "authoring", - "revision": "sha256:dca3c6da48851de9878daa19e0f15b48f867abc87bfd90a0e5ef738a75dc79bd", + "revision": "sha256:e79873067041f4addc70ab7004fcef3bb0cf5993d5af8fec884c017b3150c257", "status": "complete", "version": "0.49.0-dev" } diff --git a/products/breg/examples/formats/explain/actions-explanation.json b/products/breg/examples/formats/explain/actions-explanation.json index cb64860763..8732ba6929 100644 --- a/products/breg/examples/formats/explain/actions-explanation.json +++ b/products/breg/examples/formats/explain/actions-explanation.json @@ -1641,6 +1641,6 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:dca3c6da48851de9878daa19e0f15b48f867abc87bfd90a0e5ef738a75dc79bd", + "revision": "sha256:e79873067041f4addc70ab7004fcef3bb0cf5993d5af8fec884c017b3150c257", "statisticalDatasets": [] } diff --git a/products/breg/examples/formats/explain/model-explanation.json b/products/breg/examples/formats/explain/model-explanation.json index b908a4e2cd..c259f4eb84 100644 --- a/products/breg/examples/formats/explain/model-explanation.json +++ b/products/breg/examples/formats/explain/model-explanation.json @@ -1524,6 +1524,12 @@ "/actions/deactivate-facility/plan/effects/0/set", "/actions/deactivate-facility/plan/effects/0/set/status", "/actions/deactivate-facility/plan/effects/0/set/status/value", + "/rowBoundarySets", + "/rowBoundarySets/same-jurisdiction", + "/rowBoundarySets/same-jurisdiction/0", + "/rowBoundarySets/same-jurisdiction/0/field", + "/rowBoundarySets/same-jurisdiction/0/claim", + "/rowBoundarySets/same-jurisdiction/0/operator", "/accessProfiles", "/accessProfiles/operator-editor", "/accessProfiles/operator-editor/principalClaim", @@ -1549,10 +1555,7 @@ "/accessProfiles/operator-editor/permissions/records/0/writableFields/1", "/accessProfiles/operator-editor/permissions/records/0/writableFields/2", "/accessProfiles/operator-editor/permissions/records/0/rowBoundaries", - "/accessProfiles/operator-editor/permissions/records/0/rowBoundaries/0", - "/accessProfiles/operator-editor/permissions/records/0/rowBoundaries/0/field", - "/accessProfiles/operator-editor/permissions/records/0/rowBoundaries/0/claim", - "/accessProfiles/operator-editor/permissions/records/0/rowBoundaries/0/operator", + "/accessProfiles/operator-editor/permissions/records/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-reader", "/accessProfiles/facility-reader/principalClaim", "/accessProfiles/facility-reader/requiredScopes", @@ -1571,10 +1574,7 @@ "/accessProfiles/facility-reader/permissions/records/0/readableFields/1", "/accessProfiles/facility-reader/permissions/records/0/readableFields/2", "/accessProfiles/facility-reader/permissions/records/0/rowBoundaries", - "/accessProfiles/facility-reader/permissions/records/0/rowBoundaries/0", - "/accessProfiles/facility-reader/permissions/records/0/rowBoundaries/0/field", - "/accessProfiles/facility-reader/permissions/records/0/rowBoundaries/0/claim", - "/accessProfiles/facility-reader/permissions/records/0/rowBoundaries/0/operator", + "/accessProfiles/facility-reader/permissions/records/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-reader/permissions/records/1", "/accessProfiles/facility-reader/permissions/records/1/recordType", "/accessProfiles/facility-reader/permissions/records/1/operations", @@ -1596,10 +1596,7 @@ "/accessProfiles/facility-reader/permissions/records/1/readPaths/0/readableFields/1", "/accessProfiles/facility-reader/permissions/records/1/readPaths/0/readableFields/2", "/accessProfiles/facility-reader/permissions/records/1/rowBoundaries", - "/accessProfiles/facility-reader/permissions/records/1/rowBoundaries/0", - "/accessProfiles/facility-reader/permissions/records/1/rowBoundaries/0/field", - "/accessProfiles/facility-reader/permissions/records/1/rowBoundaries/0/claim", - "/accessProfiles/facility-reader/permissions/records/1/rowBoundaries/0/operator", + "/accessProfiles/facility-reader/permissions/records/1/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-reader/permissions/records/2", "/accessProfiles/facility-reader/permissions/records/2/recordType", "/accessProfiles/facility-reader/permissions/records/2/operations", @@ -1613,10 +1610,7 @@ "/accessProfiles/facility-reader/permissions/records/2/filterableFields/0", "/accessProfiles/facility-reader/permissions/records/2/filterableFields/1", "/accessProfiles/facility-reader/permissions/records/2/rowBoundaries", - "/accessProfiles/facility-reader/permissions/records/2/rowBoundaries/0", - "/accessProfiles/facility-reader/permissions/records/2/rowBoundaries/0/field", - "/accessProfiles/facility-reader/permissions/records/2/rowBoundaries/0/claim", - "/accessProfiles/facility-reader/permissions/records/2/rowBoundaries/0/operator", + "/accessProfiles/facility-reader/permissions/records/2/rowBoundaries/rowBoundarySet", "/accessProfiles/directory-editor", "/accessProfiles/directory-editor/default", "/accessProfiles/directory-editor/principalClaim", @@ -1642,10 +1636,7 @@ "/accessProfiles/directory-editor/permissions/records/0/writableFields/1", "/accessProfiles/directory-editor/permissions/records/0/writableFields/2", "/accessProfiles/directory-editor/permissions/records/0/rowBoundaries", - "/accessProfiles/directory-editor/permissions/records/0/rowBoundaries/0", - "/accessProfiles/directory-editor/permissions/records/0/rowBoundaries/0/field", - "/accessProfiles/directory-editor/permissions/records/0/rowBoundaries/0/claim", - "/accessProfiles/directory-editor/permissions/records/0/rowBoundaries/0/operator", + "/accessProfiles/directory-editor/permissions/records/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-registrar", "/accessProfiles/facility-registrar/principalClaim", "/accessProfiles/facility-registrar/requiredScopes", @@ -1662,24 +1653,15 @@ "/accessProfiles/facility-registrar/permissions/actions/0/targets/0", "/accessProfiles/facility-registrar/permissions/actions/0/targets/0/recordType", "/accessProfiles/facility-registrar/permissions/actions/0/targets/0/rowBoundaries", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/0/rowBoundaries/0", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/0/rowBoundaries/0/field", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/0/rowBoundaries/0/claim", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/0/rowBoundaries/0/operator", + "/accessProfiles/facility-registrar/permissions/actions/0/targets/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-registrar/permissions/actions/0/targets/1", "/accessProfiles/facility-registrar/permissions/actions/0/targets/1/recordType", "/accessProfiles/facility-registrar/permissions/actions/0/targets/1/rowBoundaries", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/1/rowBoundaries/0", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/1/rowBoundaries/0/field", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/1/rowBoundaries/0/claim", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/1/rowBoundaries/0/operator", + "/accessProfiles/facility-registrar/permissions/actions/0/targets/1/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-registrar/permissions/actions/0/targets/2", "/accessProfiles/facility-registrar/permissions/actions/0/targets/2/recordType", "/accessProfiles/facility-registrar/permissions/actions/0/targets/2/rowBoundaries", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/2/rowBoundaries/0", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/2/rowBoundaries/0/field", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/2/rowBoundaries/0/claim", - "/accessProfiles/facility-registrar/permissions/actions/0/targets/2/rowBoundaries/0/operator", + "/accessProfiles/facility-registrar/permissions/actions/0/targets/2/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-registrar/permissions/actions/0/results", "/accessProfiles/facility-registrar/permissions/actions/0/results/0", "/accessProfiles/facility-registrar/permissions/actions/0/results/1", @@ -1699,10 +1681,7 @@ "/accessProfiles/facility-correction-author/permissions/actions/0/targets/0", "/accessProfiles/facility-correction-author/permissions/actions/0/targets/0/recordType", "/accessProfiles/facility-correction-author/permissions/actions/0/targets/0/rowBoundaries", - "/accessProfiles/facility-correction-author/permissions/actions/0/targets/0/rowBoundaries/0", - "/accessProfiles/facility-correction-author/permissions/actions/0/targets/0/rowBoundaries/0/field", - "/accessProfiles/facility-correction-author/permissions/actions/0/targets/0/rowBoundaries/0/claim", - "/accessProfiles/facility-correction-author/permissions/actions/0/targets/0/rowBoundaries/0/operator", + "/accessProfiles/facility-correction-author/permissions/actions/0/targets/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-correction-author/permissions/actions/1", "/accessProfiles/facility-correction-author/permissions/actions/1/action", "/accessProfiles/facility-correction-author/permissions/actions/1/operations", @@ -1711,10 +1690,7 @@ "/accessProfiles/facility-correction-author/permissions/actions/1/targets/0", "/accessProfiles/facility-correction-author/permissions/actions/1/targets/0/recordType", "/accessProfiles/facility-correction-author/permissions/actions/1/targets/0/rowBoundaries", - "/accessProfiles/facility-correction-author/permissions/actions/1/targets/0/rowBoundaries/0", - "/accessProfiles/facility-correction-author/permissions/actions/1/targets/0/rowBoundaries/0/field", - "/accessProfiles/facility-correction-author/permissions/actions/1/targets/0/rowBoundaries/0/claim", - "/accessProfiles/facility-correction-author/permissions/actions/1/targets/0/rowBoundaries/0/operator", + "/accessProfiles/facility-correction-author/permissions/actions/1/targets/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-correction-author/permissions/proposals", "/accessProfiles/facility-correction-author/permissions/proposals/0", "/accessProfiles/facility-correction-author/permissions/proposals/0/action", @@ -1742,10 +1718,7 @@ "/accessProfiles/facility-correction-author/permissions/proposals/0/targets/0", "/accessProfiles/facility-correction-author/permissions/proposals/0/targets/0/recordType", "/accessProfiles/facility-correction-author/permissions/proposals/0/targets/0/rowBoundaries", - "/accessProfiles/facility-correction-author/permissions/proposals/0/targets/0/rowBoundaries/0", - "/accessProfiles/facility-correction-author/permissions/proposals/0/targets/0/rowBoundaries/0/field", - "/accessProfiles/facility-correction-author/permissions/proposals/0/targets/0/rowBoundaries/0/claim", - "/accessProfiles/facility-correction-author/permissions/proposals/0/targets/0/rowBoundaries/0/operator", + "/accessProfiles/facility-correction-author/permissions/proposals/0/targets/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-correction-author/permissions/proposals/1", "/accessProfiles/facility-correction-author/permissions/proposals/1/action", "/accessProfiles/facility-correction-author/permissions/proposals/1/operations", @@ -1765,10 +1738,7 @@ "/accessProfiles/facility-correction-author/permissions/proposals/1/targets/0", "/accessProfiles/facility-correction-author/permissions/proposals/1/targets/0/recordType", "/accessProfiles/facility-correction-author/permissions/proposals/1/targets/0/rowBoundaries", - "/accessProfiles/facility-correction-author/permissions/proposals/1/targets/0/rowBoundaries/0", - "/accessProfiles/facility-correction-author/permissions/proposals/1/targets/0/rowBoundaries/0/field", - "/accessProfiles/facility-correction-author/permissions/proposals/1/targets/0/rowBoundaries/0/claim", - "/accessProfiles/facility-correction-author/permissions/proposals/1/targets/0/rowBoundaries/0/operator", + "/accessProfiles/facility-correction-author/permissions/proposals/1/targets/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-correction-applier", "/accessProfiles/facility-correction-applier/principalClaim", "/accessProfiles/facility-correction-applier/requiredScopes", @@ -1787,10 +1757,7 @@ "/accessProfiles/facility-correction-applier/permissions/proposals/0/targets/0", "/accessProfiles/facility-correction-applier/permissions/proposals/0/targets/0/recordType", "/accessProfiles/facility-correction-applier/permissions/proposals/0/targets/0/rowBoundaries", - "/accessProfiles/facility-correction-applier/permissions/proposals/0/targets/0/rowBoundaries/0", - "/accessProfiles/facility-correction-applier/permissions/proposals/0/targets/0/rowBoundaries/0/field", - "/accessProfiles/facility-correction-applier/permissions/proposals/0/targets/0/rowBoundaries/0/claim", - "/accessProfiles/facility-correction-applier/permissions/proposals/0/targets/0/rowBoundaries/0/operator", + "/accessProfiles/facility-correction-applier/permissions/proposals/0/targets/0/rowBoundaries/rowBoundarySet", "/accessProfiles/facility-correction-applier/permissions/proposals/1", "/accessProfiles/facility-correction-applier/permissions/proposals/1/action", "/accessProfiles/facility-correction-applier/permissions/proposals/1/operations", @@ -1801,10 +1768,7 @@ "/accessProfiles/facility-correction-applier/permissions/proposals/1/targets/0", "/accessProfiles/facility-correction-applier/permissions/proposals/1/targets/0/recordType", "/accessProfiles/facility-correction-applier/permissions/proposals/1/targets/0/rowBoundaries", - "/accessProfiles/facility-correction-applier/permissions/proposals/1/targets/0/rowBoundaries/0", - "/accessProfiles/facility-correction-applier/permissions/proposals/1/targets/0/rowBoundaries/0/field", - "/accessProfiles/facility-correction-applier/permissions/proposals/1/targets/0/rowBoundaries/0/claim", - "/accessProfiles/facility-correction-applier/permissions/proposals/1/targets/0/rowBoundaries/0/operator", + "/accessProfiles/facility-correction-applier/permissions/proposals/1/targets/0/rowBoundaries/rowBoundarySet", "/accessProfiles/proposal-reviewer", "/accessProfiles/proposal-reviewer/principalClaim", "/accessProfiles/proposal-reviewer/requiredScopes", @@ -1822,10 +1786,7 @@ "/accessProfiles/proposal-reviewer/permissions/records/0/readableFields/1", "/accessProfiles/proposal-reviewer/permissions/records/0/readableFields/2", "/accessProfiles/proposal-reviewer/permissions/records/0/rowBoundaries", - "/accessProfiles/proposal-reviewer/permissions/records/0/rowBoundaries/0", - "/accessProfiles/proposal-reviewer/permissions/records/0/rowBoundaries/0/field", - "/accessProfiles/proposal-reviewer/permissions/records/0/rowBoundaries/0/claim", - "/accessProfiles/proposal-reviewer/permissions/records/0/rowBoundaries/0/operator", + "/accessProfiles/proposal-reviewer/permissions/records/0/rowBoundaries/rowBoundarySet", "/accessProfiles/proposal-reviewer/permissions/proposals", "/accessProfiles/proposal-reviewer/permissions/proposals/0", "/accessProfiles/proposal-reviewer/permissions/proposals/0/action", @@ -1840,10 +1801,7 @@ "/accessProfiles/proposal-reviewer/permissions/proposals/0/targets/0", "/accessProfiles/proposal-reviewer/permissions/proposals/0/targets/0/recordType", "/accessProfiles/proposal-reviewer/permissions/proposals/0/targets/0/rowBoundaries", - "/accessProfiles/proposal-reviewer/permissions/proposals/0/targets/0/rowBoundaries/0", - "/accessProfiles/proposal-reviewer/permissions/proposals/0/targets/0/rowBoundaries/0/field", - "/accessProfiles/proposal-reviewer/permissions/proposals/0/targets/0/rowBoundaries/0/claim", - "/accessProfiles/proposal-reviewer/permissions/proposals/0/targets/0/rowBoundaries/0/operator", + "/accessProfiles/proposal-reviewer/permissions/proposals/0/targets/0/rowBoundaries/rowBoundarySet", "/accessProfiles/casework-review-status", "/accessProfiles/casework-review-status/actorKind", "/accessProfiles/casework-review-status/principalClaim", @@ -2644,7 +2602,7 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:dca3c6da48851de9878daa19e0f15b48f867abc87bfd90a0e5ef738a75dc79bd", + "revision": "sha256:e79873067041f4addc70ab7004fcef3bb0cf5993d5af8fec884c017b3150c257", "statisticalDatasets": [], "version": "0.1.0" } diff --git a/products/breg/examples/formats/odrl-coverage.json b/products/breg/examples/formats/odrl-coverage.json index e386fe5ca9..20ac13a390 100644 --- a/products/breg/examples/formats/odrl-coverage.json +++ b/products/breg/examples/formats/odrl-coverage.json @@ -1 +1 @@ -{"apiVersion":"id.registrystack.org/formats/breg/odrl-coverage/v1alpha1","audience":"operator-review","excludedSurfaces":["actions","proposals","statistics","lookups","read-paths","revisions","snapshots","mutations","counts","filters","sorting","spatial-queries","data-export","provenance"],"grants":[{"accessProfile":"directory-editor","operation":"create","reasons":["unsupported-operation","row-boundaries"],"recordType":"contact","status":"omitted"},{"accessProfile":"directory-editor","operation":"get","reasons":["row-boundaries"],"recordType":"contact","status":"omitted"},{"accessProfile":"directory-editor","operation":"list","reasons":["row-boundaries"],"recordType":"contact","status":"omitted"},{"accessProfile":"directory-editor","operation":"patch","reasons":["unsupported-operation","row-boundaries"],"recordType":"contact","status":"omitted"}],"kind":"BRegOdrlCoverage","partial":true,"registryId":"local-directory","revision":"sha256:5e7fbc35de52b6437ee46b9623af792b19758d176001c2d82acfc0c6c9a8c670","scope":"record-operation-grants","selectedAccessProfile":null,"totals":{"considered":4,"exported":0,"omitted":4}} \ No newline at end of file +{"apiVersion":"id.registrystack.org/formats/breg/odrl-coverage/v1alpha1","audience":"operator-review","excludedSurfaces":["actions","proposals","statistics","lookups","read-paths","revisions","snapshots","mutations","counts","filters","sorting","spatial-queries","data-export","provenance"],"grants":[{"accessProfile":"directory-editor","operation":"create","reasons":["unsupported-operation","row-boundaries"],"recordType":"contact","status":"omitted"},{"accessProfile":"directory-editor","operation":"get","reasons":["row-boundaries"],"recordType":"contact","status":"omitted"},{"accessProfile":"directory-editor","operation":"list","reasons":["row-boundaries"],"recordType":"contact","status":"omitted"},{"accessProfile":"directory-editor","operation":"patch","reasons":["unsupported-operation","row-boundaries"],"recordType":"contact","status":"omitted"}],"kind":"BRegOdrlCoverage","partial":true,"registryId":"local-directory","revision":"sha256:ce5659a026ee22f47809f0e9c5c66abe349f2d57412ebc8fd3dd125470ed780e","scope":"record-operation-grants","selectedAccessProfile":null,"totals":{"considered":4,"exported":0,"omitted":4}} \ No newline at end of file diff --git a/products/breg/generated/authoring/registry-module.schema.json b/products/breg/generated/authoring/registry-module.schema.json index 319974f07a..c871763909 100644 --- a/products/breg/generated/authoring/registry-module.schema.json +++ b/products/breg/generated/authoring/registry-module.schema.json @@ -106,16 +106,31 @@ "uniqueItems": true }, "rowBoundaries": { - "description": "Every profile must include these exact field, verified-claim, and operator bindings. Omit to demand no row boundary.", - "items": { - "$ref": "#/$defs/RowBoundarySource" - }, - "minItems": 1, - "type": "array" + "anyOf": [ + { + "items": { + "$ref": "#/$defs/RowBoundarySource" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/RowBoundarySetReference" + } + ], + "description": "Every profile must include these exact field, verified-claim, and operator bindings. Omit to demand no row boundary." } }, "type": "object" }, + "ActionConcurrency": { + "description": "How an immediate Action guards its patches against a concurrent write.\n`condition-required` asks the caller to prove the revision it saw.\n`current-revision` evaluates the Action's commit guards against the locked\ncurrent row instead, so the caller sends no condition.", + "enum": [ + "condition-required", + "current-revision" + ], + "type": "string" + }, "ActionEffectSource": { "additionalProperties": false, "properties": { @@ -212,6 +227,9 @@ { "additionalProperties": false, "properties": { + "concurrency": { + "$ref": "#/$defs/ActionConcurrency" + }, "mode": { "const": "immediate", "type": "string" @@ -711,6 +729,13 @@ "minimum": -365000, "type": "integer" }, + "currentDateOffsetMonths": { + "description": "Whole calendar months added to the registry-local date before applying\n`currentDate`, clamping to the last day of a shorter month (January 31\nplus one month is February 28 or 29). Requires `currentDate`, is\nexclusive with `currentDateOffsetDays`, and zero preserves the\nunshifted comparison.", + "format": "int32", + "maximum": 12000, + "minimum": -12000, + "type": "integer" + }, "equals": { "$ref": "#/$defs/ScalarLiteral" }, @@ -729,6 +754,10 @@ "description": "Requires the stored value to be unset. Only `true` is read.", "type": "boolean" }, + "label": { + "$ref": "#/$defs/DisplayText", + "description": "Authored refusal text, a constant of at most 256 bytes that requires\n`reason`. It is returned as the Problem `detail` and as the availability\n`guardLabel` exactly where `reason` is returned, so it is disclosed only\nwhen every guard and boundary fact is readable. It never replaces the\ngeneric precondition refusal." + }, "reason": { "$ref": "#/$defs/LocalId", "description": "Stable application copy key; disclosure still requires readable guard facts." @@ -3695,9 +3724,27 @@ }, "minItems": 1, "type": "array" + }, + { + "$ref": "#/$defs/RowBoundarySetReference", + "description": "Reach the rows every boundary of a named set binds to the caller's claims." } ], - "description": "The rows a permission reaches: the keyword `unrestricted`, or a list of at\nleast one row boundary." + "description": "The rows a permission reaches: the keyword `unrestricted`, a list of at\nleast one row boundary, or a reference to a named list of them." + }, + "RowBoundarySetReference": { + "additionalProperties": false, + "description": "A reference to a named list of row boundaries the file declares under\n`rowBoundarySets`. The reader expands a reference into the set's boundaries\nbefore the typed model is decoded, so the compiler never holds one.", + "properties": { + "rowBoundarySet": { + "$ref": "#/$defs/LocalId", + "description": "The identifier of a set declared under `rowBoundarySets` in the same file." + } + }, + "required": [ + "rowBoundarySet" + ], + "type": "object" }, "RowBoundarySource": { "additionalProperties": false, @@ -4998,6 +5045,21 @@ }, "type": "object" }, + "rowBoundarySets": { + "additionalProperties": { + "items": { + "$ref": "#/$defs/RowBoundarySource" + }, + "minItems": 1, + "type": "array" + }, + "description": "Named lists of row boundaries, declared once and referenced as\n`rowBoundaries: {rowBoundarySet: }` wherever a row reach is written\nin this file. A reference expands to the set's boundaries when the file\nis read, so each grant still states its own reach. A set holds at least\none boundary and is never `unrestricted`.", + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object", + "writeOnly": true + }, "valueTypes": { "additionalProperties": { "$ref": "#/$defs/ReusableValueTypeSource" diff --git a/products/breg/generated/authoring/registry-project.schema.json b/products/breg/generated/authoring/registry-project.schema.json index fa1d357670..3d9bab3e17 100644 --- a/products/breg/generated/authoring/registry-project.schema.json +++ b/products/breg/generated/authoring/registry-project.schema.json @@ -106,16 +106,31 @@ "uniqueItems": true }, "rowBoundaries": { - "description": "Every profile must include these exact field, verified-claim, and operator bindings. Omit to demand no row boundary.", - "items": { - "$ref": "#/$defs/RowBoundarySource" - }, - "minItems": 1, - "type": "array" + "anyOf": [ + { + "items": { + "$ref": "#/$defs/RowBoundarySource" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/RowBoundarySetReference" + } + ], + "description": "Every profile must include these exact field, verified-claim, and operator bindings. Omit to demand no row boundary." } }, "type": "object" }, + "ActionConcurrency": { + "description": "How an immediate Action guards its patches against a concurrent write.\n`condition-required` asks the caller to prove the revision it saw.\n`current-revision` evaluates the Action's commit guards against the locked\ncurrent row instead, so the caller sends no condition.", + "enum": [ + "condition-required", + "current-revision" + ], + "type": "string" + }, "ActionEffectSource": { "additionalProperties": false, "properties": { @@ -212,6 +227,9 @@ { "additionalProperties": false, "properties": { + "concurrency": { + "$ref": "#/$defs/ActionConcurrency" + }, "mode": { "const": "immediate", "type": "string" @@ -747,6 +765,13 @@ "minimum": -365000, "type": "integer" }, + "currentDateOffsetMonths": { + "description": "Whole calendar months added to the registry-local date before applying\n`currentDate`, clamping to the last day of a shorter month (January 31\nplus one month is February 28 or 29). Requires `currentDate`, is\nexclusive with `currentDateOffsetDays`, and zero preserves the\nunshifted comparison.", + "format": "int32", + "maximum": 12000, + "minimum": -12000, + "type": "integer" + }, "equals": { "$ref": "#/$defs/ScalarLiteral" }, @@ -765,6 +790,10 @@ "description": "Requires the stored value to be unset. Only `true` is read.", "type": "boolean" }, + "label": { + "$ref": "#/$defs/DisplayText", + "description": "Authored refusal text, a constant of at most 256 bytes that requires\n`reason`. It is returned as the Problem `detail` and as the availability\n`guardLabel` exactly where `reason` is returned, so it is disclosed only\nwhen every guard and boundary fact is readable. It never replaces the\ngeneric precondition refusal." + }, "reason": { "$ref": "#/$defs/LocalId", "description": "Stable application copy key; disclosure still requires readable guard facts." @@ -4866,9 +4895,27 @@ }, "minItems": 1, "type": "array" + }, + { + "$ref": "#/$defs/RowBoundarySetReference", + "description": "Reach the rows every boundary of a named set binds to the caller's claims." } ], - "description": "The rows a permission reaches: the keyword `unrestricted`, or a list of at\nleast one row boundary." + "description": "The rows a permission reaches: the keyword `unrestricted`, a list of at\nleast one row boundary, or a reference to a named list of them." + }, + "RowBoundarySetReference": { + "additionalProperties": false, + "description": "A reference to a named list of row boundaries the file declares under\n`rowBoundarySets`. The reader expands a reference into the set's boundaries\nbefore the typed model is decoded, so the compiler never holds one.", + "properties": { + "rowBoundarySet": { + "$ref": "#/$defs/LocalId", + "description": "The identifier of a set declared under `rowBoundarySets` in the same file." + } + }, + "required": [ + "rowBoundarySet" + ], + "type": "object" }, "RowBoundarySource": { "additionalProperties": false, @@ -6629,6 +6676,21 @@ }, "type": "object" }, + "rowBoundarySets": { + "additionalProperties": { + "items": { + "$ref": "#/$defs/RowBoundarySource" + }, + "minItems": 1, + "type": "array" + }, + "description": "Named lists of row boundaries, declared once and referenced as\n`rowBoundaries: {rowBoundarySet: }` wherever a row reach is written\nin this file. A reference expands to the set's boundaries when the file\nis read, so each grant still states its own reach. A set holds at least\none boundary and is never `unrestricted`.", + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object", + "writeOnly": true + }, "statisticalDatasets": { "additionalProperties": { "additionalProperties": false, diff --git a/products/breg/generated/facility/generated/action-schemas/register-facility.availability.response.schema.json b/products/breg/generated/facility/generated/action-schemas/register-facility.availability.response.schema.json index ffa70d7b68..661200c2cc 100644 --- a/products/breg/generated/facility/generated/action-schemas/register-facility.availability.response.schema.json +++ b/products/breg/generated/facility/generated/action-schemas/register-facility.availability.response.schema.json @@ -1 +1 @@ -{"$id":"urn:breg:action:register-facility:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"register-facility"} \ No newline at end of file +{"$id":"urn:breg:action:register-facility:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"register-facility"} \ No newline at end of file diff --git a/products/breg/generated/facility/generated/openapi.json b/products/breg/generated/facility/generated/openapi.json index 91f965d7f9..c160fbbe6f 100644 --- a/products/breg/generated/facility/generated/openapi.json +++ b/products/breg/generated/facility/generated/openapi.json @@ -1 +1 @@ -{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.slot-write-once","attachment.too-large","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-correct-address-invoke-input":{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},"action-correct-address-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-deactivate-facility-invoke-input":{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},"action-deactivate-facility-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-register-facility-availability-input":{"$id":"urn:breg:action:register-facility:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"operatorId":{"format":"uuid","type":"string"}},"required":["operatorId"]},"targetInput":{"const":"operatorId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["operatorId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-availability-response":{"$id":"urn:breg:action:register-facility:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-invoke-input":{"$id":"urn:breg:action:register-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-facility","x-registry-requiredConditionKeys":[]},"action-register-facility-invoke-response":{"$id":"urn:breg:action:register-facility:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"register-facility"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"assignment":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility-assignment"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"facility":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["assignment","facility"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"directory-entry":{"$id":"urn:breg:record-type:directory-entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"directory-entry-create-input":{"$id":"urn:breg:record-type:directory-entry:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"facility":{"$id":"urn:breg:record-type:facility","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"required":["facilityCode","name","addressLine","city","postalCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable","x-registry-mutationPolicy":{"patch":"proposal-required"}},"facility-assignment":{"$id":"urn:breg:record-type:facility-assignment","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"required":["facility","operator","jurisdiction"],"type":"object","x-registry-mutationMode":"create-only"},"operator":{"$id":"urn:breg:record-type:operator","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"operator-create-input":{"$id":"urn:breg:record-type:operator:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"}}},"info":{"title":"facility-registry","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/correct-address/proposals":{"post":{"operationId":"actions.correct-address.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"correctAddress","attachments":[{"contentTypes":["application/pdf"],"id":"supporting-document","maximumBytes":1048576,"required":false}],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a frozen address correction for independent review and later application.","label":"Correct facility address"},"execution":{"application":"automatic","mode":"proposal","review":"required"},"id":"correct-address","inputMode":"handler","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}}],"maximumInputStringBytes":16384,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-address","operation":"patch","recordType":"facility"}],"revision":"sha256:efb20d40704ae6c133b660f2fe3d556b4a00ee5478a5871cf1fd026e7d7b6b7a","route":"/v1/actions/correct-address/proposals","routes":{"availability":null,"start":{"inputSchema":"action-correct-address-invoke-input","method":"POST","operationId":"actions.correct-address.start","path":"/v1/actions/correct-address/proposals","requiresIdempotencyKey":true,"responseSchema":"action-correct-address-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/deactivate-facility/proposals":{"post":{"operationId":"actions.deactivate-facility.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"deactivateFacility","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a durable deactivation that requires no external review.","label":"Deactivate facility"},"execution":{"application":"manual","mode":"proposal","review":"none"},"id":"deactivate-facility","inputMode":"fixed","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-status","operation":"patch","recordType":"facility"}],"revision":"sha256:9237300ee419a0014c3b123cc7ac90eb9623cb4c45bba4a65c03936083299f1d","route":"/v1/actions/deactivate-facility/proposals","routes":{"availability":null,"start":{"inputSchema":"action-deactivate-facility-invoke-input","method":"POST","operationId":"actions.deactivate-facility.start","path":"/v1/actions/deactivate-facility/proposals","requiresIdempotencyKey":true,"responseSchema":"action-deactivate-facility-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility":{"post":{"operationId":"actions.register-facility.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility/availability":{"post":{"operationId":"actions.register-facility.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/review-context":{"get":{"description":"One bounded transport exchange under each item's current get-review-context authority. Ordered visible or concealed results; operational failures refuse the whole batch. Maximum response is 8 MiB.","operationId":"proposals.get-review-context-batch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["proposal-reviewer"],"type":"string"}},{"description":"One to 100 distinct canonical Proposal UUIDs, in response order.","explode":false,"in":"query","name":"ids","required":true,"schema":{"items":{"format":"uuid","type":"string"},"maxItems":100,"minItems":1,"type":"array","uniqueItems":true},"style":"form"}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"context":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"},"id":{"format":"uuid","type":"string"},"status":{"const":"visible"}},"required":["id","status","context"],"type":"object"},{"additionalProperties":false,"properties":{"id":{"format":"uuid","type":"string"},"status":{"const":"concealed"}},"required":["id","status"],"type":"object"}]},"maxItems":100,"minItems":1,"type":"array"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/apply":{"post":{"operationId":"proposals.apply","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"reason":{"description":"Optional application explanation, preserved unchanged. At most 4096 Unicode characters; NUL is refused.","maxLength":4096,"pattern":"^[^\\u0000]*$","type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["submissionVersion","effectDigest"],"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["facility-correction-applier"]}},"/v1/proposals/{proposal_id}/attachments/supporting-document":{"delete":{"operationId":"proposals.attachments.supporting-document.delete","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]},"get":{"operationId":"proposals.attachments.supporting-document.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author","proposal-reviewer"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"query","name":"submissionVersion","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"reviewContextField","required":false,"schema":{"pattern":"^[a-z][a-zA-Z0-9]{0,63}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"effectDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"contextSchemaDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}}],"responses":{"200":{"content":{"application/octet-stream":{"schema":{"format":"binary","maxLength":16777216,"type":"string"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author","proposal-reviewer"]},"patch":{"operationId":"proposals.attachments.supporting-document.patch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/pdf":{"schema":{"format":"binary","maxLength":1048576,"type":"string"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/rebase":{"post":{"operationId":"proposals.rebase","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/retry":{"post":{"operationId":"proposals.retry","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/review-context":{"get":{"operationId":"proposals.get-review-context","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["proposal-reviewer"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}/review-status":{"get":{"operationId":"proposals.get-review-status","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["casework-review-status","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request the institution's optional applicant-visible progress code. The code is returned only when the selected caller-owned grant enables readableReviewProgress.","in":"query","name":"include","required":false,"schema":{"const":"progress"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"reference":{"type":"string"}},"required":["reference"],"type":"object"},"effectDigest":{"type":"string"},"handoff":{"additionalProperties":false,"properties":{"reason":{"enum":["remote-refused","producer-identity-mismatch","review-acceptance-changed","review-policy-changed","submission-recovery-expired","operator-closed","unspecified"]},"state":{"enum":["pending","accepted","failed","withdrawn"]}},"required":["state"],"type":"object"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"progressCode":{"description":"Institution-defined applicant-visible progress. Absent when the institution conceals the current stage, progress was not requested or granted, the provider is unavailable, or the accepted review round is no longer live.","maxLength":64,"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"requestId":{"format":"uuid","type":"string"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["casework-review-status","facility-correction-author"]}},"/v1/proposals/{proposal_id}/revise":{"post":{"operationId":"proposals.revise","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},{"additionalProperties":false,"type":"object"}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"410":{"description":"The submission's review result and application receipt are no longer retained"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/records/directory-entries":{"get":{"operationId":"records.directory-entry.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.directory-entry.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/directory-entry-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/directory-entries/{record_id}":{"get":{"operationId":"records.directory-entry.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.directory-entry.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities":{"get":{"operationId":"records.facility.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["addressLine","city","facilityCode","jurisdiction","name","postalCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facilities/{record_id}":{"get":{"operationId":"records.facility.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","proposal-reviewer"],"x-registry-operation":"get","x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities/{record_id}/operators":{"get":{"operationId":"records.facility.path.operators","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments":{"get":{"operationId":"records.facility-assignment.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[{"operators":["equals","in","is-null","is-not-null"],"property":"facility"},{"operators":["equals","in","is-null","is-not-null"],"property":"operator"}],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["facility","jurisdiction","operator"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments/{record_id}":{"get":{"operationId":"records.facility-assignment.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"get","x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators":{"get":{"operationId":"records.operator.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null},"operator-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"operator-editor","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.operator.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/operator-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"create","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators/{record_id}":{"get":{"operationId":"records.operator.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"get","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.operator.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"patch","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion token and recipient binding.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"Idempotency-Key","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion or idempotency binding is invalid."},"401":{"description":"The completion authority could not be authenticated."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"bearerAuth":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file +{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.slot-write-once","attachment.too-large","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-correct-address-invoke-input":{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},"action-correct-address-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-deactivate-facility-invoke-input":{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},"action-deactivate-facility-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-register-facility-availability-input":{"$id":"urn:breg:action:register-facility:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"operatorId":{"format":"uuid","type":"string"}},"required":["operatorId"]},"targetInput":{"const":"operatorId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["operatorId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-availability-response":{"$id":"urn:breg:action:register-facility:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-invoke-input":{"$id":"urn:breg:action:register-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-facility","x-registry-requiredConditionKeys":[]},"action-register-facility-invoke-response":{"$id":"urn:breg:action:register-facility:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"register-facility"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"assignment":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility-assignment"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"facility":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["assignment","facility"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"directory-entry":{"$id":"urn:breg:record-type:directory-entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"directory-entry-create-input":{"$id":"urn:breg:record-type:directory-entry:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"facility":{"$id":"urn:breg:record-type:facility","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"required":["facilityCode","name","addressLine","city","postalCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable","x-registry-mutationPolicy":{"patch":"proposal-required"}},"facility-assignment":{"$id":"urn:breg:record-type:facility-assignment","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"required":["facility","operator","jurisdiction"],"type":"object","x-registry-mutationMode":"create-only"},"operator":{"$id":"urn:breg:record-type:operator","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"operator-create-input":{"$id":"urn:breg:record-type:operator:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"}}},"info":{"title":"facility-registry","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/correct-address/proposals":{"post":{"operationId":"actions.correct-address.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"correctAddress","attachments":[{"contentTypes":["application/pdf"],"id":"supporting-document","maximumBytes":1048576,"required":false}],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a frozen address correction for independent review and later application.","label":"Correct facility address"},"execution":{"application":"automatic","mode":"proposal","review":"required"},"id":"correct-address","inputMode":"handler","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}}],"maximumInputStringBytes":16384,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-address","operation":"patch","recordType":"facility"}],"revision":"sha256:efb20d40704ae6c133b660f2fe3d556b4a00ee5478a5871cf1fd026e7d7b6b7a","route":"/v1/actions/correct-address/proposals","routes":{"availability":null,"start":{"inputSchema":"action-correct-address-invoke-input","method":"POST","operationId":"actions.correct-address.start","path":"/v1/actions/correct-address/proposals","requiresIdempotencyKey":true,"responseSchema":"action-correct-address-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/deactivate-facility/proposals":{"post":{"operationId":"actions.deactivate-facility.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"deactivateFacility","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a durable deactivation that requires no external review.","label":"Deactivate facility"},"execution":{"application":"manual","mode":"proposal","review":"none"},"id":"deactivate-facility","inputMode":"fixed","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-status","operation":"patch","recordType":"facility"}],"revision":"sha256:9237300ee419a0014c3b123cc7ac90eb9623cb4c45bba4a65c03936083299f1d","route":"/v1/actions/deactivate-facility/proposals","routes":{"availability":null,"start":{"inputSchema":"action-deactivate-facility-invoke-input","method":"POST","operationId":"actions.deactivate-facility.start","path":"/v1/actions/deactivate-facility/proposals","requiresIdempotencyKey":true,"responseSchema":"action-deactivate-facility-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility":{"post":{"operationId":"actions.register-facility.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility/availability":{"post":{"operationId":"actions.register-facility.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/review-context":{"get":{"description":"One bounded transport exchange under each item's current get-review-context authority. Ordered visible or concealed results; operational failures refuse the whole batch. Maximum response is 8 MiB.","operationId":"proposals.get-review-context-batch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["proposal-reviewer"],"type":"string"}},{"description":"One to 100 distinct canonical Proposal UUIDs, in response order.","explode":false,"in":"query","name":"ids","required":true,"schema":{"items":{"format":"uuid","type":"string"},"maxItems":100,"minItems":1,"type":"array","uniqueItems":true},"style":"form"}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"context":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"},"id":{"format":"uuid","type":"string"},"status":{"const":"visible"}},"required":["id","status","context"],"type":"object"},{"additionalProperties":false,"properties":{"id":{"format":"uuid","type":"string"},"status":{"const":"concealed"}},"required":["id","status"],"type":"object"}]},"maxItems":100,"minItems":1,"type":"array"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/apply":{"post":{"operationId":"proposals.apply","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"reason":{"description":"Optional application explanation, preserved unchanged. At most 4096 Unicode characters; NUL is refused.","maxLength":4096,"pattern":"^[^\\u0000]*$","type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["submissionVersion","effectDigest"],"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["facility-correction-applier"]}},"/v1/proposals/{proposal_id}/attachments/supporting-document":{"delete":{"operationId":"proposals.attachments.supporting-document.delete","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]},"get":{"operationId":"proposals.attachments.supporting-document.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author","proposal-reviewer"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"query","name":"submissionVersion","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"reviewContextField","required":false,"schema":{"pattern":"^[a-z][a-zA-Z0-9]{0,63}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"effectDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"contextSchemaDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}}],"responses":{"200":{"content":{"application/octet-stream":{"schema":{"format":"binary","maxLength":16777216,"type":"string"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author","proposal-reviewer"]},"patch":{"operationId":"proposals.attachments.supporting-document.patch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/pdf":{"schema":{"format":"binary","maxLength":1048576,"type":"string"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/rebase":{"post":{"operationId":"proposals.rebase","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/retry":{"post":{"operationId":"proposals.retry","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/review-context":{"get":{"operationId":"proposals.get-review-context","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["proposal-reviewer"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}/review-status":{"get":{"operationId":"proposals.get-review-status","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["casework-review-status","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request the institution's optional applicant-visible progress code. The code is returned only when the selected caller-owned grant enables readableReviewProgress.","in":"query","name":"include","required":false,"schema":{"const":"progress"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"reference":{"type":"string"}},"required":["reference"],"type":"object"},"effectDigest":{"type":"string"},"handoff":{"additionalProperties":false,"properties":{"reason":{"enum":["remote-refused","producer-identity-mismatch","review-acceptance-changed","review-policy-changed","submission-recovery-expired","operator-closed","unspecified"]},"state":{"enum":["pending","accepted","failed","withdrawn"]}},"required":["state"],"type":"object"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"progressCode":{"description":"Institution-defined applicant-visible progress. Absent when the institution conceals the current stage, progress was not requested or granted, the provider is unavailable, or the accepted review round is no longer live.","maxLength":64,"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"requestId":{"format":"uuid","type":"string"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["casework-review-status","facility-correction-author"]}},"/v1/proposals/{proposal_id}/revise":{"post":{"operationId":"proposals.revise","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},{"additionalProperties":false,"type":"object"}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"410":{"description":"The submission's review result and application receipt are no longer retained"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/records/directory-entries":{"get":{"operationId":"records.directory-entry.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.directory-entry.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/directory-entry-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/directory-entries/{record_id}":{"get":{"operationId":"records.directory-entry.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.directory-entry.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities":{"get":{"operationId":"records.facility.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["addressLine","city","facilityCode","jurisdiction","name","postalCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facilities/{record_id}":{"get":{"operationId":"records.facility.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","proposal-reviewer"],"x-registry-operation":"get","x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities/{record_id}/operators":{"get":{"operationId":"records.facility.path.operators","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments":{"get":{"operationId":"records.facility-assignment.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[{"operators":["equals","in","is-null","is-not-null"],"property":"facility"},{"operators":["equals","in","is-null","is-not-null"],"property":"operator"}],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["facility","jurisdiction","operator"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments/{record_id}":{"get":{"operationId":"records.facility-assignment.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"get","x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators":{"get":{"operationId":"records.operator.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null},"operator-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"operator-editor","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.operator.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/operator-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"create","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators/{record_id}":{"get":{"operationId":"records.operator.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"get","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.operator.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"patch","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion token and recipient binding.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"Idempotency-Key","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion or idempotency binding is invalid."},"401":{"description":"The completion authority could not be authenticated."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"bearerAuth":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file diff --git a/products/breg/generated/minimal/generated/action-schemas/update-contact-email.availability.response.schema.json b/products/breg/generated/minimal/generated/action-schemas/update-contact-email.availability.response.schema.json index be0b96f168..11c2caa2ba 100644 --- a/products/breg/generated/minimal/generated/action-schemas/update-contact-email.availability.response.schema.json +++ b/products/breg/generated/minimal/generated/action-schemas/update-contact-email.availability.response.schema.json @@ -1 +1 @@ -{"$id":"urn:breg:action:update-contact-email:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["contactId","email"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"update-contact-email"} \ No newline at end of file +{"$id":"urn:breg:action:update-contact-email:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["contactId","email"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"update-contact-email"} \ No newline at end of file diff --git a/products/breg/generated/minimal/generated/openapi.json b/products/breg/generated/minimal/generated/openapi.json index 42b334b223..6cd9e51ed8 100644 --- a/products/breg/generated/minimal/generated/openapi.json +++ b/products/breg/generated/minimal/generated/openapi.json @@ -1 +1 @@ -{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.slot-write-once","attachment.too-large","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-register-contact-invoke-input":{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]},"action-register-contact-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-update-contact-email-availability-input":{"$id":"urn:breg:action:update-contact-email:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"contactId":{"format":"uuid","type":"string"}},"required":["contactId"]},"targetInput":{"const":"contactId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["contactId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"update-contact-email"},"action-update-contact-email-availability-response":{"$id":"urn:breg:action:update-contact-email:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["contactId","email"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"update-contact-email"},"action-update-contact-email-invoke-input":{"$id":"urn:breg:action:update-contact-email:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":["contactId","email"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"action-update-contact-email-invoke-response":{"$id":"urn:breg:action:update-contact-email:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"update-contact-email"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"contact-email":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"contact"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["contact-email"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"action-update-contact-email-target-conditions-input":{"$id":"urn:breg:action:update-contact-email:target-conditions-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"}},"required":["contactId"],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"action-update-contact-email-target-conditions-response":{"$id":"urn:breg:action:update-contact-email:target-conditions-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["preconditions"],"type":"object","x-registry-action":"update-contact-email"},"contact":{"$id":"urn:breg:record-type:contact","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"contact-create-input":{"$id":"urn:breg:record-type:contact:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"}}},"info":{"title":"local-directory","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/register-contact/proposals":{"post":{"operationId":"actions.register-contact.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-contact-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-contact-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"registerContact","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Create one contact through a Proposal that applies on submit without external review.","label":"Register contact"},"execution":{"application":"automatic","mode":"proposal","review":"none"},"id":"register-contact","inputMode":"fixed","inputs":[{"apiName":"name","classification":"internal","fieldType":{"maximumLength":160,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":160,"minLength":1,"type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[],"requiredConditionKeys":[],"resultEffects":[{"effect":"contact","operation":"create","recordType":"contact"}],"revision":"sha256:2a81cd7c0637d4bfd3043ca4643134bde20a92d9e14ba15cd966a8e00d3e40da","route":"/v1/actions/register-contact/proposals","routes":{"availability":null,"start":{"inputSchema":"action-register-contact-invoke-input","method":"POST","operationId":"actions.register-contact.start","path":"/v1/actions/register-contact/proposals","requiresIdempotencyKey":true,"responseSchema":"action-register-contact-invoke-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/update-contact-email":{"post":{"operationId":"actions.update-contact-email.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/update-contact-email/availability":{"post":{"operationId":"actions.update-contact-email.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/actions/update-contact-email/target-conditions":{"post":{"operationId":"actions.update-contact-email.target-conditions","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-target-conditions-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-target-conditions-response"}}},"description":"Action target conditions returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"target-conditions"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"410":{"description":"The submission's review result and application receipt are no longer retained"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/records/contacts":{"get":{"operationId":"records.contact.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.contact.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/contact-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/contacts/{record_id}":{"get":{"operationId":"records.contact.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.contact.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion token and recipient binding.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"Idempotency-Key","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion or idempotency binding is invalid."},"401":{"description":"The completion authority could not be authenticated."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"bearerAuth":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file +{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.slot-write-once","attachment.too-large","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-register-contact-invoke-input":{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]},"action-register-contact-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-update-contact-email-availability-input":{"$id":"urn:breg:action:update-contact-email:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"contactId":{"format":"uuid","type":"string"}},"required":["contactId"]},"targetInput":{"const":"contactId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["contactId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"update-contact-email"},"action-update-contact-email-availability-response":{"$id":"urn:breg:action:update-contact-email:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["contactId","email"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"update-contact-email"},"action-update-contact-email-invoke-input":{"$id":"urn:breg:action:update-contact-email:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":["contactId","email"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"action-update-contact-email-invoke-response":{"$id":"urn:breg:action:update-contact-email:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"update-contact-email"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"contact-email":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"contact"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["contact-email"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"action-update-contact-email-target-conditions-input":{"$id":"urn:breg:action:update-contact-email:target-conditions-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"}},"required":["contactId"],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"action-update-contact-email-target-conditions-response":{"$id":"urn:breg:action:update-contact-email:target-conditions-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["preconditions"],"type":"object","x-registry-action":"update-contact-email"},"contact":{"$id":"urn:breg:record-type:contact","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"contact-create-input":{"$id":"urn:breg:record-type:contact:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"}}},"info":{"title":"local-directory","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/register-contact/proposals":{"post":{"operationId":"actions.register-contact.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-contact-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-contact-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"registerContact","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Create one contact through a Proposal that applies on submit without external review.","label":"Register contact"},"execution":{"application":"automatic","mode":"proposal","review":"none"},"id":"register-contact","inputMode":"fixed","inputs":[{"apiName":"name","classification":"internal","fieldType":{"maximumLength":160,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":160,"minLength":1,"type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[],"requiredConditionKeys":[],"resultEffects":[{"effect":"contact","operation":"create","recordType":"contact"}],"revision":"sha256:2a81cd7c0637d4bfd3043ca4643134bde20a92d9e14ba15cd966a8e00d3e40da","route":"/v1/actions/register-contact/proposals","routes":{"availability":null,"start":{"inputSchema":"action-register-contact-invoke-input","method":"POST","operationId":"actions.register-contact.start","path":"/v1/actions/register-contact/proposals","requiresIdempotencyKey":true,"responseSchema":"action-register-contact-invoke-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/update-contact-email":{"post":{"operationId":"actions.update-contact-email.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/update-contact-email/availability":{"post":{"operationId":"actions.update-contact-email.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/actions/update-contact-email/target-conditions":{"post":{"operationId":"actions.update-contact-email.target-conditions","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-target-conditions-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-target-conditions-response"}}},"description":"Action target conditions returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"target-conditions"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"410":{"description":"The submission's review result and application receipt are no longer retained"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/records/contacts":{"get":{"operationId":"records.contact.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.contact.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/contact-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/contacts/{record_id}":{"get":{"operationId":"records.contact.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.contact.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer credential is missing or refused.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion token and recipient binding.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"Idempotency-Key","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion or idempotency binding is invalid."},"401":{"description":"The completion authority could not be authenticated."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"bearerAuth":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file diff --git a/products/breg/scripts/test-adopter-workflow.sh b/products/breg/scripts/test-adopter-workflow.sh index a7eda935cb..74c4e83903 100755 --- a/products/breg/scripts/test-adopter-workflow.sh +++ b/products/breg/scripts/test-adopter-workflow.sh @@ -757,7 +757,6 @@ run_json "$temporary_root/schema-test-v2.json" test "$temporary_root/project-v2" --baseline-package "$temporary_root/build-v1/package" \ --output "$temporary_root/schema-test-receipt-v2.json" assert_json_ok "$temporary_root/schema-test-v2.json" test -schema_fingerprint_v2=$(json_field "$temporary_root/schema-test-v2.json" schemaFingerprint) run_json "$temporary_root/package-v2.json" package "$temporary_root/project-v2" \ --baseline-package "$temporary_root/build-v1/package" \ @@ -1039,48 +1038,35 @@ run_json "$temporary_root/measure-v3.json" test "$temporary_root/project-v3" --f --runtime-config "$temporary_root/runtime-test-v3.yaml" assert_json_ok "$temporary_root/measure-v3.json" test schema_fingerprint_v3=$(json_field "$temporary_root/measure-v3.json" schemaFingerprint) -postgres_major=$(psql "$adopter_production_admin_url" -Atqc 'SELECT current_setting('\''server_version_num'\'')::integer / 10000') - -# Test-fixture evidence only, for a metadata-only review with no authored SQL. -# The target fingerprint and lock-timeout refusal above were measured, not guessed. -python3 - "$temporary_root" "$package_digest_v2" "$schema_fingerprint_v2" "$schema_fingerprint_v3" "$postgres_major" <<'PY' -import hashlib +# A change that needs no SQL is reviewed with a drafted migration: the command +# covers the access changes against the verified predecessor and measures the +# target on the disposable database, so no evidence is written by hand. The +# measured fingerprint is the one the independent measurement above reported. +run_json "$temporary_root/draft-v3.json" migration draft "$temporary_root/project-v3" \ + --baseline-package "$temporary_root/build-v2/package" \ + --runtime-config "$temporary_root/runtime-test-v3.yaml" \ + --output "$temporary_root/review-v3" --module asset-site-placement-core --id read-maintenance-note +assert_json_ok "$temporary_root/draft-v3.json" "migration draft" +python3 - "$temporary_root/draft-v3.json" "$package_digest_v2" "$schema_fingerprint_v3" <<'PY' import json import sys -from pathlib import Path -root = Path(sys.argv[1]) -changes = json.loads((root / "diff-v3.json").read_text())["changes"] -if any(change["classification"] == "unsupported" for change in changes): - raise SystemExit("reviewed successor was incorrectly classified as unsupported") -covers = [{"code": item["change"]["code"], "target": item["change"]["target"]} - for item in changes if item["change"]["class"] != "compatible-additive"] -if {cover["code"] for cover in covers} != {"access-profile-changed", "query-inventory-changed"}: - raise SystemExit("reviewed successor did not have the expected permission changes") -base = "modules/asset-site-placement-core/migrations/read-maintenance-note" -descriptor = { - "apiVersion": "id.registrystack.org/formats/breg/migration-descriptor/v1alpha1", - "kind": "BRegMigrationDescriptor", - "id": "read-maintenance-note", "changeClass": "access-or-disclosure-change", - "covers": covers, "recovery": "exact-target-resume", "lockTimeoutMilliseconds": 1000, - "statementTimeoutMilliseconds": 60000, "steps": [], "preAssertions": [], "postAssertions": [], - "rehearsalReceiptPath": f"{base}/rehearsal.json", -} -def canonical(document): - return json.dumps(document, sort_keys=True, separators=(",", ":")).encode("ascii") -descriptor_bytes = canonical(descriptor) -receipt = { - "apiVersion": "id.registrystack.org/formats/breg/migration-rehearsal-receipt/v1alpha1", - "kind": "BRegMigrationRehearsalReceipt", - "priorPackageDigest": sys.argv[2], "priorSchemaFingerprint": sys.argv[3], - "planDigest": "sha256:" + hashlib.sha256(descriptor_bytes).hexdigest(), - "sqlDigests": [], "assertionDigests": [], "fixtureInventory": [], "postgresMajor": int(sys.argv[5]), - "rowAssertions": [], "finalSchemaFingerprint": sys.argv[4], -} -directory = root / "review-v3" / base -directory.mkdir(parents=True) -(directory / "descriptor.json").write_bytes(descriptor_bytes) -(directory / "rehearsal.json").write_bytes(canonical(receipt)) +report = json.load(open(sys.argv[1], encoding="utf-8")) +if {cover["code"] for cover in report["covers"]} != {"access-profile-changed", "query-inventory-changed"}: + raise SystemExit("the drafted migration did not cover the expected permission changes") +if report["priorPackageDigest"] != sys.argv[2]: + raise SystemExit("the drafted receipt does not bind the verified predecessor") +if report["finalSchemaFingerprint"] != sys.argv[3]: + raise SystemExit("the drafted receipt does not carry the measured target fingerprint") PY +# A draft never overwrites a migration it already wrote. +if run_json "$temporary_root/draft-v3-again.json" migration draft "$temporary_root/project-v3" \ + --baseline-package "$temporary_root/build-v2/package" \ + --runtime-config "$temporary_root/runtime-test-v3.yaml" \ + --output "$temporary_root/review-v3" --module asset-site-placement-core --id read-maintenance-note; then + printf '%s\n' 'a second draft unexpectedly overwrote the first.' >&2 + exit 1 +fi +assert_json_failure "$temporary_root/draft-v3-again.json" migration.draft.output-exists reviewed_candidate_args+=(--reviewed-migrations "$temporary_root/review-v3") review_receipt="$temporary_root/review-v3/modules/asset-site-placement-core/migrations/read-maintenance-note/rehearsal.json" cp "$review_receipt" "$temporary_root/review-receipt-v3.original.json" diff --git a/products/breg/scripts/test_validate_product.py b/products/breg/scripts/test_validate_product.py index 26a1e3eece..987bfc2df8 100644 --- a/products/breg/scripts/test_validate_product.py +++ b/products/breg/scripts/test_validate_product.py @@ -74,7 +74,7 @@ def test_security_range_is_closed_through_derived_sql_invariants(self) -> None: ) extension_rows = matrix["invariants"][24:] self.assertEqual( - [f"BREG-NEG-{index:02d}" for index in range(25, 224) if index not in {61, 62}], + [f"BREG-NEG-{index:02d}" for index in range(25, 225) if index not in {61, 62}], [invariant["negativeId"] for invariant in extension_rows], ) for invariant in extension_rows: diff --git a/products/breg/scripts/validate_product.py b/products/breg/scripts/validate_product.py index ec0e79dec5..adec946934 100644 --- a/products/breg/scripts/validate_product.py +++ b/products/breg/scripts/validate_product.py @@ -31,7 +31,7 @@ CONTRACT_STATES = {"enforced", "partial", "planned"} V1_REQUIREMENT_IDS = tuple(f"BREG-V1-{index:02d}" for index in range(1, 45)) ACCEPTANCE_JOURNEY_IDS = tuple(f"BREG-J{index:02d}" for index in range(1, 25)) -SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 224) if index not in {61, 62}) +SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 225) if index not in {61, 62}) ACCEPTANCE_FIXTURES = { "BREG-J01": ("asset-site-placement", "acceptance/asset-site-placement"), "BREG-J02": ("asset-site-placement", "acceptance/asset-site-placement"), diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index bead8cb53f..afe7268d49 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -30,7 +30,7 @@ "description": "Base Registry Engine fixed Proposal lifecycle event schema, reproduced byte-for-byte from its packaged artifact.", "source": { "path": "crates/registry-breg/src/proposal_hooks.rs", - "sha256": "02fe083f3d06c107298847923f42c0036ee98d5ba12347e527e886c0cedd2178" + "sha256": "23fceb42341650d4f4a3477a025fe8a8065759a7f490ec98a0ff11281c23a917" }, "artifact": { "path": "products/breg/generated/event-schemas/proposal-lifecycle.schema.json", @@ -4946,7 +4946,7 @@ "description": "Base Registry Engine portable Action contract export schema, reproduced from the canonical compiled project.", "source": { "path": "crates/registry-breg/src/artifacts.rs", - "sha256": "1205595c67c8ae57e9744b2a52b98cbff6546416f1271491a42d29387ddbaa70" + "sha256": "a90f5a0d37662f711d136c6bc418cd93308ceac4b3e64b5d249a5890709bd1ed" }, "artifact": { "path": "products/breg/generated/facility/generated/action-contracts.schema.json", @@ -5184,7 +5184,7 @@ }, "artifact": { "path": "products/breg/generated/authoring/registry-module.schema.json", - "sha256": "0689f2010a51d1bc5b12c20377b208a5b579c525828a2246d03da5f6f64ac408", + "sha256": "fc153209d577848348fbe95965500b0269cb57c7ce4e80c87013057280df2275", "mediaType": "application/schema+json" } }, @@ -5202,7 +5202,7 @@ }, "artifact": { "path": "products/breg/generated/authoring/registry-project.schema.json", - "sha256": "206317fcd5bc1ca10bbf77c534305c26094c7879143319214bfb1fbd627a2738", + "sha256": "2140744201848a465df671c0ab4b1f2a160ea3feb3758d78e8dbdda41a1ddada", "mediaType": "application/schema+json" } }, From bbf7a6e132f483659b03381687393a422c62037f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 27 Nov 2026 13:06:22 +0100 Subject: [PATCH 083/136] feat(platform): record the declared posture on every audit journal line An auditor reading a journal could not tell whether a line came from a development or a production deployment. Every new line now carries the writer's declared posture, development or production, serialized before the line reaches the file or stream sink, detached responses included. AuditWriter::open and AuditWriter::from_line_sink take the declaration. Their _without_posture forms record production, and every runtime uses them until it declares its own posture. Journal readers accept older lines without the member and refuse a malformed one. The Evidence, Render and BReg envelope assertions and the published Evidence audit event schemas include the member. Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-breg-mcp/src/gateway/tests.rs | 8 +- crates/registry-breg-mcp/src/runtime.rs | 2 +- crates/registry-breg-review/src/journal.rs | 2 +- crates/registry-breg-review/src/lib.rs | 2 +- .../registry-breg-review/tests/support/mod.rs | 4 +- crates/registry-breg/src/audit.rs | 6 +- crates/registry-breg/src/startup.rs | 4 +- .../tests/postgres_proposal_security.rs | 2 +- .../registry-breg/tests/postgres_startup.rs | 2 +- crates/registry-casework/src/audit.rs | 2 +- crates/registry-casework/src/runtime.rs | 2 +- crates/registry-coordinator/src/deployment.rs | 12 +- crates/registry-coordinator/src/store.rs | 2 +- .../tests/calendar_trigger_authoring.rs | 2 +- .../tests/deployment_postgres.rs | 14 +- .../tests/postgres_state.rs | 8 +- .../tests/read_in_force_postgres.rs | 2 +- .../tests/read_lease_recovery.rs | 2 +- .../tests/recovery_audit.rs | 2 +- crates/registry-documents/src/audit.rs | 2 +- crates/registry-documents/src/runtime.rs | 2 +- .../tests/postgres_documents.rs | 8 +- .../tests/postgres_operator.rs | 4 +- .../registry-documents/tests/support/mod.rs | 4 +- crates/registry-evidence-oid4vci/src/audit.rs | 2 +- .../registry-evidence-oid4vci/src/service.rs | 2 +- .../tests/audit_attribution.rs | 4 +- .../tests/draft13_profile.rs | 4 +- .../tests/inji_interoperability.rs | 2 +- .../tests/offer_authorization.rs | 4 +- .../tests/state_machine_recovery.rs | 6 +- .../tests/store_contract.rs | 2 +- crates/registry-evidence-oid4vp/src/audit.rs | 2 +- crates/registry-evidence/src/audit.rs | 33 +- crates/registry-evidence/src/authority.rs | 4 +- crates/registry-evidence/src/runtime_tests.rs | 2 +- .../tests/source_authority_paths.rs | 2 +- crates/registry-mcp-edge/src/audit.rs | 10 +- .../src/compatibility_tests/audit.rs | 2 +- .../src/compatibility_tests/server.rs | 4 +- .../src/inbound/refusal_tests.rs | 4 +- crates/registry-mcp-edge/src/tests.rs | 4 +- crates/registry-mcp/src/runtime.rs | 2 +- crates/registry-messaging/src/audit.rs | 4 +- crates/registry-messaging/src/runtime.rs | 15 +- .../tests/postgres_callbacks.rs | 8 +- .../tests/postgres_messages.rs | 16 +- .../tests/postgres_retention.rs | 24 +- .../registry-messaging/tests/support/mod.rs | 8 +- crates/registry-platform-audit/Cargo.toml | 1 + crates/registry-platform-audit/README.md | 10 +- crates/registry-platform-audit/src/lib.rs | 5 +- crates/registry-platform-audit/src/writer.rs | 367 +++++++++++++----- .../tests/cross_crate_integration.rs | 2 +- crates/registry-render/src/audit.rs | 14 +- crates/registry-render/src/server.rs | 4 +- crates/registry-render/tests/serve.rs | 1 + crates/registry-scheduling/src/audit.rs | 6 +- crates/registry-scheduling/src/runtime.rs | 2 +- .../registry-schedulingctl/src/activation.rs | 6 +- crates/registry-schedulingctl/src/lib.rs | 4 +- .../docs/operate/casework-retention.mdx | 2 +- .../content/docs/operate/evidence-audit.mdx | 3 +- .../content/docs/operate/registry-render.mdx | 2 +- .../docs/reference/casework-configuration.mdx | 2 +- products/breg/scripts/test-backup-restore.sh | 2 +- products/evidence/OPERATOR-CONTRACT.md | 3 +- .../contracts/audit-event.schema.yaml | 2 +- .../public-check-audit-event.schema.yaml | 2 +- .../request-batch-audit-event.schema.yaml | 2 +- .../contracts/security-invariant-matrix.yaml | 2 +- .../deployment-projects/CONFIG.md | 2 +- products/platform/CHANGELOG.md | 6 + 74 files changed, 478 insertions(+), 245 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d96dee5c42..0845b8a72a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7797,6 +7797,7 @@ version = "0.49.0" dependencies = [ "hmac 0.13.0", "regex", + "registry-platform-posture", "rustix 1.1.6", "schemars", "serde", diff --git a/crates/registry-breg-mcp/src/gateway/tests.rs b/crates/registry-breg-mcp/src/gateway/tests.rs index 094166d7be..6f705e0dcf 100644 --- a/crates/registry-breg-mcp/src/gateway/tests.rs +++ b/crates/registry-breg-mcp/src/gateway/tests.rs @@ -76,7 +76,7 @@ impl AuditCapture { fn capture_audit() -> (ToolAuditLog, AuditCapture) { let buffer = AuditBuffer::default(); - let writer = AuditWriter::from_line_sink(Box::new(buffer.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())); ( ToolAuditLog::new(writer.clone()), AuditCapture { writer, buffer }, @@ -132,7 +132,11 @@ impl Fixture { ); let audit = match override_audit { Some(audit) => audit, - None => ToolAuditLog::new(AuditWriter::open(destination).await.expect("audit opens")), + None => ToolAuditLog::new( + AuditWriter::open_without_posture(destination) + .await + .expect("audit opens"), + ), }; let (binding, provider) = breg_binding_for_test( ®istry_config, diff --git a/crates/registry-breg-mcp/src/runtime.rs b/crates/registry-breg-mcp/src/runtime.rs index c47c51a907..9660d01452 100644 --- a/crates/registry-breg-mcp/src/runtime.rs +++ b/crates/registry-breg-mcp/src/runtime.rs @@ -234,7 +234,7 @@ pub async fn build(config: &RuntimeConfig) -> Result { .audit .destination() .map_err(|error| StartupError::Audit(error.to_string()))?; - let audit = ToolAuditLog::new(AuditWriter::open(destination).await?); + let audit = ToolAuditLog::new(AuditWriter::open_without_posture(destination).await?); let resource = config.resource_server.resource.to_url(); let info = GatewayInfo::new( "breg-mcp", diff --git a/crates/registry-breg-review/src/journal.rs b/crates/registry-breg-review/src/journal.rs index b77d6ade2e..42d53d984f 100644 --- a/crates/registry-breg-review/src/journal.rs +++ b/crates/registry-breg-review/src/journal.rs @@ -219,7 +219,7 @@ mod tests { } fn journal(lines: &Lines) -> (Journal, AuditWriter) { - let writer = AuditWriter::from_line_sink(Box::new(lines.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(lines.clone())); let journal = Journal::new( writer.clone(), AuditProfile::unkeyed_dev_only().key_hasher(), diff --git a/crates/registry-breg-review/src/lib.rs b/crates/registry-breg-review/src/lib.rs index 240b6c8afb..f405f55fb4 100644 --- a/crates/registry-breg-review/src/lib.rs +++ b/crates/registry-breg-review/src/lib.rs @@ -683,7 +683,7 @@ async fn build(config: RuntimeConfig, writer: Option) -> Result writer, - None => AuditWriter::open( + None => AuditWriter::open_without_posture( config .audit .destination() diff --git a/crates/registry-breg-review/tests/support/mod.rs b/crates/registry-breg-review/tests/support/mod.rs index a4f2204e4e..567b045082 100644 --- a/crates/registry-breg-review/tests/support/mod.rs +++ b/crates/registry-breg-review/tests/support/mod.rs @@ -1210,7 +1210,9 @@ impl Harness { .expect("runtime document loads"); let router = match sink { Some(sink) => { - let writer = registry_platform_audit::AuditWriter::from_line_sink(Box::new(sink)); + let writer = registry_platform_audit::AuditWriter::from_line_sink_without_posture( + Box::new(sink), + ); registry_breg_review::router_with_audit_writer(config, writer).await } None => registry_breg_review::router(config).await, diff --git a/crates/registry-breg/src/audit.rs b/crates/registry-breg/src/audit.rs index cb97c254ed..1c0fbd6e22 100644 --- a/crates/registry-breg/src/audit.rs +++ b/crates/registry-breg/src/audit.rs @@ -89,7 +89,7 @@ impl RegistryAudit { .destination() .for_process(COMPANION_PROCESS_ROLE) .map_err(|_| RegistryAuditError::Unavailable)?; - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|_| RegistryAuditError::Unavailable)?; Ok(Self::new(profile, writer)) @@ -1316,7 +1316,9 @@ pub mod test_support { /// process appending to the same destination would. #[must_use] pub fn audit(&self, profile: AuditProfile) -> RegistryAudit { - let writer = AuditWriter::from_line_sink(Box::new(CaptureSink(Arc::clone(&self.0)))); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(CaptureSink( + Arc::clone(&self.0), + ))); self.0 .lock() .expect("audit capture lock") diff --git a/crates/registry-breg/src/startup.rs b/crates/registry-breg/src/startup.rs index fd4b09c67a..c0f06e982e 100644 --- a/crates/registry-breg/src/startup.rs +++ b/crates/registry-breg/src/startup.rs @@ -1564,7 +1564,7 @@ async fn prepare_verified_package_with_key_source( /// refuses to start instead of interleaving entries. async fn open_registry_audit(config: &RuntimeConfig) -> Result { let profile = config.audit_profile().map_err(|_| StartupError::Audit)?; - let writer = AuditWriter::open(config.audit().destination().clone()) + let writer = AuditWriter::open_without_posture(config.audit().destination().clone()) .await .map_err(|error| StartupError::AuditDestination(error.operator_description()))?; Ok(RegistryAudit::new(profile, writer)) @@ -1597,7 +1597,7 @@ fn check_registry_audit(config: &RuntimeConfig) -> Result { .map_err(|error| StartupError::AuditDestination(error.operator_description()))?; Ok(RegistryAudit::new( profile, - AuditWriter::from_line_sink(Box::new(RefuseEveryEntry)), + AuditWriter::from_line_sink_without_posture(Box::new(RefuseEveryEntry)), )) } diff --git a/crates/registry-breg/tests/postgres_proposal_security.rs b/crates/registry-breg/tests/postgres_proposal_security.rs index 5d7df42e49..efc02483ae 100644 --- a/crates/registry-breg/tests/postgres_proposal_security.rs +++ b/crates/registry-breg/tests/postgres_proposal_security.rs @@ -1410,7 +1410,7 @@ async fn proposal_disclosures_refuse_a_signed_grant_expiring_during_terminal_aud let entries = Arc::new(std::sync::Mutex::new(Vec::new())); let audit = RegistryAudit::new( AuditProfile::production_from_secret_bytes(vec![0x61; 32].into()).unwrap(), - AuditWriter::from_line_sink(Box::new(DelayedTerminal { + AuditWriter::from_line_sink_without_posture(Box::new(DelayedTerminal { expiry, reached: reached.clone(), was_current: was_current.clone(), diff --git a/crates/registry-breg/tests/postgres_startup.rs b/crates/registry-breg/tests/postgres_startup.rs index 33910d0b13..934e4b856d 100644 --- a/crates/registry-breg/tests/postgres_startup.rs +++ b/crates/registry-breg/tests/postgres_startup.rs @@ -2801,7 +2801,7 @@ async fn assert_audit_destination_has_one_writer_and_checks_take_none( serving_config: &Path, unopened: &Path, ) { - let serving_writer = registry_platform_audit::AuditWriter::open( + let serving_writer = registry_platform_audit::AuditWriter::open_without_posture( registry_platform_audit::AuditDestination::from_settings( registry_platform_audit::AuditDestinationKind::File, Some(configured_audit_path(serving_config)), diff --git a/crates/registry-casework/src/audit.rs b/crates/registry-casework/src/audit.rs index 034b8b6043..a6f2e358d8 100644 --- a/crates/registry-casework/src/audit.rs +++ b/crates/registry-casework/src/audit.rs @@ -885,7 +885,7 @@ mod capture { #[must_use] pub fn capture() -> (Self, AuditCapture) { let capture = AuditCapture::default(); - let writer = AuditWriter::from_line_sink(Box::new(capture.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(capture.clone())); let audit = Self::new(writer.clone(), AuditKeyHasher::unkeyed_dev_only()); { let mut state = capture.0.lock().expect("audit capture"); diff --git a/crates/registry-casework/src/runtime.rs b/crates/registry-casework/src/runtime.rs index 7767745520..85143b7363 100644 --- a/crates/registry-casework/src/runtime.rs +++ b/crates/registry-casework/src/runtime.rs @@ -778,7 +778,7 @@ pub async fn open_audit( .for_process(process) .map_err(|error| RuntimeError::AuditDestination(error.to_string()))?; } - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|error| RuntimeError::AuditDestination(error.operator_description()))?; Ok(crate::CaseworkAudit::new( diff --git a/crates/registry-coordinator/src/deployment.rs b/crates/registry-coordinator/src/deployment.rs index 7d88762346..be210b17f2 100644 --- a/crates/registry-coordinator/src/deployment.rs +++ b/crates/registry-coordinator/src/deployment.rs @@ -510,7 +510,7 @@ async fn open_named( } else { destination }; - let audit = AuditWriter::open(destination) + let audit = AuditWriter::open_without_posture(destination) .await .map_err(audit_open_refusal)?; let security = StoreSecurity { @@ -1081,8 +1081,10 @@ mod tests { AuditDestination::File(FileDestination::new(root.path().join("audit.jsonl")).unwrap()) .for_process("apply") .unwrap(); - let first = AuditWriter::open(destination.clone()).await.unwrap(); - let error = match AuditWriter::open(destination.clone()).await { + let first = AuditWriter::open_without_posture(destination.clone()) + .await + .unwrap(); + let error = match AuditWriter::open_without_posture(destination.clone()).await { Ok(_) => panic!("a second writer must not acquire the same companion"), Err(error) => error, }; @@ -1093,7 +1095,9 @@ mod tests { Some("restore writable durable audit custody (sink-locked)") ); drop(first); - let reopened = AuditWriter::open(destination).await.unwrap(); + let reopened = AuditWriter::open_without_posture(destination) + .await + .unwrap(); drop(reopened); root.close().unwrap(); } diff --git a/crates/registry-coordinator/src/store.rs b/crates/registry-coordinator/src/store.rs index 3c0cfa6263..03be4ea620 100644 --- a/crates/registry-coordinator/src/store.rs +++ b/crates/registry-coordinator/src/store.rs @@ -719,7 +719,7 @@ impl Store { StoreSecurity { database_id: namespace.to_owned(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32])?, - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) diff --git a/crates/registry-coordinator/tests/calendar_trigger_authoring.rs b/crates/registry-coordinator/tests/calendar_trigger_authoring.rs index e5e97b9e99..ba8bf30bfd 100644 --- a/crates/registry-coordinator/tests/calendar_trigger_authoring.rs +++ b/crates/registry-coordinator/tests/calendar_trigger_authoring.rs @@ -230,7 +230,7 @@ impl Fixture { [0x22; 32], ) .unwrap(), - audit: AuditWriter::from_line_sink(Box::new(sink)), + audit: AuditWriter::from_line_sink_without_posture(Box::new(sink)), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) diff --git a/crates/registry-coordinator/tests/deployment_postgres.rs b/crates/registry-coordinator/tests/deployment_postgres.rs index e2a8396a30..60d78830d7 100644 --- a/crates/registry-coordinator/tests/deployment_postgres.rs +++ b/crates/registry-coordinator/tests/deployment_postgres.rs @@ -1384,10 +1384,9 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re database_id: "router-test".into(), keys: StateKeys::new(1, BTreeMap::from([(1, state_key)]), admission_key) .unwrap(), - audit: AuditWriter::from_line_sink(Box::new(RefuseAcceptedResponse( - attempts.clone(), - "admit", - ))), + audit: AuditWriter::from_line_sink_without_posture(Box::new( + RefuseAcceptedResponse(attempts.clone(), "admit"), + )), audit_profile: AuditProfile::production_from_secret_bytes( zeroize::Zeroizing::new(fs::read(root_path.join("audit-key")).unwrap()), ) @@ -1474,10 +1473,9 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re database_id: "router-test".into(), keys: StateKeys::new(1, BTreeMap::from([(1, state_key)]), admission_key) .unwrap(), - audit: AuditWriter::from_line_sink(Box::new(RefuseAcceptedResponse( - status_attempts.clone(), - "status", - ))), + audit: AuditWriter::from_line_sink_without_posture(Box::new( + RefuseAcceptedResponse(status_attempts.clone(), "status"), + )), audit_profile: AuditProfile::production_from_secret_bytes( zeroize::Zeroizing::new(fs::read(root_path.join("audit-key")).unwrap()), ) diff --git a/crates/registry-coordinator/tests/postgres_state.rs b/crates/registry-coordinator/tests/postgres_state.rs index 4c0418333a..1c96eaff1c 100644 --- a/crates/registry-coordinator/tests/postgres_state.rs +++ b/crates/registry-coordinator/tests/postgres_state.rs @@ -2691,7 +2691,7 @@ async fn terminal_retention_keeps_spent_idempotency_keys_across_payload_rotation [0x22; 32], ) .unwrap(), - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) @@ -2886,7 +2886,7 @@ async fn audit_failure_prevents_admission_and_payload_release() { StoreSecurity { database_id: h.namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32]).unwrap(), - audit: AuditWriter::from_line_sink(Box::new(Fails)), + audit: AuditWriter::from_line_sink_without_posture(Box::new(Fails)), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) @@ -2949,7 +2949,7 @@ async fn changing_admission_key_cannot_reopen_a_spent_identity() { StoreSecurity { database_id: h.namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x99; 32]).unwrap(), - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) @@ -2965,7 +2965,7 @@ async fn changing_admission_key_cannot_reopen_a_spent_identity() { StoreSecurity { database_id: h.namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x55; 32])]), [0x22; 32]).unwrap(), - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) diff --git a/crates/registry-coordinator/tests/read_in_force_postgres.rs b/crates/registry-coordinator/tests/read_in_force_postgres.rs index 5d65a64236..b7cba8d1a7 100644 --- a/crates/registry-coordinator/tests/read_in_force_postgres.rs +++ b/crates/registry-coordinator/tests/read_in_force_postgres.rs @@ -120,7 +120,7 @@ async fn two_records_in_force_hold_the_run_until_an_operator_retries() { database_id: namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32]) .expect("test keys"), - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) diff --git a/crates/registry-coordinator/tests/read_lease_recovery.rs b/crates/registry-coordinator/tests/read_lease_recovery.rs index e5cd7b74fb..35dc5674ae 100644 --- a/crates/registry-coordinator/tests/read_lease_recovery.rs +++ b/crates/registry-coordinator/tests/read_lease_recovery.rs @@ -142,7 +142,7 @@ impl Harness { database_id: namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32]) .expect("test keys"), - audit: AuditWriter::from_line_sink(Box::new(capture.clone())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(capture.clone())), audit_profile: AuditProfile::production_from_secret_bytes( zeroize::Zeroizing::new(vec![0x33; 32]), ) diff --git a/crates/registry-coordinator/tests/recovery_audit.rs b/crates/registry-coordinator/tests/recovery_audit.rs index 946b4dd761..26edc4cbc4 100644 --- a/crates/registry-coordinator/tests/recovery_audit.rs +++ b/crates/registry-coordinator/tests/recovery_audit.rs @@ -99,7 +99,7 @@ impl Harness { StoreSecurity { database_id: self.namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32]).unwrap(), - audit: AuditWriter::from_line_sink(Box::new(sink)), + audit: AuditWriter::from_line_sink_without_posture(Box::new(sink)), audit_profile: profile(), }, None, diff --git a/crates/registry-documents/src/audit.rs b/crates/registry-documents/src/audit.rs index 89399089de..613f2c0e89 100644 --- a/crates/registry-documents/src/audit.rs +++ b/crates/registry-documents/src/audit.rs @@ -164,7 +164,7 @@ mod tests { AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new(vec![7u8; 32])) .unwrap(); DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(std::io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), profile.key_hasher(), ) } diff --git a/crates/registry-documents/src/runtime.rs b/crates/registry-documents/src/runtime.rs index 48d6f68822..baecd38dc4 100644 --- a/crates/registry-documents/src/runtime.rs +++ b/crates/registry-documents/src/runtime.rs @@ -754,7 +754,7 @@ async fn open_audit( .for_process(process) .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; } - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; Ok(DocumentsAudit::new(writer, profile.key_hasher())) diff --git a/crates/registry-documents/tests/postgres_documents.rs b/crates/registry-documents/tests/postgres_documents.rs index 5fe30762c1..7067397615 100644 --- a/crates/registry-documents/tests/postgres_documents.rs +++ b/crates/registry-documents/tests/postgres_documents.rs @@ -1180,7 +1180,7 @@ async fn a_verification_audit_failure_refuses_the_claim_and_records_no_verdict() .await .unwrap(); let audit = DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(FailingSink)), + AuditWriter::from_line_sink_without_posture(Box::new(FailingSink)), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) @@ -2537,7 +2537,7 @@ async fn a_request_audit_failure_refuses_the_upload_and_the_download() { fn failing_audit() -> DocumentsAudit { DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(FailingSink)), + AuditWriter::from_line_sink_without_posture(Box::new(FailingSink)), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) @@ -2752,7 +2752,9 @@ async fn a_response_audit_failure_after_commit_answers_unavailable_and_the_retry .await .expect("the runtime prepares") .with_audit(DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(FirstLineSink { kept: kept.clone() })), + AuditWriter::from_line_sink_without_posture(Box::new(FirstLineSink { + kept: kept.clone(), + })), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) diff --git a/crates/registry-documents/tests/postgres_operator.rs b/crates/registry-documents/tests/postgres_operator.rs index 1fd24b327e..c96ba8cb64 100644 --- a/crates/registry-documents/tests/postgres_operator.rs +++ b/crates/registry-documents/tests/postgres_operator.rs @@ -1463,7 +1463,7 @@ async fn replay_audited( .await .unwrap(); let audit = DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(LimitedSink { lines })), + AuditWriter::from_line_sink_without_posture(Box::new(LimitedSink { lines })), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) @@ -1836,7 +1836,7 @@ async fn erasure_replay_audited( .await .unwrap(); let audit = DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(LimitedSink { lines })), + AuditWriter::from_line_sink_without_posture(Box::new(LimitedSink { lines })), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) diff --git a/crates/registry-documents/tests/support/mod.rs b/crates/registry-documents/tests/support/mod.rs index 84b8d99019..3f7a88e12a 100644 --- a/crates/registry-documents/tests/support/mod.rs +++ b/crates/registry-documents/tests/support/mod.rs @@ -42,7 +42,9 @@ pub fn database_url() -> String { /// An independent in-memory audit sink for direct worker boundary tests. pub fn worker_audit() -> registry_documents::audit::DocumentsAudit { registry_documents::audit::DocumentsAudit::new( - registry_platform_audit::AuditWriter::from_line_sink(Box::new(Vec::::new())), + registry_platform_audit::AuditWriter::from_line_sink_without_posture(Box::new( + Vec::::new(), + )), registry_platform_audit::AuditProfile::production_from_secret_bytes( zeroize::Zeroizing::new(b"documents-canary-audit-key-not-a-secret".to_vec()), ) diff --git a/crates/registry-evidence-oid4vci/src/audit.rs b/crates/registry-evidence-oid4vci/src/audit.rs index 77dbe66cc2..277c6d0267 100644 --- a/crates/registry-evidence-oid4vci/src/audit.rs +++ b/crates/registry-evidence-oid4vci/src/audit.rs @@ -69,7 +69,7 @@ impl DeliveryAudit { master_secret: Zeroizing>, ) -> Result { let profile = AuditProfile::production_from_secret_bytes(master_secret)?; - let writer = AuditWriter::open(destination).await?; + let writer = AuditWriter::open_without_posture(destination).await?; Ok(Self { writer, key_hasher: profile.key_hasher(), diff --git a/crates/registry-evidence-oid4vci/src/service.rs b/crates/registry-evidence-oid4vci/src/service.rs index cd07624bf5..cce746989e 100644 --- a/crates/registry-evidence-oid4vci/src/service.rs +++ b/crates/registry-evidence-oid4vci/src/service.rs @@ -1965,7 +1965,7 @@ mod tests { fn test_audit_with(sink: Box) -> Arc { Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(sink), + AuditWriter::from_line_sink_without_posture(sink), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), diff --git a/crates/registry-evidence-oid4vci/tests/audit_attribution.rs b/crates/registry-evidence-oid4vci/tests/audit_attribution.rs index b65935a33a..2b92cef986 100644 --- a/crates/registry-evidence-oid4vci/tests/audit_attribution.rs +++ b/crates/registry-evidence-oid4vci/tests/audit_attribution.rs @@ -46,7 +46,7 @@ impl CapturedLines { async fn offer_audit_refuses_an_exchange_without_a_verified_identity() { let captured = CapturedLines::default(); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(captured.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the audit profile is valid"); @@ -64,7 +64,7 @@ async fn offer_audit_refuses_an_exchange_without_a_verified_identity() { async fn offer_and_delivery_audit_is_correlated_and_privacy_safe() { let captured = CapturedLines::default(); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(captured.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the audit profile is valid"); diff --git a/crates/registry-evidence-oid4vci/tests/draft13_profile.rs b/crates/registry-evidence-oid4vci/tests/draft13_profile.rs index 77fff8744b..a08676207f 100644 --- a/crates/registry-evidence-oid4vci/tests/draft13_profile.rs +++ b/crates/registry-evidence-oid4vci/tests/draft13_profile.rs @@ -314,7 +314,7 @@ fn harness(draft13: bool) -> Harness { Arc::clone(&issuer) as Arc, Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(std::io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), @@ -1255,7 +1255,7 @@ async fn inspect_shows_the_draft13_metadata_only_when_the_profile_is_on() { Arc::new(SigningIssuer::new()) as Arc, Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(std::io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), diff --git a/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs b/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs index 8e27f9626e..26827cc5fe 100644 --- a/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs +++ b/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs @@ -366,7 +366,7 @@ fn deployment() -> (tempfile::TempDir, Arc, TestServer) { Arc::clone(&issuer) as Arc, Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), diff --git a/crates/registry-evidence-oid4vci/tests/offer_authorization.rs b/crates/registry-evidence-oid4vci/tests/offer_authorization.rs index cd83147b5e..f86b1c689a 100644 --- a/crates/registry-evidence-oid4vci/tests/offer_authorization.rs +++ b/crates/registry-evidence-oid4vci/tests/offer_authorization.rs @@ -222,7 +222,7 @@ async fn restricted_and_unrestricted_clients_audit_the_same_canonical_azp() { let captured = AuditCapture::default(); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(captured.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the audit profile loads"); @@ -264,7 +264,7 @@ async fn a_sub_only_offer_token_is_accepted_and_audited_without_inventing_a_clie let captured = AuditCapture::default(); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(captured.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the audit profile loads"); diff --git a/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs b/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs index da86bc440d..25e4fe04c2 100644 --- a/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs +++ b/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs @@ -404,7 +404,7 @@ fn service_with_issuer( issuer, Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), @@ -874,7 +874,7 @@ async fn post_claim_evidence_failures_are_terminal_and_never_restore_the_token() let audit_capture = AuditCapture::default(); let audit = Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(audit_capture.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(audit_capture.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), @@ -943,7 +943,7 @@ async fn a_post_claim_timeout_is_terminal_and_never_restores_the_token() { let audit_capture = AuditCapture::default(); let audit = Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(audit_capture.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(audit_capture.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), diff --git a/crates/registry-evidence-oid4vci/tests/store_contract.rs b/crates/registry-evidence-oid4vci/tests/store_contract.rs index 405ef69a79..9d594f8c87 100644 --- a/crates/registry-evidence-oid4vci/tests/store_contract.rs +++ b/crates/registry-evidence-oid4vci/tests/store_contract.rs @@ -1093,7 +1093,7 @@ store: std::fs::write(&path, SERVICE_CONFIG).expect("write the test deployment"); let config = DeliveryConfig::load(&path).expect("the test deployment loads"); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"); diff --git a/crates/registry-evidence-oid4vp/src/audit.rs b/crates/registry-evidence-oid4vp/src/audit.rs index b1cdee7998..6ca40e502b 100644 --- a/crates/registry-evidence-oid4vp/src/audit.rs +++ b/crates/registry-evidence-oid4vp/src/audit.rs @@ -47,7 +47,7 @@ impl SessionAudit { master_secret: Zeroizing>, ) -> Result { let profile = AuditProfile::production_from_secret_bytes(master_secret)?; - let writer = AuditWriter::open(destination).await?; + let writer = AuditWriter::open_without_posture(destination).await?; Ok(Self { writer, key_hasher: profile.key_hasher(), diff --git a/crates/registry-evidence/src/audit.rs b/crates/registry-evidence/src/audit.rs index 8b220188cd..55f914de27 100644 --- a/crates/registry-evidence/src/audit.rs +++ b/crates/registry-evidence/src/audit.rs @@ -12,7 +12,7 @@ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use registry_platform_audit::{ AuditDestination, AuditEntry, AuditError, AuditKeyHasher, AuditPhase as EntryPhase, AuditProfile, AuditSegments, AuditUnavailable, AuditWriter, AuthorizationAuditEvent, - AuthorizationOutcome, + AuthorizationOutcome, StoredAuditEntry, }; use registry_platform_crypto::canonicalize_json; use registry_platform_oidc::ActorKind; @@ -1260,7 +1260,7 @@ impl EvidenceAuditLog { key_version: u32, ) -> Result { let key_hasher = identifier_key_hasher(master_secret, key_version)?; - let writer = AuditWriter::open(destination).await?; + let writer = AuditWriter::open_without_posture(destination).await?; Ok(Self { writer, key_hasher, @@ -1269,7 +1269,7 @@ impl EvidenceAuditLog { } /// Wrap a writer that is already open, such as one built with - /// [`AuditWriter::from_line_sink`] to observe or refuse writes. + /// [`AuditWriter::from_line_sink_without_posture`] to observe or refuse writes. pub fn with_writer( writer: AuditWriter, master_secret: Vec, @@ -1580,18 +1580,6 @@ struct LocalPublicCheckOperationEvent { safe_error_category: Option, } -/// One stored line as the platform writer lays it out. -#[derive(Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct StoredAuditEntry { - schema: String, - event_id: String, - time: String, - phase: EntryPhase, - correlation: String, - record: serde_json::Value, -} - /// Largest stored line the local reader accepts, matching the writer's entry /// bound. const MAXIMUM_LOCAL_AUDIT_LINE_BYTES: u64 = 1024 * 1024; @@ -2356,8 +2344,7 @@ fn read_local_audit_file( if line.pop() != Some(b'\n') { return Err(invalid_audit_data()); } - let entry: StoredAuditEntry = - serde_json::from_slice(&line).map_err(|_| invalid_audit_data())?; + let entry = AuditSegments::parse_line(&line)?; collector.collect(entry)?; } } @@ -3621,7 +3608,7 @@ mod tests { fn captured_log() -> (EvidenceAuditLog, CapturedLines) { let captured = CapturedLines::default(); - let writer = AuditWriter::from_line_sink(Box::new(captured.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())); let log = EvidenceAuditLog::with_writer(writer, MASTER.to_vec(), 1).expect("audit key derives"); (log, captured) @@ -3642,7 +3629,7 @@ mod tests { /// Write entries exactly as given, bypassing the native record checks, so /// the local reader's own checks are what a test exercises. async fn append_raw_entries(path: &Path, entries: Vec) { - let writer = AuditWriter::open(file_destination(path)) + let writer = AuditWriter::open_without_posture(file_destination(path)) .await .expect("raw writer opens"); for entry in entries { @@ -3718,7 +3705,8 @@ mod tests { #[test] fn pseudonyms_keep_key_epochs_distinguishable() { let pseudonym = |master: &[u8], version: u32| { - let writer = AuditWriter::from_line_sink(Box::new(CapturedLines::default())); + let writer = + AuditWriter::from_line_sink_without_posture(Box::new(CapturedLines::default())); EvidenceAuditLog::with_writer(writer, master.to_vec(), version) .expect("audit key derives") .pseudonym("requester-v1", "urn:example:trust", b"principal-canary") @@ -3815,6 +3803,7 @@ mod tests { "correlation", "eventId", "phase", + "posture", "record", "schema", "time" @@ -3833,7 +3822,7 @@ mod tests { #[tokio::test] async fn a_refused_write_stops_every_later_append() { - let writer = AuditWriter::from_line_sink(Box::new(RefusingSink)); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(RefusingSink)); let log = EvidenceAuditLog::with_writer(writer, MASTER.to_vec(), 1).expect("audit key derives"); assert!(matches!( @@ -3879,7 +3868,7 @@ mod tests { .expect("audit reads") .lines() .map(|line| { - let entry: StoredAuditEntry = serde_json::from_str(line).expect("entry parses"); + let entry = AuditSegments::parse_line(line.as_bytes()).expect("entry parses"); assert_eq!(entry.schema, AUDIT_SCHEMA); assert_eq!(entry.phase, EntryPhase::Request); entry.correlation diff --git a/crates/registry-evidence/src/authority.rs b/crates/registry-evidence/src/authority.rs index eeecd4bf0f..f5ebf703a8 100644 --- a/crates/registry-evidence/src/authority.rs +++ b/crates/registry-evidence/src/authority.rs @@ -1080,7 +1080,9 @@ mod tests { accepted, }; let log = EvidenceAuditLog::with_writer( - registry_platform_audit::AuditWriter::from_line_sink(Box::new(sink.clone())), + registry_platform_audit::AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + )), b"activation-audit-key-canary-32-bytes".to_vec(), 1, ) diff --git a/crates/registry-evidence/src/runtime_tests.rs b/crates/registry-evidence/src/runtime_tests.rs index f0de73decb..5c9788d1a8 100644 --- a/crates/registry-evidence/src/runtime_tests.rs +++ b/crates/registry-evidence/src/runtime_tests.rs @@ -3975,7 +3975,7 @@ async fn admitted_release_append_completes_and_returns_bytes_after_deadline() { let captured = Arc::new(Mutex::new(Vec::new())); let release_started = Arc::new(Mutex::new(None)); let audit = EvidenceAuditLog::with_writer( - AuditWriter::from_line_sink(Box::new(SlowDisclosureSink { + AuditWriter::from_line_sink_without_posture(Box::new(SlowDisclosureSink { bytes: Arc::clone(&captured), release_started: Arc::clone(&release_started), delay: Duration::from_millis(1_500), diff --git a/crates/registry-evidence/tests/source_authority_paths.rs b/crates/registry-evidence/tests/source_authority_paths.rs index dbe54eb5e8..ce6121b941 100644 --- a/crates/registry-evidence/tests/source_authority_paths.rs +++ b/crates/registry-evidence/tests/source_authority_paths.rs @@ -323,7 +323,7 @@ impl Write for RecordingSink { impl RecordingSink { fn audit(&self) -> EvidenceAuditLog { EvidenceAuditLog::with_writer( - AuditWriter::from_line_sink(Box::new(self.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(self.clone())), b"source-authority-audit-key-32-bytes".to_vec(), 1, ) diff --git a/crates/registry-mcp-edge/src/audit.rs b/crates/registry-mcp-edge/src/audit.rs index 4474eb8a26..3c355b1c78 100644 --- a/crates/registry-mcp-edge/src/audit.rs +++ b/crates/registry-mcp-edge/src/audit.rs @@ -102,10 +102,12 @@ impl ToolAuditLog { } } - Self::new(AuditWriter::from_line_sink(Box::new(RefusingSink { - accepted, - writes: Arc::new(Mutex::new(0)), - }))) + Self::new(AuditWriter::from_line_sink_without_posture(Box::new( + RefusingSink { + accepted, + writes: Arc::new(Mutex::new(0)), + }, + ))) } } diff --git a/crates/registry-mcp-edge/src/compatibility_tests/audit.rs b/crates/registry-mcp-edge/src/compatibility_tests/audit.rs index c253f7b607..36718e005c 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/audit.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/audit.rs @@ -26,7 +26,7 @@ impl Write for Buffer { fn fixture() -> (ToolAuditLog, AuditWriter, Buffer, AuditOptions) { let buffer = Buffer::default(); - let writer = AuditWriter::from_line_sink(Box::new(buffer.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())); ( ToolAuditLog::new(writer.clone()), writer, diff --git a/crates/registry-mcp-edge/src/compatibility_tests/server.rs b/crates/registry-mcp-edge/src/compatibility_tests/server.rs index 2938e25147..8beab704d1 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/server.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/server.rs @@ -67,7 +67,9 @@ fn gateway_core() -> Arc { ["unused".to_owned()], ) .expect("binding"); - let audit = ToolAuditLog::new(AuditWriter::from_line_sink(Box::new(io::sink()))); + let audit = ToolAuditLog::new(AuditWriter::from_line_sink_without_posture(Box::new( + io::sink(), + ))); Arc::new( GatewayCore::new( [binding], diff --git a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs index 2b2e8acb62..9cd57e10d1 100644 --- a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs +++ b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs @@ -77,7 +77,9 @@ fn gateway_core() -> Arc { ["unused".to_owned()], ) .expect("binding"); - let audit = ToolAuditLog::new(AuditWriter::from_line_sink(Box::new(io::sink()))); + let audit = ToolAuditLog::new(AuditWriter::from_line_sink_without_posture(Box::new( + io::sink(), + ))); Arc::new( GatewayCore::new( [binding], diff --git a/crates/registry-mcp-edge/src/tests.rs b/crates/registry-mcp-edge/src/tests.rs index e322f12c20..83ee149a09 100644 --- a/crates/registry-mcp-edge/src/tests.rs +++ b/crates/registry-mcp-edge/src/tests.rs @@ -260,7 +260,9 @@ fn delegation() -> Delegation { fn audit() -> (ToolAuditLog, Buffer) { let buffer = Buffer::default(); ( - ToolAuditLog::new(AuditWriter::from_line_sink(Box::new(buffer.clone()))), + ToolAuditLog::new(AuditWriter::from_line_sink_without_posture(Box::new( + buffer.clone(), + ))), buffer, ) } diff --git a/crates/registry-mcp/src/runtime.rs b/crates/registry-mcp/src/runtime.rs index a74337a847..13b22d1739 100644 --- a/crates/registry-mcp/src/runtime.rs +++ b/crates/registry-mcp/src/runtime.rs @@ -435,7 +435,7 @@ pub async fn build(config: &RuntimeConfig) -> Result { ) })?; let audit = ToolAuditLog::new( - AuditWriter::open(destination) + AuditWriter::open_without_posture(destination) .await .map_err(audit_failure)?, ); diff --git a/crates/registry-messaging/src/audit.rs b/crates/registry-messaging/src/audit.rs index 23aec5fe39..8eae7b7159 100644 --- a/crates/registry-messaging/src/audit.rs +++ b/crates/registry-messaging/src/audit.rs @@ -187,7 +187,7 @@ pub(crate) mod tests { pub(crate) fn memory_journal() -> (Arc, MessagingAudit) { let sink = Arc::new(MemorySink::default()); - let writer = AuditWriter::from_line_sink(Box::new((*sink).clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new((*sink).clone())); ( sink, MessagingAudit::new(writer, AuditKeyHasher::unkeyed_dev_only()), @@ -201,7 +201,7 @@ pub(crate) mod tests { ) .unwrap(); let audit = MessagingAudit::new( - AuditWriter::from_line_sink(Box::new(io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(io::sink())), profile.key_hasher(), ); let identity = CallerIdentity { diff --git a/crates/registry-messaging/src/runtime.rs b/crates/registry-messaging/src/runtime.rs index a51af188c2..f7c83e7ad6 100644 --- a/crates/registry-messaging/src/runtime.rs +++ b/crates/registry-messaging/src/runtime.rs @@ -409,7 +409,7 @@ pub async fn assemble( audit_secret.expose_secret().to_vec(), )) .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; - let writer = AuditWriter::open(config.audit.destination()?) + let writer = AuditWriter::open_without_posture(config.audit.destination()?) .await .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; let audit = Arc::new(MessagingAudit::new(writer, audit_profile.key_hasher())); @@ -638,7 +638,7 @@ async fn open_audit( .for_process(process) .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; } - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; Ok(MessagingAudit::new(writer, profile.key_hasher())) @@ -836,11 +836,12 @@ mod tests { let profile = AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new(vec![7u8; 32])) .unwrap(); - let writer = AuditWriter::open(registry_platform_audit::AuditDestination::File( - registry_platform_audit::FileDestination::new(&audit).unwrap(), - )) - .await - .unwrap(); + let writer = + AuditWriter::open_without_posture(registry_platform_audit::AuditDestination::File( + registry_platform_audit::FileDestination::new(&audit).unwrap(), + )) + .await + .unwrap(); let journal = MessagingAudit::new(writer, profile.key_hasher()); journal .append_background( diff --git a/crates/registry-messaging/tests/postgres_callbacks.rs b/crates/registry-messaging/tests/postgres_callbacks.rs index 8601570b69..99cd19dcd4 100644 --- a/crates/registry-messaging/tests/postgres_callbacks.rs +++ b/crates/registry-messaging/tests/postgres_callbacks.rs @@ -569,7 +569,9 @@ async fn a_post_commit_callback_audit_refusal_retries_without_duplicate_history( let id = deployment.sent().await; let reference = reference_for(id); let sink = RefusingAuditSink::after(1); - let audit = test_audit(AuditWriter::from_line_sink(Box::new(sink.clone()))); + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + ))); let app = deployment.harness.app_with_audit(audit).await; let (status, problem) = send_app( @@ -622,7 +624,7 @@ async fn a_receipt_audit_failure_names_whether_the_receipt_was_applied() { let unavailable = record_receipt( &deployment.harness.store, - &test_audit(AuditWriter::from_line_sink(Box::new( + &test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(0), ))), "sms-gateway", @@ -638,7 +640,7 @@ async fn a_receipt_audit_failure_names_whether_the_receipt_was_applied() { let unconfirmed = record_receipt( &deployment.harness.store, - &test_audit(AuditWriter::from_line_sink(Box::new( + &test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(1), ))), "sms-gateway", diff --git a/crates/registry-messaging/tests/postgres_messages.rs b/crates/registry-messaging/tests/postgres_messages.rs index 167dce0dc8..1ab086a939 100644 --- a/crates/registry-messaging/tests/postgres_messages.rs +++ b/crates/registry-messaging/tests/postgres_messages.rs @@ -162,7 +162,7 @@ async fn an_accepted_submission_records_its_rendered_parts_and_answers_a_receipt #[tokio::test] async fn an_audit_request_refusal_records_no_submission() { let harness = Harness::start().await; - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(0), ))); let app = harness.app_with_audit(audit).await; @@ -193,7 +193,7 @@ async fn an_audit_request_refusal_records_no_submission() { #[tokio::test] async fn a_post_commit_audit_refusal_replays_one_committed_submission_receipt() { let harness = Harness::start().await; - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(1), ))); let app = harness.app_with_audit(audit).await; @@ -241,7 +241,7 @@ async fn a_post_commit_audit_refusal_replays_one_committed_submission_receipt() #[tokio::test] async fn readiness_fails_when_the_audit_writer_loses_its_destination() { let harness = Harness::start().await; - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(0), ))); assert!(audit @@ -348,9 +348,9 @@ async fn an_exact_retry_across_an_audit_key_rotation_replays_and_never_sends_aga // caller's issuer and subject, so the rotation does not free it. let journal = RefusingAuditSink::after(usize::MAX); let rotated = harness - .app_with_audit(rotated_test_audit(AuditWriter::from_line_sink(Box::new( - journal.clone(), - )))) + .app_with_audit(rotated_test_audit( + AuditWriter::from_line_sink_without_posture(Box::new(journal.clone())), + )) .await; let (status, _, replay) = submit_to(rotated.clone(), &sender, "key-1", &email_submission()).await; @@ -1460,7 +1460,7 @@ async fn a_dispatch_core_refusal_is_reported_as_an_outcome_that_may_have_applied /// A message store over the harness's schema whose audit writer accepts /// only its first `accepted_writes` records. async fn store_with_audit(harness: &Harness, accepted_writes: usize) -> MessageStore { - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(accepted_writes), ))); let schema = harness.store.current_schema().await.unwrap(); @@ -1666,7 +1666,7 @@ async fn original_receipt_disclosure_requires_both_audit_entries() { StatusCode::ACCEPTED ); for accepted_writes in [0, 1] { - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(accepted_writes), ))); let app = harness.app_with_audit(audit).await; diff --git a/crates/registry-messaging/tests/postgres_retention.rs b/crates/registry-messaging/tests/postgres_retention.rs index 3cb9e40ed0..2a6070e2db 100644 --- a/crates/registry-messaging/tests/postgres_retention.rs +++ b/crates/registry-messaging/tests/postgres_retention.rs @@ -338,9 +338,11 @@ async fn a_record_is_deleted_record_days_after_a_terminal_state_with_everything_ let mut other = email_submission(); other["correlationId"] = serde_json::json!("another-body"); let rotated = harness - .app_with_audit(rotated_test_audit(AuditWriter::from_line_sink(Box::new( - RefusingAuditSink::after(usize::MAX), - )))) + .app_with_audit(rotated_test_audit( + AuditWriter::from_line_sink_without_posture(Box::new(RefusingAuditSink::after( + usize::MAX, + ))), + )) .await; for app in [harness.app.clone(), rotated] { for body in [email_submission(), other.clone()] { @@ -528,9 +530,11 @@ async fn a_spent_key_forgets_its_caller_once_its_receipt_is_erased_and_stays_spe let mut other = email_submission(); other["correlationId"] = serde_json::json!("another-body"); let rotated = harness - .app_with_audit(rotated_test_audit(AuditWriter::from_line_sink(Box::new( - RefusingAuditSink::after(usize::MAX), - )))) + .app_with_audit(rotated_test_audit( + AuditWriter::from_line_sink_without_posture(Box::new(RefusingAuditSink::after( + usize::MAX, + ))), + )) .await; for app in [harness.app.clone(), rotated] { for (body, status_code, code) in [ @@ -721,7 +725,9 @@ async fn an_audit_request_refusal_erases_nothing() { let id = harness.accepted(&email_submission()).await; settle_as(&harness, id, "delivered", 8).await; let sink = RefusingAuditSink::after(0); - let audit = test_audit(AuditWriter::from_line_sink(Box::new(sink.clone()))); + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + ))); let refused = erase_expired( &harness.store, @@ -745,7 +751,9 @@ async fn a_post_commit_retention_audit_refusal_leaves_erasure_committed() { let id = harness.accepted(&email_submission()).await; settle_as(&harness, id, "delivered", 8).await; let sink = RefusingAuditSink::after(1); - let audit = test_audit(AuditWriter::from_line_sink(Box::new(sink.clone()))); + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + ))); let refused = erase_expired( &harness.store, diff --git a/crates/registry-messaging/tests/support/mod.rs b/crates/registry-messaging/tests/support/mod.rs index 24a2309a7f..99325c9cfc 100644 --- a/crates/registry-messaging/tests/support/mod.rs +++ b/crates/registry-messaging/tests/support/mod.rs @@ -298,9 +298,11 @@ impl Harness { )) .expect("the audit profile"); let audit = Arc::new(MessagingAudit::new( - AuditWriter::open(config.audit.destination().expect("audit destination")) - .await - .expect("the audit writer"), + AuditWriter::open_without_posture( + config.audit.destination().expect("audit destination"), + ) + .await + .expect("the audit writer"), profile.key_hasher(), )); let loaded = config.load_package().expect("the package"); diff --git a/crates/registry-platform-audit/Cargo.toml b/crates/registry-platform-audit/Cargo.toml index b0f28e8d03..b39ba440da 100644 --- a/crates/registry-platform-audit/Cargo.toml +++ b/crates/registry-platform-audit/Cargo.toml @@ -15,6 +15,7 @@ schema = ["dep:schemars"] [dependencies] hmac.workspace = true +registry-platform-posture.workspace = true rustix.workspace = true schemars = { workspace = true, optional = true } serde.workspace = true diff --git a/crates/registry-platform-audit/README.md b/crates/registry-platform-audit/README.md index 29e50b782f..46aa5b2c82 100644 --- a/crates/registry-platform-audit/README.md +++ b/crates/registry-platform-audit/README.md @@ -6,7 +6,7 @@ authorization event shape for Registry Stack services. ## What It Provides - `AuditWriter`, the one audit writer every product uses. It appends one JSON - object per line (`schema`, `eventId`, `time`, `phase`, `correlation`, + object per line (`schema`, `eventId`, `time`, `phase`, `posture`, `correlation`, `record`): a `request` entry before protected I/O and a `response` entry with the outcome, both carrying the same `correlation`. - `AuditDestination::File` (durable: fsync with group commit, size rotation, @@ -23,12 +23,18 @@ authorization event shape for Registry Stack services. across products, using pseudonyms from each product's existing audit profile. - `require_audit_under` to keep an audit path under a persistent root. +Every new journal line records the writer's declared `posture` as +`development` or `production`. The transitional constructors record +`production`. Readers accept a missing posture on historical lines and +refuse a present value outside those two spellings. + ## Typical Use ```rust use registry_platform_audit::{ AuditDestination, AuditEntry, AuditProfile, AuditWriter, FileDestination, }; +use registry_platform_posture::Posture; use serde_json::json; use zeroize::Zeroizing; @@ -36,7 +42,7 @@ async fn write_audit_entries() -> Result<(), Box> { let master_secret = Zeroizing::new(std::fs::read("/run/secrets/registry-audit-hash")?); let profile = AuditProfile::production_from_secret_bytes(master_secret)?; let destination = FileDestination::new("/var/lib/registry/audit/audit.jsonl")?; - let writer = AuditWriter::open(AuditDestination::File(destination)).await?; + let writer = AuditWriter::open(AuditDestination::File(destination), Posture::Production).await?; let subject_ref = profile.key_hasher().hash("did:example:123"); writer diff --git a/crates/registry-platform-audit/src/lib.rs b/crates/registry-platform-audit/src/lib.rs index d76f458f70..d598e5a189 100644 --- a/crates/registry-platform-audit/src/lib.rs +++ b/crates/registry-platform-audit/src/lib.rs @@ -29,8 +29,9 @@ mod writer; pub use writer::{ AuditDestination, AuditDestinationError, AuditDestinationKind, AuditEntry, AuditPhase, AuditRequest, AuditSegments, AuditUnavailable, AuditUnavailableReason, AuditWriter, - FileDestination, SealedSegment, ABSOLUTE_AUDIT_PATH_PATTERN, DEFAULT_AUDIT_RETAIN_DAYS, - DEFAULT_AUDIT_ROTATE_BYTES, MAX_AUDIT_RETAIN_DAYS, MIN_AUDIT_ROTATE_BYTES, + FileDestination, SealedSegment, StoredAuditEntry, ABSOLUTE_AUDIT_PATH_PATTERN, + DEFAULT_AUDIT_RETAIN_DAYS, DEFAULT_AUDIT_ROTATE_BYTES, MAX_AUDIT_RETAIN_DAYS, + MIN_AUDIT_ROTATE_BYTES, }; use std::{ diff --git a/crates/registry-platform-audit/src/writer.rs b/crates/registry-platform-audit/src/writer.rs index 2109d6d39f..d0e43926bd 100644 --- a/crates/registry-platform-audit/src/writer.rs +++ b/crates/registry-platform-audit/src/writer.rs @@ -33,6 +33,7 @@ use std::{ time::{Duration, Instant, SystemTime}, }; +use registry_platform_posture::Posture; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use thiserror::Error; @@ -188,7 +189,7 @@ impl AuditEntry { &self.record } - fn to_line(&self) -> Result { + fn to_line(&self, posture: Posture) -> Result { let schema_valid = !self.schema.is_empty() && self.schema.len() <= MAX_SCHEMA_BYTES && self @@ -213,6 +214,7 @@ impl AuditEntry { event_id: Uuid::new_v4().to_string(), time, phase: self.phase, + posture: posture.as_str(), correlation: &self.correlation, record, }; @@ -233,6 +235,7 @@ struct WireEntry<'a> { event_id: String, time: String, phase: AuditPhase, + posture: &'static str, correlation: &'a str, record: &'a Map, } @@ -656,6 +659,7 @@ impl AuditDestination { /// The audit writer. Cheap to clone; clones share one destination. #[derive(Clone)] pub struct AuditWriter { + posture: Posture, inner: Arc, open: Arc, } @@ -816,7 +820,7 @@ impl std::fmt::Debug for AuditWriter { impl AuditWriter { /// Open the destination. The file destination takes a process-lifetime /// single-writer lock beside the active file and applies retention. - pub async fn open(destination: AuditDestination) -> Result { + pub async fn open(destination: AuditDestination, posture: Posture) -> Result { let inner = match destination { AuditDestination::File(file) => { let opened = tokio::task::spawn_blocking(move || SegmentedFile::open(file)) @@ -828,11 +832,17 @@ impl AuditWriter { AuditDestination::Stderr => WriterInner::stream(Box::new(io::stderr())), }; Ok(Self { + posture, inner: Arc::new(inner), open: Arc::default(), }) } + /// Open a destination that records the production posture. + pub async fn open_without_posture(destination: AuditDestination) -> Result { + Self::open(destination, Posture::Production).await + } + /// A writer over an arbitrary line sink, with `stdout` semantics. For /// tests that need to observe emitted lines without a file. /// @@ -840,13 +850,20 @@ impl AuditWriter { /// append waits for it on the Tokio timer: the runtime that appends needs /// its time driver. #[must_use] - pub fn from_line_sink(sink: Box) -> Self { + pub fn from_line_sink(sink: Box, posture: Posture) -> Self { Self { + posture, inner: Arc::new(WriterInner::stream(sink)), open: Arc::default(), } } + /// Create a line-sink writer that records the production posture. + #[must_use] + pub fn from_line_sink_without_posture(sink: Box) -> Self { + Self::from_line_sink(sink, Posture::Production) + } + /// Append one entry. For the file destination this returns only after the /// entry's bytes are durable. Canceling the caller does not cancel an /// enqueued file write or the other entries in its group commit. @@ -891,7 +908,7 @@ impl AuditWriter { } async fn write(&self, entry: &AuditEntry) -> Result<(), AuditUnavailable> { - let line = entry.to_line()?; + let line = entry.to_line(self.posture)?; match self.inner.as_ref() { WriterInner::File(file) => { let file = Arc::clone(file); @@ -934,7 +951,8 @@ impl AuditWriter { // The unfinished response must be writable before the request is: // a request accepted with a response it could never write would stay // unpaired. - AuditEntry::response(schema.clone(), correlation.clone(), unfinished.clone()).to_line()?; + AuditEntry::response(schema.clone(), correlation.clone(), unfinished.clone()) + .to_line(self.posture)?; // The request is written and its handle registered in one task that // outlives a canceled caller. A caller that stops waiting drops the // finished handle with the task's output, which writes the @@ -989,7 +1007,7 @@ impl AuditWriter { /// Write `entry` without waiting for the destination to accept it. fn append_detached(&self, entry: &AuditEntry) { - let line = match entry.to_line() { + let line = match entry.to_line(self.posture) { Ok(line) => line, Err(_) => { tracing::error!("an unfinished response entry is malformed and was not written"); @@ -2260,7 +2278,48 @@ pub struct SealedSegment { pub path: PathBuf, } +/// A decoded journal line. Historical lines can omit posture. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StoredAuditEntry { + /// The product's audit record schema. + pub schema: String, + /// The writer-generated identifier for this entry. + pub event_id: String, + /// The writer-generated timestamp. + pub time: String, + /// Whether the entry records a request or response. + pub phase: AuditPhase, + /// The writer's declared posture, if the line records it. + #[serde(default, deserialize_with = "deserialize_posture")] + pub posture: Option, + /// The product's request and response correlation. + pub correlation: String, + /// The product-owned record. + pub record: Value, +} + +fn deserialize_posture<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + let value = String::deserialize(deserializer)?; + Posture::parse(&value) + .map(Some) + .ok_or_else(|| serde::de::Error::custom("invalid audit posture")) +} + impl AuditSegments { + /// Decode a journal line from the active file or a sealed segment. + /// A present posture must be a recognized declaration. + pub fn parse_line(line: &[u8]) -> Result { + serde_json::from_slice(line).map_err(|_| { + AuditError::Io(io::Error::new( + ErrorKind::InvalidData, + "audit record is invalid", + )) + }) + } + /// The namespace of the active file at `path`. pub fn new(path: impl Into) -> Self { Self { path: path.into() } @@ -2634,10 +2693,9 @@ static TORN_RECOVERIES: StdMutex> = StdMutex::new(V /// Refuse an active file whose first entry was not produced by this writer, /// such as a leftover journal from the pre-simplification hash-chained /// writer. Every entry this writer appends carries `eventId`, `schema`, -/// `time`, `phase`, and `correlation`; an old-format entry carries none of -/// them. Only the first line is read, bounded to the largest entry this -/// writer accepts, since a file this writer manages never mixes formats. A -/// torn final line is not part of the first entry the check reads. +/// `time`, `phase`, and `correlation`. Historical entries can omit posture. +/// Only the first line is read, bounded to the largest entry this writer +/// accepts. A torn final line is outside the check. fn require_current_entry_format(active: &File, torn: Option<&TornTail>) -> Result<(), AuditError> { let length = match torn { Some(torn) => torn.complete, @@ -2653,20 +2711,25 @@ fn require_current_entry_format(active: &File, torn: Option<&TornTail>) -> Resul .read_exact_at(&mut buffer, 0) .map_err(AuditError::Io)?; let first_line = buffer.split(|&byte| byte == b'\n').next().unwrap_or(&[]); - let is_current_format = serde_json::from_slice::(first_line) - .ok() - .and_then(|value| value.as_object().cloned()) - .is_some_and(|entry| { - entry.get("eventId").is_some_and(Value::is_string) - && entry.get("schema").is_some_and(Value::is_string) - && entry.get("time").is_some_and(Value::is_string) - && entry.get("correlation").is_some_and(Value::is_string) - && matches!( - entry.get("phase").and_then(Value::as_str), - Some("request" | "response") - ) - }); - if !is_current_format { + #[derive(Deserialize)] + struct CurrentEntryFormat { + #[serde(rename = "schema")] + _schema: String, + #[serde(rename = "eventId")] + _event_id: String, + #[serde(rename = "time")] + _time: String, + #[serde(rename = "phase")] + _phase: AuditPhase, + #[serde(rename = "correlation")] + _correlation: String, + #[serde(rename = "posture", default, deserialize_with = "deserialize_posture")] + _posture: Option, + } + + if !first_line.trim_ascii_start().starts_with(b"{") + || serde_json::from_slice::(first_line).is_err() + { return Err(AuditError::Io(io::Error::new( ErrorKind::InvalidData, "audit file's first entry is not in the format this writer produces; archive it and restart with a fresh path", @@ -2971,6 +3034,7 @@ mod tests { .expect("open"); file.sync_hook = Some(hook); AuditWriter { + posture: Posture::Production, inner: Arc::new(WriterInner::File(Arc::new(GroupCommitFile::new(file)))), open: Arc::default(), } @@ -2985,7 +3049,9 @@ mod tests { } fn current_format_line(correlation: &str) -> String { - request(correlation).to_line().expect("line") + request(correlation) + .to_line(Posture::Production) + .expect("line") } /// Every name shaped like a sealed segment of `path`, oldest first. @@ -3037,12 +3103,116 @@ mod tests { } } + #[tokio::test] + async fn explicit_writers_record_their_posture() { + let directory = directory(); + let destination = file_destination(&directory); + let path = destination.path().to_owned(); + let writer = AuditWriter::open(AuditDestination::File(destination), Posture::Development) + .await + .expect("open"); + writer.append(request("explicit")).await.expect("write"); + assert_eq!(lines(&path)[0]["posture"], "development"); + + let buffer = SharedBuffer::default(); + let writer = AuditWriter::from_line_sink(Box::new(buffer.clone()), Posture::Production); + writer.append(request("explicit")).await.expect("write"); + let bytes = buffer.0.lock().expect("buffer"); + let entry: Value = serde_json::from_slice(&bytes).expect("json line"); + assert_eq!(entry["posture"], "production"); + } + + #[test] + fn startup_refuses_a_malformed_posture_in_the_first_line() { + let directory = directory(); + let destination = file_destination(&directory); + let path = destination.path(); + fs::DirBuilder::new() + .mode(0o700) + .create(path.parent().expect("parent")) + .expect("audit directory"); + let line = current_format_line("request"); + let duplicate = line.replace( + r#""posture":"production""#, + r#""posture":"staging","posture":"production""#, + ); + let invalid = line.replace(r#""posture":"production""#, r#""posture":"staging""#); + fs::write(path, &invalid).expect("write malformed line"); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("mode"); + for content in [invalid, duplicate] { + fs::write(path, content).expect("write malformed line"); + let error = destination.check_writable().expect_err("malformed posture"); + assert!( + matches!(error, AuditError::Io(error) if error.kind() == ErrorKind::InvalidData) + ); + } + + let legacy = line.replace(r#""posture":"production","#, ""); + fs::write(path, legacy).expect("write historical line"); + destination + .check_writable() + .expect("historical line accepted"); + } + + #[test] + fn segment_lines_accept_declared_and_missing_posture() { + let directory = directory(); + let active = directory.path().join("audit.jsonl"); + let segments = AuditSegments::new(&active); + let mut entry = json!({ + "schema": "registry.test.audit/v2", + "eventId": "event", + "time": "2024-01-01T00:00:00Z", + "phase": "request", + "correlation": "request", + "record": {} + }); + let legacy = entry.to_string(); + entry["posture"] = json!("development"); + fs::write( + active.with_extension("jsonl.00000001"), + format!("{entry}\n{legacy}\n"), + ) + .expect("write segment"); + + let sealed = segments.sealed(1).expect("list segment"); + let contents = fs::read_to_string(&sealed[0].path).expect("read segment"); + let postures: Vec<_> = contents + .lines() + .map(|line| { + AuditSegments::parse_line(line.as_bytes()) + .expect("parse line") + .posture + }) + .collect(); + assert_eq!(postures, [Some(Posture::Development), None]); + + for invalid in [json!("staging"), Value::Null, json!(1)] { + entry["posture"] = invalid; + let error = + AuditSegments::parse_line(entry.to_string().as_bytes()).expect_err("malformed"); + assert!( + matches!(error, AuditError::Io(error) if error.kind() == ErrorKind::InvalidData) + ); + } + } + + #[tokio::test] + async fn transitional_sink_writes_production_posture() { + let buffer = SharedBuffer::default(); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())); + writer.append(request("transitional")).await.expect("write"); + let bytes = buffer.0.lock().expect("buffer"); + let entry: Value = serde_json::from_slice(&bytes).expect("json line"); + assert_eq!(entry["posture"], "production"); + } + #[tokio::test] async fn file_entries_carry_only_the_envelope_fields() { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("request"); @@ -3067,6 +3237,7 @@ mod tests { "correlation", "eventId", "phase", + "posture", "record", "schema", "time" @@ -3100,7 +3271,7 @@ mod tests { /// later entry an interrupted write left, and return the accepted bytes. async fn seed_torn_tail(destination: &FileDestination, torn: &[u8]) -> Vec { let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); writer.append(request("accepted")).await.expect("append"); @@ -3124,7 +3295,7 @@ mod tests { let torn = b"{\"schema\":\"registry.test.audit/v2\",\"corr"; let accepted = seed_torn_tail(&destination, torn).await; - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("a torn final line is recovered at open"); let side = AuditSegments::new(&path).torn_line(); @@ -3161,7 +3332,7 @@ mod tests { fs::write(&path, torn).expect("torn file"); fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("mode"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("a torn first line is recovered at open"); assert_eq!( @@ -3176,14 +3347,14 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); writer.append(request("before")).await.expect("append"); drop(writer); let before = fs::read(&path).expect("read before restart"); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen complete stream"); assert_eq!(fs::read(&path).expect("read after restart"), before); @@ -3205,7 +3376,7 @@ mod tests { destination .check_writable() .expect_err("check refuses a side file holding other bytes"); - let error = AuditWriter::open(AuditDestination::File(destination)) + let error = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("open refuses a side file holding other bytes"); assert!( @@ -3238,7 +3409,7 @@ mod tests { destination .check_writable() .expect("check accepts the copy"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open finishes the recovery"); assert_eq!(fs::read(&side).expect("side file"), torn); @@ -3256,7 +3427,7 @@ mod tests { destination .check_writable() .expect_err("check refuses a tail no write of this writer left"); - let error = AuditWriter::open(AuditDestination::File(destination)) + let error = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("open refuses a tail no write of this writer left"); assert_eq!( @@ -3273,13 +3444,13 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); writer.append(request("before")).await.expect("append"); drop(writer); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen complete stream"); writer @@ -3368,7 +3539,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let WriterInner::File(file) = writer.inner.as_ref() else { @@ -3502,7 +3673,7 @@ mod tests { .build() .expect("runtime") .block_on(async { - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -3594,7 +3765,7 @@ mod tests { let destination = FileDestination::new(unlistable.join("audit").join("audit.jsonl")).expect("absolute"); let refused = destination.check_writable(); - let opened = AuditWriter::open(AuditDestination::File(destination)).await; + let opened = AuditWriter::open_without_posture(AuditDestination::File(destination)).await; fs::set_permissions(&unlistable, fs::Permissions::from_mode(0o700)).expect("restore"); opened.expect_err("the writer cannot sync the ancestor"); refused.expect_err("ancestor cannot be listed"); @@ -3632,7 +3803,7 @@ mod tests { .build() .expect("runtime") .block_on(async { - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -3678,7 +3849,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -3699,10 +3870,10 @@ mod tests { async fn a_second_writer_on_the_same_path_is_refused() { let directory = directory(); let destination = file_destination(&directory); - let _first = AuditWriter::open(AuditDestination::File(destination.clone())) + let _first = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("first"); - let second = AuditWriter::open(AuditDestination::File(destination)) + let second = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("second writer"); // `role` is `None` for the service's own destination: whoever holds @@ -3719,10 +3890,10 @@ mod tests { let destination = AuditDestination::File(file_destination(&directory)) .for_process("caseworkctl") .expect("companion destination"); - let _first = AuditWriter::open(destination.clone()) + let _first = AuditWriter::open_without_posture(destination.clone()) .await .expect("first companion writer"); - let second = AuditWriter::open(destination) + let second = AuditWriter::open_without_posture(destination) .await .expect_err("second companion writer"); // The lock is on the companion sibling file, so only another @@ -3739,9 +3910,10 @@ mod tests { #[tokio::test] async fn invalid_entries_are_refused_without_stopping_the_writer() { let directory = directory(); - let writer = AuditWriter::open(AuditDestination::File(file_destination(&directory))) - .await - .expect("open"); + let writer = + AuditWriter::open_without_posture(AuditDestination::File(file_destination(&directory))) + .await + .expect("open"); for entry in [ AuditEntry::request("", "req", json!({})), AuditEntry::request("schema/v2", "", json!({})), @@ -3769,7 +3941,7 @@ mod tests { .with_rotate_bytes(MIN_AUDIT_ROTATE_BYTES) .expect("rotation"); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let padding = "x".repeat(4096); @@ -3861,7 +4033,7 @@ mod tests { .expect("age file"); } - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); assert!(!expired.exists(), "expired sealed segment kept"); @@ -3909,7 +4081,7 @@ mod tests { }) .expect("age active file"); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer @@ -3945,7 +4117,7 @@ mod tests { fs::write(&existing, "{}\n").expect("seed"); fs::set_permissions(&existing, fs::Permissions::from_mode(0o600)).expect("mode"); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let padding = "x".repeat(4096); @@ -3970,7 +4142,7 @@ mod tests { #[tokio::test] async fn stream_destination_emits_one_json_line_per_entry() { let buffer = SharedBuffer::default(); - let writer = AuditWriter::from_line_sink(Box::new(buffer.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())); assert_eq!(writer.kind(), AuditDestinationKind::Stdout); writer.append(request("req-1")).await.expect("request"); writer @@ -3996,7 +4168,7 @@ mod tests { #[tokio::test] async fn a_failing_stream_refuses_the_append_and_every_later_one() { - let writer = AuditWriter::from_line_sink(Box::new(FailingSink)); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(FailingSink)); let first = writer.append(request("req-1")).await.expect_err("refused"); assert_eq!(first.reason(), AuditUnavailableReason::WriteFailed); let second = writer.append(request("req-2")).await.expect_err("refused"); @@ -4032,7 +4204,7 @@ mod tests { let (entered, first_write) = std::sync::mpsc::channel(); let (release, failure_gate) = std::sync::mpsc::channel(); let writes = Arc::new(AtomicU64::new(0)); - let writer = AuditWriter::from_line_sink(Box::new(FailOnce { + let writer = AuditWriter::from_line_sink_without_posture(Box::new(FailOnce { entered, release: failure_gate, writes: writes.clone(), @@ -4115,7 +4287,7 @@ mod tests { .build() .expect("current-thread runtime"); runtime.block_on(async move { - let writer = AuditWriter::from_line_sink(Box::new(BlockingSink { + let writer = AuditWriter::from_line_sink_without_posture(Box::new(BlockingSink { entered, release: write_released, })); @@ -4190,7 +4362,7 @@ mod tests { unreachable!() }; let path = file.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File( + let writer = AuditWriter::open_without_posture(AuditDestination::File( file.with_rotate_bytes(MIN_AUDIT_ROTATE_BYTES) .expect("rotation"), )) @@ -4353,7 +4525,9 @@ mod tests { companion.for_process("schedulingctl"), Ok(AuditDestination::Stderr) ); - let companion_writer = AuditWriter::open(companion).await.expect("stderr"); + let companion_writer = AuditWriter::open_without_posture(companion) + .await + .expect("stderr"); assert_eq!(companion_writer.kind(), AuditDestinationKind::Stdout); for role in ["", "-x", "Bregctl", "a/b", "a.b", &"x".repeat(33)] { assert_eq!( @@ -4363,10 +4537,13 @@ mod tests { ); } - let _service_writer = AuditWriter::open(service.clone()).await.expect("service"); - let tool_writer = AuditWriter::open(service.for_process("bregctl").expect("role")) + let _service_writer = AuditWriter::open_without_posture(service.clone()) .await - .expect("a companion process opens its own file beside a running service"); + .expect("service"); + let tool_writer = + AuditWriter::open_without_posture(service.for_process("bregctl").expect("role")) + .await + .expect("a companion process opens its own file beside a running service"); tool_writer .append(AuditEntry::response( "test/v1", @@ -4459,7 +4636,7 @@ mod tests { // Opening applies retention, which lists the directory. fs::set_permissions(&parent, fs::Permissions::from_mode(0o300)).expect("mode"); let refused = destination.check_writable(); - let opened = AuditWriter::open(AuditDestination::File(destination)).await; + let opened = AuditWriter::open_without_posture(AuditDestination::File(destination)).await; fs::set_permissions(&parent, fs::Permissions::from_mode(0o700)).expect("restore"); opened.expect_err("the writer cannot list the directory"); refused.expect_err("unlistable audit directory"); @@ -4528,7 +4705,7 @@ mod tests { let content = "{\"envelope_id\":\"01J000000000000000000000\"}\n{\"envelope_id\""; fs::write(&path, content).expect("old-format file"); fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("mode"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("leftover journal with a torn tail"); assert_eq!(fs::read_to_string(&path).expect("active file"), content); @@ -4644,7 +4821,8 @@ mod tests { let destination = FileDestination::new(shared.join("audit").join("audit.jsonl")).expect("absolute"); let checked = destination.check_writable(); - let opened = AuditWriter::open(AuditDestination::File(destination)).await; + let opened = + AuditWriter::open_without_posture(AuditDestination::File(destination)).await; if accepted { checked.expect("sticky or group-writable ancestor"); opened.expect("sticky or group-writable ancestor"); @@ -4696,14 +4874,14 @@ mod tests { .and_then(|handle| handle.set_modified(old)) .expect("age file"); } - let first = AuditWriter::open(AuditDestination::File(destination.clone())) + let first = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); assert!(sealed_segments(&path).expect("sealed").is_empty()); drop(first); // A second restart finds no sealed segment at all. - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen"); let padding = "x".repeat(4096); @@ -4741,7 +4919,7 @@ mod tests { destination .check_writable() .expect_err("check refuses the sequence file"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("open refuses the sequence file"); } @@ -4782,7 +4960,7 @@ mod tests { let third = seed_segment(&path, 3, 3); let fourth = seed_segment(&path, 4, 0); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); @@ -4814,7 +4992,7 @@ mod tests { fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("mode"); refuse_retention(&path); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("a retention failure does not refuse open"); assert!(expired.exists()); @@ -4835,7 +5013,7 @@ mod tests { drop(writer); allow_retention(&path); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen"); assert!( @@ -4877,7 +5055,7 @@ mod tests { .create(path.parent().expect("parent")) .expect("audit directory"); seed_nearly_full_active(&path); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); writer @@ -4889,7 +5067,7 @@ mod tests { fs::remove_file(segment_path(&path, 1)).expect("ship the sealed segment"); seed_nearly_full_active(&path); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen"); writer @@ -4920,7 +5098,7 @@ mod tests { .expect("audit directory"); seed_nearly_full_active(&path); ship_on_seal(&path); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); @@ -4943,13 +5121,13 @@ mod tests { let path = destination.path().to_path_buf(); let parent = path.parent().expect("parent").to_path_buf(); drop( - AuditWriter::open(AuditDestination::File(destination.clone())) + AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("first open creates the lock and active file"), ); forget_directory_syncs(&parent); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen"); // A crash after creating the names but before the directory sync @@ -4962,7 +5140,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -4982,7 +5160,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -5004,7 +5182,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -5051,7 +5229,7 @@ mod tests { }) .expect("age other stream"); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); assert!(other.exists(), "another stream's active file deleted"); @@ -5277,7 +5455,7 @@ mod tests { let target = directory.path().join("elsewhere.jsonl"); fs::write(&target, "").expect("target"); std::os::unix::fs::symlink(&target, &path).expect("symlink"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("symlinked active file"); } @@ -5296,7 +5474,7 @@ mod tests { // Every append reopens the lock for read to check it is still pinned, // so a write-only lock would stop the writer on its first entry. fs::set_permissions(&lock, fs::Permissions::from_mode(0o200)).expect("mode"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("write-only lock"); } @@ -5320,7 +5498,7 @@ mod tests { ) .expect("old-format file"); fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("mode"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("leftover hash-chained journal"); } @@ -5334,7 +5512,7 @@ mod tests { fn buffered() -> (AuditWriter, SharedBuffer) { let buffer = SharedBuffer::default(); ( - AuditWriter::from_line_sink(Box::new(buffer.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())), buffer, ) } @@ -5549,7 +5727,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let (started, begun) = tokio::sync::oneshot::channel(); @@ -5616,7 +5794,7 @@ mod tests { .build() .expect("runtime"); let result: Result<(), &str> = runtime.block_on(async move { - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let _request = writer @@ -5645,7 +5823,7 @@ mod tests { .build() .expect("runtime"); let (writer, request) = runtime.block_on(async move { - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let request = writer @@ -5681,7 +5859,7 @@ mod tests { #[tokio::test] async fn a_stopped_writer_refuses_the_request_and_writes_nothing() { - let writer = AuditWriter::from_line_sink(Box::new(FailingSink)); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(FailingSink)); assert!(writer .begin( SCHEMA, @@ -5762,7 +5940,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_request_canceled_while_its_entry_is_written_is_still_paired() { let sink = GatedSink::new(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let begun = tokio::spawn({ let writer = writer.clone(); async move { @@ -5787,7 +5965,7 @@ mod tests { async fn a_response_accepted_after_its_caller_left_is_the_only_answer() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let request = writer .begin( SCHEMA, @@ -5817,7 +5995,7 @@ mod tests { async fn a_response_appended_after_its_caller_left_still_answers_the_request() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let request = writer .begin( SCHEMA, @@ -5860,7 +6038,7 @@ mod tests { async fn a_request_dropped_while_an_appended_response_is_written_is_answered_once() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let request = writer .begin( SCHEMA, @@ -5902,7 +6080,7 @@ mod tests { async fn an_appended_response_skips_a_request_whose_own_response_is_in_flight() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let first = writer .begin(SCHEMA, "shared", json!({"n": 1}), unfinished()) .await @@ -5982,7 +6160,7 @@ mod tests { fn dropping_a_request_never_waits_on_a_stalled_stream() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -6008,7 +6186,7 @@ mod tests { async fn a_response_claimed_while_its_request_is_dropped_is_the_only_answer() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let request = writer .begin( SCHEMA, @@ -6135,6 +6313,7 @@ mod tests { queue_lines: usize, ) -> AuditWriter { AuditWriter { + posture: Posture::Production, inner: Arc::new(WriterInner::Stream(LineStream::with_limits( Box::new(sink), deadline, diff --git a/crates/registry-platform-testing/tests/cross_crate_integration.rs b/crates/registry-platform-testing/tests/cross_crate_integration.rs index f76790b2b0..d6f7bf8415 100644 --- a/crates/registry-platform-testing/tests/cross_crate_integration.rs +++ b/crates/registry-platform-testing/tests/cross_crate_integration.rs @@ -162,7 +162,7 @@ async fn sample_axum_app_wires_middleware_oidc_and_audit_writer() { let destination = FileDestination::new(dir.path().join("audit").join("audit.jsonl")).expect("absolute path"); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("file destination opens"); let correlation = "request-1"; diff --git a/crates/registry-render/src/audit.rs b/crates/registry-render/src/audit.rs index c43f2c61e0..e32f93f0cc 100644 --- a/crates/registry-render/src/audit.rs +++ b/crates/registry-render/src/audit.rs @@ -192,12 +192,14 @@ impl RenderAudit { /// Open the configured destination. A file destination takes the /// single-writer lock and creates an owner-only parent directory. pub async fn open(destination: AuditDestination) -> Result { - let writer = AuditWriter::open(destination).await.map_err(|err| { - RenderProblem::new( - ProblemKind::AuditFailed, - format!("cannot open audit destination: {err}"), - ) - })?; + let writer = AuditWriter::open_without_posture(destination) + .await + .map_err(|err| { + RenderProblem::new( + ProblemKind::AuditFailed, + format!("cannot open audit destination: {err}"), + ) + })?; Ok(Self::new(writer)) } diff --git a/crates/registry-render/src/server.rs b/crates/registry-render/src/server.rs index a6acfe26e2..61972790e6 100644 --- a/crates/registry-render/src/server.rs +++ b/crates/registry-render/src/server.rs @@ -2024,7 +2024,9 @@ mod tests { Bundle::load_package(&bundle_path, &verified).expect("packaged receipt bundle"); Arc::new(Service { bundle, - audit: RenderAudit::new(AuditWriter::from_line_sink(Box::new(lines.clone()))), + audit: RenderAudit::new(AuditWriter::from_line_sink_without_posture(Box::new( + lines.clone(), + ))), api_key: TEST_API_KEY.as_bytes().to_vec(), oidc: None, caller_fingerprint: "caller-fingerprint".to_owned(), diff --git a/crates/registry-render/tests/serve.rs b/crates/registry-render/tests/serve.rs index be455ae0a2..2450eeee61 100644 --- a/crates/registry-render/tests/serve.rs +++ b/crates/registry-render/tests/serve.rs @@ -1107,6 +1107,7 @@ fn a_render_writes_a_request_entry_then_a_response_entry_sharing_correlation() { "correlation", "eventId", "phase", + "posture", "record", "schema", "time" diff --git a/crates/registry-scheduling/src/audit.rs b/crates/registry-scheduling/src/audit.rs index 3553ebaf26..c0b64f8a4e 100644 --- a/crates/registry-scheduling/src/audit.rs +++ b/crates/registry-scheduling/src/audit.rs @@ -244,7 +244,7 @@ mod capture { #[must_use] pub fn capture() -> (Self, AuditCapture) { let capture = AuditCapture::default(); - let writer = AuditWriter::from_line_sink(Box::new(capture.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(capture.clone())); capture.0.lock().expect("audit capture").writer = Some(writer.clone()); (Self::new(writer), capture) } @@ -369,7 +369,9 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_stalled_destination_is_not_ready_until_it_drains() { let sink = HeldSink::default(); - let audit = SchedulingAudit::new(AuditWriter::from_line_sink(Box::new(sink.clone()))); + let audit = SchedulingAudit::new(AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + ))); assert!(audit.ready().await); // The destination stops taking lines. The request waiting on it is diff --git a/crates/registry-scheduling/src/runtime.rs b/crates/registry-scheduling/src/runtime.rs index 2429eac657..bd76b6f12d 100644 --- a/crates/registry-scheduling/src/runtime.rs +++ b/crates/registry-scheduling/src/runtime.rs @@ -614,7 +614,7 @@ pub async fn open_audit( .for_process(process) .map_err(|error| RuntimeError::AuditDestination(error.to_string()))?; } - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|error| RuntimeError::AuditDestination(error.operator_description()))?; Ok((audit_profile.key_hasher(), SchedulingAudit::new(writer))) diff --git a/crates/registry-schedulingctl/src/activation.rs b/crates/registry-schedulingctl/src/activation.rs index 5e0c1bf510..c803f00f5f 100644 --- a/crates/registry-schedulingctl/src/activation.rs +++ b/crates/registry-schedulingctl/src/activation.rs @@ -254,7 +254,9 @@ fn refusing_audit() -> SchedulingAudit { Ok(()) } } - SchedulingAudit::new(AuditWriter::from_line_sink(Box::new(RefusingSink))) + SchedulingAudit::new(AuditWriter::from_line_sink_without_posture(Box::new( + RefusingSink, + ))) } pub fn plan(config_path: &Path) -> Result { @@ -429,7 +431,7 @@ fn apply_audited( )) .context("opening the schedulingctl audit destination")?; let audit = match sink { - Some(sink) => SchedulingAudit::new(AuditWriter::from_line_sink(sink)), + Some(sink) => SchedulingAudit::new(AuditWriter::from_line_sink_without_posture(sink)), None => audit, }; let activation_id = Uuid::new_v4(); diff --git a/crates/registry-schedulingctl/src/lib.rs b/crates/registry-schedulingctl/src/lib.rs index a668e0c9f4..76400c81e4 100644 --- a/crates/registry-schedulingctl/src/lib.rs +++ b/crates/registry-schedulingctl/src/lib.rs @@ -1400,7 +1400,9 @@ mod tests { } } let audit = registry_scheduling::audit::SchedulingAudit::new( - registry_platform_audit::AuditWriter::from_line_sink(Box::new(Refusing)), + registry_platform_audit::AuditWriter::from_line_sink_without_posture(Box::new( + Refusing, + )), ); // A stream append waits on the Tokio timer. let unavailable = tokio::runtime::Builder::new_current_thread() diff --git a/docs/site/src/content/docs/operate/casework-retention.mdx b/docs/site/src/content/docs/operate/casework-retention.mdx index 8d933b9482..4dc7d0baa5 100644 --- a/docs/site/src/content/docs/operate/casework-retention.mdx +++ b/docs/site/src/content/docs/operate/casework-retention.mdx @@ -144,7 +144,7 @@ reason was given. This is the request entry of the decision in [Decide your first ReviewRequest](../../tutorials/first-casework/): ```text -{"schema":"registry-casework-audit/v1","eventId":"","time":"