From 73ed7d645bb4d513fef12604e2cb7359e380b198 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 14:18:40 +0000 Subject: [PATCH 01/26] test(casework): bound PostgreSQL lease observation Signed-off-by: Jeremi Joslin --- .../tests/review_postgres.rs | 203 +++++++++++++----- 1 file changed, 148 insertions(+), 55 deletions(-) diff --git a/crates/registry-casework/tests/review_postgres.rs b/crates/registry-casework/tests/review_postgres.rs index 18fdd1f3f0..898f72a1ff 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -514,19 +514,20 @@ fn bind_request( request } +fn review_test_database_url() -> String { + env::var("CASEWORK_REVIEW_TEST_DATABASE_URL") + .expect("CASEWORK_REVIEW_TEST_DATABASE_URL is required for review PostgreSQL tests") +} + async fn fixture() -> Fixture { - let base = env::var("CASEWORK_REVIEW_TEST_DATABASE_URL") - .expect("CASEWORK_REVIEW_TEST_DATABASE_URL is required for review PostgreSQL tests"); + let base = review_test_database_url(); let schema = format!("review_{}", Uuid::new_v4().simple()); let application_name = format!("casework-review-{}", Uuid::new_v4().simple()); let separator = if base.contains('?') { '&' } else { '?' }; let scoped_url = format!( "{base}{separator}options=-csearch_path%3D{schema}&application_name={application_name}" ); - let (admin, admin_connection) = tokio_postgres::connect(&base, NoTls) - .await - .expect("connect dedicated review test database"); - tokio::spawn(async move { admin_connection.await.expect("admin connection") }); + let admin = connect_review_test_database(&base).await; admin .batch_execute(&format!("CREATE SCHEMA {schema}")) .await @@ -551,7 +552,7 @@ async fn fixture() -> Fixture { let store = PostgresStore::connect_runtime(&database_config, &secrets, None) .expect("runtime store") .with_audit(registry_casework::CaseworkAudit::capture().0); - let database = connect_scoped(&scoped_url).await; + let database = connect_review_test_database(&scoped_url).await; database .batch_execute( "INSERT INTO casework_teams(team_id,revision) VALUES('review-team',1); @@ -612,11 +613,11 @@ async fn fixture() -> Fixture { } } -async fn connect_scoped(url: &str) -> tokio_postgres::Client { +async fn connect_review_test_database(url: &str) -> tokio_postgres::Client { let (client, connection) = tokio_postgres::connect(url, NoTls) .await - .expect("schema connection"); - tokio::spawn(async move { connection.await.expect("schema connection task") }); + .expect("connect review test database"); + tokio::spawn(async move { connection.await.expect("review test database connection") }); client } @@ -696,50 +697,57 @@ async fn assert_terminal_atomic(fixture: &Fixture, request_id: Uuid, completion_ ); } -async fn assert_store_sessions_hold_no_transaction_or_row_lock(fixture: &Fixture) { - let sessions = fixture - .database - .query_one( - "SELECT count(*), - count(*) FILTER (WHERE xact_start IS NOT NULL), - count(*) FILTER (WHERE state <> 'idle') - FROM pg_stat_activity - WHERE datname=current_database() AND application_name=$1 - AND pid<>pg_backend_pid()", - &[&fixture.application_name], - ) - .await - .expect("inspect completion dispatcher database sessions"); - assert!(sessions.get::<_, i64>(0) > 0, "observe the dispatcher pool"); - assert_eq!( - sessions.get::<_, i64>(1), - 0, - "completion delivery must not retain an open database transaction" - ); - assert_eq!( - sessions.get::<_, i64>(2), - 0, - "completion delivery must leave its database sessions idle" - ); - - let row_locks: i64 = fixture - .database - .query_one( - "SELECT count(*) - FROM pg_locks l - JOIN pg_stat_activity a ON a.pid=l.pid - WHERE a.datname=current_database() AND a.application_name=$1 - AND a.pid<>pg_backend_pid() AND l.granted - AND l.locktype IN ('tuple','transactionid')", - &[&fixture.application_name], - ) - .await - .expect("inspect completion dispatcher row locks") - .get(0); - assert_eq!( - row_locks, 0, - "completion delivery must not retain a row or transaction-id lock" - ); +async fn wait_for_idle_store_sessions( + observer: &tokio_postgres::Client, + application_name: &str, + budget: std::time::Duration, +) -> Result<(), String> { + let mut last_observation = None; + tokio::time::timeout(budget, async { + loop { + // Each autocommit query takes a fresh activity snapshot. The backend + // can still report an active transaction briefly after commit returns. + let observation = observer + .query_one( + "WITH sessions AS MATERIALIZED ( + SELECT pid, xact_start, state + FROM pg_stat_activity + WHERE datname=current_database() AND application_name=$1 + AND pid<>pg_backend_pid() + ) + SELECT count(*), + count(*) FILTER (WHERE xact_start IS NOT NULL), + count(*) FILTER (WHERE state IS DISTINCT FROM 'idle'), + (SELECT count(*) FROM pg_locks l + JOIN sessions s ON s.pid=l.pid + WHERE l.granted AND l.locktype IN ('tuple','transactionid')) + FROM sessions", + &[&application_name], + ) + .await + .expect("inspect completion dispatcher database sessions and locks"); + let sessions: i64 = observation.get(0); + let transactions: i64 = observation.get(1); + let busy_sessions: i64 = observation.get(2); + let locks: i64 = observation.get(3); + if sessions > 0 && transactions == 0 && busy_sessions == 0 && locks == 0 { + return; + } + last_observation = Some((sessions, transactions, busy_sessions, locks)); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + }) + .await + .map_err(|_| { + let details = match last_observation { + Some((sessions, transactions, busy_sessions, locks)) => format!( + "sessions={sessions}, transactions={transactions}, busy_sessions={busy_sessions}, \ + tuple_or_transaction_id_locks={locks}" + ), + None => "no PostgreSQL activity observation completed".to_owned(), + }; + format!("timed out waiting for the dispatcher pool to be idle without transactions or locks ({details})") + }) } #[derive(Default)] @@ -1270,6 +1278,85 @@ async fn at_least_once_completion_durably_deduplicates_after_lost_ack_and_exhaus } } +#[tokio::test] +async fn completion_lease_observer_bounds_a_stalled_database_query() { + let fixture = fixture().await; + let blocker = connect_review_test_database(&review_test_database_url()).await; + let pid: i32 = fixture + .database + .query_one("SELECT pg_backend_pid()", &[]) + .await + .expect("read the observer backend PID") + .get(0); + blocker + .query_one("SELECT pg_advisory_lock(2828, $1)", &[&pid]) + .await + .expect("hold the observer's advisory lock"); + + let bounded = tokio::time::timeout(std::time::Duration::from_secs(5), async { + tokio::select! { + biased; + // Queue a lock wait ahead of the observer query on the same connection. + result = async { + fixture.database.query_one("SELECT pg_advisory_xact_lock(2828, $1)", &[&pid]).await + } => { + panic!("the queued query must remain blocked: {result:?}"); + } + result = wait_for_idle_store_sessions( + &fixture.database, + &fixture.application_name, + std::time::Duration::from_millis(250), + ) => result, + } + }) + .await; + let unlocked: bool = blocker + .query_one("SELECT pg_advisory_unlock(2828, $1)", &[&pid]) + .await + .expect("release the observer's advisory lock") + .get(0); + assert!(unlocked); + let diagnostic = bounded + .expect("the observer must finish while its database query is stalled") + .expect_err("a stalled observer must time out"); + assert!( + diagnostic.contains("no PostgreSQL activity observation completed"), + "expected the stalled query in the diagnostic: {diagnostic}" + ); +} + +#[tokio::test] +async fn completion_lease_observer_refuses_a_held_row_lock_until_rollback() { + let mut fixture = fixture().await; + let request_id = settle_review_for_completion(&fixture, "held-completion-row").await; + let observer = connect_review_test_database(&review_test_database_url()).await; + let transaction = fixture + .database + .transaction() + .await + .expect("begin row locker"); + transaction + .query_one( + "SELECT request_id FROM casework_review_completion_outbox + WHERE request_id=$1 FOR UPDATE", + &[&request_id], + ) + .await + .expect("lock the completion row"); + + let budget = std::time::Duration::from_secs(2); + let observed = wait_for_idle_store_sessions(&observer, &fixture.application_name, budget).await; + transaction.rollback().await.expect("release the row lock"); + let diagnostic = observed.expect_err("a held transaction must exhaust the observer timeout"); + assert!( + diagnostic.contains("transactions=1, busy_sessions=1, tuple_or_transaction_id_locks=1"), + "expected the held transaction and lock in the diagnostic: {diagnostic}" + ); + wait_for_idle_store_sessions(&observer, &fixture.application_name, budget) + .await + .expect("observe fresh idle activity after rollback"); +} + #[tokio::test] async fn completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner() { let fixture = fixture().await; @@ -1329,7 +1416,13 @@ async fn completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner() { ) .await .expect("completion receiver observes the first leased delivery"); - assert_store_sessions_hold_no_transaction_or_row_lock(&fixture).await; + wait_for_idle_store_sessions( + &fixture.database, + &fixture.application_name, + std::time::Duration::from_secs(2), + ) + .await + .unwrap_or_else(|diagnostic| panic!("{diagnostic}")); let first_pass_states = fixture .database .query( From b64f936b13df0794cf96454990d509b25a956d4a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:02:00 +0000 Subject: [PATCH 02/26] test(breg): expect the missing array claim admission refusal Signed-off-by: Jeremi Joslin --- .../fixtures/multi-reference-array-claim/tests/journeys.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/breg/fixtures/multi-reference-array-claim/tests/journeys.yaml b/products/breg/fixtures/multi-reference-array-claim/tests/journeys.yaml index 622bdf5a95..e237d1a750 100644 --- a/products/breg/fixtures/multi-reference-array-claim/tests/journeys.yaml +++ b/products/breg/fixtures/multi-reference-array-claim/tests/journeys.yaml @@ -100,4 +100,4 @@ journeys: sourceAuthorityId: {recordCapture: north-authority} destinationAuthorityId: {recordCapture: south-authority} transferReference: TRANSFER-004 - expect: {outcome: refusal, status: 404, problemCode: resource.not-found} + expect: {outcome: refusal, status: 403, problemCode: profile.not-authorized} From b0c7fe09491124cefc57237fc3f2697a6152eb82 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:27:47 +0000 Subject: [PATCH 03/26] test(breg): qualify the released licence public check Signed-off-by: Jeremi Joslin --- products/breg/evidence/README.md | 8 + .../public-check/bregctl-v0.49.0.SHA256SUMS | 9 + .../breg/evidence/tests/verify-composition.py | 284 ++++++++++++++++-- 3 files changed, 268 insertions(+), 33 deletions(-) create mode 100644 products/breg/evidence/public-check/bregctl-v0.49.0.SHA256SUMS diff --git a/products/breg/evidence/README.md b/products/breg/evidence/README.md index 628ae53494..613d04fe98 100644 --- a/products/breg/evidence/README.md +++ b/products/breg/evidence/README.md @@ -95,6 +95,14 @@ outputs privately. The runner starts no services and proves: version, refused fact rules, its 10 fixtures, and Evidence's refusal of the same definition over the ordinary export. +For the served synthetic licence check, give the same runner matching released +v0.49.0 binaries for all five options, including `--breg` and `--rstack`. It +starts a disposable BReg and Evidence run with Docker, compares two native +exports to the pinned inventory in `public-check/bregctl-v0.49.0.SHA256SUMS`, +and calls the public route on loopback. The run exercises a valid licence, a +missing request member, a wrong code, a record issued without a code, and an +absent record. Use `--work-dir` to retain the generated authoring artifacts. + The offline runner does not establish successful retained-session attachment, HTTP authorization, live signing or service operation. Those need the separate native local lifecycle journey. Value changes need no new export; changes to a diff --git a/products/breg/evidence/public-check/bregctl-v0.49.0.SHA256SUMS b/products/breg/evidence/public-check/bregctl-v0.49.0.SHA256SUMS new file mode 100644 index 0000000000..ea25da318c --- /dev/null +++ b/products/breg/evidence/public-check/bregctl-v0.49.0.SHA256SUMS @@ -0,0 +1,9 @@ +ac5787573469a1d1afe5b1bcfb7c2f5c2e24c901b7efa17005c6f120f5439d94 adapter-packs/registry-check/pack.yaml +de5da14df16cbd9f8fc37a8580330242d50409aa15d28749904bc9c2823b41b2 adapter-packs/registry-check/protocols/registry-lookup.json +66e7e32afae2a7e10e61d1d2439c6d0af49f580411f25e08315bfbc01cf0e1a3 adapter-packs/registry-check/schemas/facts.json +64f09226eeb333e756f9da69b93179fe4afeecb76306d589b605eedf7d951e0f adapter-packs/registry-check/schemas/inputs.json +0ae29920c88d5bb7878c42b24ca4c1f417068ca5b81ee0ab1d5835a59622042d adapter-packs/registry-check/schemas/response.json +7b14e4c20acfeee66678ede2cfe34a03bd8c101e9cefce610cc6574c200125ce adapter-packs/registry-check/scripts/lookup.rhai +3912ec5c8bfeb077878266397a2c0f9f8cb991a200de92acba5bc31036c30300 selectors/breg-8-registry-6-record-7-by-code.yaml +f70ce6a8ce5660b940b1f98d0f50777984479303347fd4f110959129de439c8e source-export.json +bb03772f29474a51baf4d1b0637bcd0ab0af6b303e324f76b55e217d25ad8eb8 sources/registry-check.yaml diff --git a/products/breg/evidence/tests/verify-composition.py b/products/breg/evidence/tests/verify-composition.py index ec52eb961d..9011919dca 100644 --- a/products/breg/evidence/tests/verify-composition.py +++ b/products/breg/evidence/tests/verify-composition.py @@ -1,12 +1,13 @@ #!/usr/bin/env python3 -"""Offline native BReg-to-Evidence composition proof with matching binaries. +"""Native BReg-to-Evidence composition proof with matching binaries. -Requires bregctl, evidencectl, evidence and PyYAML. Starts no services. The -adopter flow uses ordinary authored files and public CLIs, not this harness. +Requires bregctl, evidencectl, evidence and PyYAML. With breg and rstack, also +serve a synthetic licence public check against a disposable PostgreSQL database. """ from __future__ import annotations import argparse +from contextlib import contextmanager import hashlib import json import os @@ -14,6 +15,8 @@ import shutil import subprocess import tempfile +from urllib.error import HTTPError +from urllib.request import build_opener, ProxyHandler, Request import yaml @@ -122,15 +125,7 @@ def facts_schema(pack_root: Path) -> dict: return read(pack_root / pack["sourceRoutes"][0]["evidence"]["factsSchema"]["path"]) -def verify_public_check(workspace: Path, binaries: dict[str, Path], - environment: dict[str, str], offline_cases: dict[str, int]) -> dict: - """A public check reads the registry through a `--public-check` export. - - Evidence compares the check code only after the Source lookup succeeds, so - this export states types only and the definition's derivation checks content. - """ - registry, project = workspace / "check-registry", workspace / "check-evidence" - target, candidate = workspace / "check-target", workspace / "check-candidate" +def public_check_registry(registry: Path) -> None: shutil.copytree(INPUTS / "registry", registry) model = read(registry / "registry.yaml") model["recordTypes"]["record"]["fields"].append({ @@ -140,14 +135,47 @@ def verify_public_check(workspace: Path, binaries: dict[str, Path], for profile in model["accessProfiles"].values(): for permission in profile["permissions"]["records"]: permission["readableFields"].append("check-code") + if "create" in permission["operations"]: + permission["writableFields"].append("check-code") write(registry / "registry.yaml", model) - arguments = ( + + +def public_check_arguments(registry: Path, authentication: str) -> tuple: + return ( "generate", "evidence-source", registry, "--access-profile", "evidence-source", "--record-type", "record", "--selector", "by-code", "--fields", "status,check-code", "--source-id", "registry-check", "--connection", "registry", - "--authentication", "oauth2-private-key-jwt", + "--authentication", authentication, ) + + +def author_public_check(project: Path, export: Path, binaries: dict[str, Path], + environment: dict[str, str]) -> None: + run(binaries["evidencectl"], "init", project, "--starter", + INPUTS / "offline-starter", "--profile", "local", environment=environment) + run(binaries["evidencectl"], "source", "import", export, "--project", project, + environment=environment) + authored = read(project / "evidence.yaml") + fragment = read(PUBLIC_CHECK / "definitions.yaml.fragment") + authored["functions"].update(fragment["functions"]) + authored["assertionDefinitions"].update(fragment["assertionDefinitions"]) + write(project / "evidence.yaml", authored) + for name in ["functions", "fixtures", "schemas"]: + shutil.copytree(PUBLIC_CHECK / name, project / name, dirs_exist_ok=True) + + +def verify_public_check(workspace: Path, binaries: dict[str, Path], + environment: dict[str, str], offline_cases: dict[str, int]) -> dict: + """A public check reads the registry through a `--public-check` export. + + Evidence compares the check code only after the Source lookup succeeds, so + this export states types only and the definition's derivation checks content. + """ + registry, project = workspace / "check-registry", workspace / "check-evidence" + target, candidate = workspace / "check-target", workspace / "check-candidate" + public_check_registry(registry) + arguments = public_check_arguments(registry, "oauth2-private-key-jwt") ordinary, exported = workspace / "check-ordinary-export", workspace / "check-export" run(binaries["bregctl"], *arguments, "--output", ordinary, environment=environment) run(binaries["bregctl"], *arguments, "--public-check", "--output", exported, @@ -174,28 +202,14 @@ def verify_public_check(workspace: Path, binaries: dict[str, Path], assert "breg.evidence-source.refused" in refused, refused assert not (workspace / "check-refused-export").exists() - fragment = read(PUBLIC_CHECK / "definitions.yaml.fragment") - - def author(directory: Path, export: Path) -> None: - run(binaries["evidencectl"], "init", directory, "--starter", - INPUTS / "offline-starter", "--profile", "local", environment=environment) - run(binaries["evidencectl"], "source", "import", export, "--project", directory, - environment=environment) - authored = read(directory / "evidence.yaml") - authored["functions"].update(fragment["functions"]) - authored["assertionDefinitions"].update(fragment["assertionDefinitions"]) - write(directory / "evidence.yaml", authored) - for name in ["functions", "fixtures", "schemas"]: - shutil.copytree(PUBLIC_CHECK / name, directory / name, dirs_exist_ok=True) - # Evidence refuses the same definition over the ordinary export. mistaken = workspace / "check-ordinary-evidence" - author(mistaken, ordinary) + author_public_check(mistaken, ordinary, binaries, environment) refused = run(binaries["evidencectl"], "check", mistaken, environment=environment, refused=True) assert "public-check-facts-content" in refused, refused - author(project, exported) + author_public_check(project, exported, binaries, environment) new_local_target(project, target, binaries, environment) # Declaring publicCheck opens nothing. The target authority activates it. settings = read(target / "target.yaml") @@ -231,6 +245,202 @@ def author(directory: Path, export: Path) -> None: } +@contextmanager +def managed_product(binaries: dict[str, Path], state: Path, project: Path, product: str): + env = dict(os.environ) + env.pop("RSTACK_DEV_DATABASE_URL", None) + env.pop("RSTACK_DEV_DATABASE_CA", None) + env["RSTACK_DEV_STATE_DIR"] = str(state) + env["EVIDENCE_BIN"] = str(binaries["evidence"]) + for name in ("breg", "bregctl", "evidence", "evidencectl"): + env[f"RSTACK_{name.upper()}_BIN"] = str(binaries[name]) + command = [str(binaries["rstack"]), "--install-root", str(state.parent / "install"), + "--format", "json", "dev"] + + def dev(*args: object) -> dict: + result = subprocess.run( + [*command, *map(str, args)], env=env, capture_output=True, timeout=180, check=False, + ) + report = json.loads(result.stdout) + if result.returncode: + detail = report.get("error", {}).get("message") if args[0] != "token" else None + raise RuntimeError(f"{product} dev {args[0]} exited {result.returncode}: {detail}") + return report + + started = dev("start", project, "--ttl", "5m") + run_id = started["run_id"] + try: + assert started["status"] == "ready" + origin = started["products"][product] + assert origin.startswith("http://127.0.0.1:") + yield origin, lambda alias: dev("token", run_id, "--as", alias) + finally: + clean = ["--clean"] if started["database"]["mode"] == "managed" else [] + stopped = dev("stop", run_id, *clean) + assert stopped["status"] == "stopped" + + +def verify_live_public_check(workspace: Path, binaries: dict[str, Path]) -> dict: + environment = dict(os.environ) + versions = { + name: run(path, "--version", environment=environment).strip().split()[-1] + for name, path in binaries.items() + } + assert len(set(versions.values())) == 1, versions + expected_file = PUBLIC_CHECK / f"bregctl-v{versions['bregctl']}.SHA256SUMS" + assert expected_file.is_file(), f"no reviewed export for bregctl {versions['bregctl']}" + expected = { + name: digest + for digest, name in (line.split(maxsplit=1) for line in expected_file.read_text().splitlines()) + } + registry = workspace / "licence-registry" + public_check_registry(registry) + journey_path = registry / "dev-journeys.yaml" + journey = read(journey_path) + active, no_code, _ = journey["journeys"][0]["steps"] + code = "K7QWM4XRT5PZ3NB6VHJYDC2A" + number, legacy_number = "SYNTHETIC-LICENCE-001", "SYNTHETIC-LICENCE-LEGACY" + active["body"]["data"].update(code=number, checkCode=code) + no_code["body"]["data"]["code"] = legacy_number + write(journey_path, journey) + + arguments = public_check_arguments(registry, "static-authorization") + exported = workspace / "licence-source" + repeated = workspace / "licence-source-repeat" + for output in (exported, repeated): + run(binaries["bregctl"], *arguments, "--public-check", "--output", output, + environment=environment) + export_bytes = authored_snapshot(exported) + snapshot = { + name: hashlib.sha256(content).hexdigest() + for name, content in sorted(export_bytes.items()) + } + assert export_bytes == authored_snapshot(repeated) + assert snapshot == expected, "the native export differs from the reviewed release inventory" + facts = facts_schema(exported / "adapter-packs/registry-check") + assert facts["properties"] == { + "check-code": {"type": "string"}, "status": {"type": "string"}, + } + assert not facts.get("required") + project = workspace / "licence-evidence" + author_public_check(project, exported, binaries, environment) + project_path = project / "evidence.yaml" + authored = read(project_path) + authored["assertionDefinitions"].pop("extract-record-active") + authored["functions"].pop("extract-record-active") + authored["lookups"].pop("record-by-code-v1") + authored["sources"].pop("record-status") + write(project_path, authored) + fixture_path = project / "fixtures/record-check.yaml" + fixture = read(fixture_path) + for case in fixture["cases"]: + acquisition = case.get("acquisition") + if acquisition is not None: + acquisition["intercepts"] = [ + entry for entry in acquisition["intercepts"] if entry["type"] != "token-endpoint" + ] + acquisition["exchanges"] = [ + exchange for exchange in acquisition["exchanges"] + if not exchange["request"].get("tokenRequest") + ] + write(fixture_path, fixture) + + with tempfile.TemporaryDirectory(prefix="licence-run-", dir=workspace) as work: + scratch = Path(work) + local = scratch / "evidence" + shutil.copytree(project, local) + with managed_product(binaries, scratch / "breg-state", registry, "breg") as (origin, token): + target_path = local / "local-target.yaml" + target = read(target_path) + authority_path = local / target["authority"] + authority = read(authority_path) + authority["publicCheck"] = {"definition": "record-check"} + # Packaging also exercises signed synthetic fixtures. They enter + # through the ordinary relying-service profile. + [grant] = authority["accessProfiles"]["local-service"]["grants"] + grant["definition"] = "record-check" + [subject] = grant["subjects"] + subject["lookup"] = "breg-8-registry-6-record-7-by-code" + write(authority_path, authority) + target.pop("extracts") + target["connections"].pop("record-status-extract") + target["connections"]["registry"] = {"endpoints": {"registry": { + "origin": origin, + "authentication": {"type": "static-authorization", + "tokenRef": "secret:file/licence-source-token"}, + }}} + write(target_path, target) + write(local / "dev.yaml", { + "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", + "kind": "RStackDev", "issuer": "run", + "products": [{"product": "evidence", "project": ".", + "audience": "urn:example:licence-public-check"}], + "journeyFile": "dev-journeys.yaml", + "people": {"caller": { + "subject": "urn:example:caller:public-check-fixture", + "client": "caller", + "grants": {"evidence": { + "profile": "local-service", + "scopes": ["evidence:request"], + "claims": {"evidence_audience": "urn:example:audience:local-evidence"}, + }}, + }}, + }) + write(local / "dev-journeys.yaml", { + "apiVersion": "id.registrystack.org/formats/rstack/journeys/v1alpha1", + "kind": "RStackJourneys", + "journeys": [{"id": "public-check-ready", "steps": [{ + "id": "definitions", "product": "evidence", "as": "caller", + "method": "GET", "path": "/v1/evidence-definitions", + "expect": {"status": 200}, + }]}], + }) + # rstack creates this short-lived fixture credential. Keep it + # out of retained authoring artifacts and diagnostic output. + [credential] = token("source")["credentials"] + header = Path(credential["header_file"]).read_text().strip() + name, scheme, value = header.split(maxsplit=2) + assert name.lower() == "authorization:" and scheme == "Bearer" + secret_path = local / ".generated/secrets/licence-source-token" + secret_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(secret_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fd, "w") as secret: + secret.write(value) + + with managed_product(binaries, scratch / "evidence-state", local, "evidence") as (evidence, _): + client = build_opener(ProxyHandler({})) + + def check(document_number: str, **fields: str) -> tuple[int, dict]: + request = Request( + evidence + "/v1/public-check", + data=json.dumps({"documentNumber": document_number, **fields}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with client.open(request, timeout=15) as result: + return result.status, json.load(result) + except HTTPError as error: + with error: + return error.code, json.load(error) + + status, result = check(number, checkCode=code) + assert status == 200 and result.pop("observedAt"), (status, result) + assert result == {"schema": "registry.evidence.public-check/v1alpha1", + "status": "valid", "fields": {"recordStatus": "active"}} + missing_status, missing = check(number) + assert (missing_status, missing["code"]) == (400, "evidence.invalid-request") + unresolved = [] + for document_number, check_code in [ + (number, "A" * 24), (legacy_number, code), ("SYNTHETIC-LICENCE-ABSENT", code), + ]: + status, problem = check(document_number, checkCode=check_code) + assert (status, problem["code"]) == (404, "resource.not-found") + problem.pop("traceId", None) + unresolved.append(problem) + assert unresolved[0] == unresolved[1] == unresolved[2] + return {"versions": versions, "publicCheckExportSha256": snapshot, "servedCases": 5} + + def verify(workspace: Path, binaries: dict[str, Path]) -> dict: environment = dict(os.environ) environment.pop("REGISTRY_EVIDENCE_RUNTIME", None) @@ -481,10 +691,17 @@ def main() -> None: parser = argparse.ArgumentParser(description=__doc__) for name in ["bregctl", "evidencectl", "evidence"]: parser.add_argument(f"--{name}", type=Path, default=shutil.which(name)) + parser.add_argument("--breg", type=Path, help="native BReg runtime for the served licence check") + parser.add_argument("--rstack", type=Path, help="native launcher for the served licence check") parser.add_argument("--work-dir", type=Path, help="new private directory retaining synthetic outputs") args = parser.parse_args() binaries = {} - for name in ["bregctl", "evidencectl", "evidence"]: + if bool(args.breg) != bool(args.rstack): + parser.error("provide both --breg and --rstack for the served licence check") + names = ["bregctl", "evidencectl", "evidence"] + if args.breg: + names.extend(["breg", "rstack"]) + for name in names: path = getattr(args, name) if path is None or not path.is_file(): parser.error(f"provide --{name} with a matching native executable") @@ -492,10 +709,11 @@ def main() -> None: if args.work_dir: workspace = args.work_dir.resolve() workspace.mkdir(mode=0o700) - report = verify(workspace, binaries) + report = verify_live_public_check(workspace, binaries) if args.breg else verify(workspace, binaries) else: with tempfile.TemporaryDirectory(prefix="breg-evidence-composition-") as directory: - report = verify(Path(directory).resolve(), binaries) + workspace = Path(directory).resolve() + report = verify_live_public_check(workspace, binaries) if args.breg else verify(workspace, binaries) print(json.dumps(report, indent=2)) From 1fc1b3f9ee34f99b4d7e08958f113d99da34363c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:58:52 +0000 Subject: [PATCH 04/26] test(breg): let the released launcher cancel public-check startup Signed-off-by: Jeremi Joslin --- .../evidence/tests/test_verify_composition.py | 83 +++++++++++++++++++ .../breg/evidence/tests/verify-composition.py | 81 +++++++++++++++--- 2 files changed, 151 insertions(+), 13 deletions(-) create mode 100644 products/breg/evidence/tests/test_verify_composition.py diff --git a/products/breg/evidence/tests/test_verify_composition.py b/products/breg/evidence/tests/test_verify_composition.py new file mode 100644 index 0000000000..6b123b454a --- /dev/null +++ b/products/breg/evidence/tests/test_verify_composition.py @@ -0,0 +1,83 @@ +# SPDX-License-Identifier: Apache-2.0 + +import importlib.util +from pathlib import Path +import signal +import subprocess +import tempfile +import unittest +from unittest.mock import patch + + +spec = importlib.util.spec_from_file_location( + "verify_composition", Path(__file__).with_name("verify-composition.py"), +) +composition = importlib.util.module_from_spec(spec) +spec.loader.exec_module(composition) + + +class DevelopmentStartupTest(unittest.TestCase): + def test_slow_launch_gets_the_native_startup_window(self): + argv = ["rstack", "dev", "start", "/fixture"] + with patch.object(composition.subprocess, "Popen") as start: + process = start.return_value.__enter__.return_value + process.communicate.return_value = (b'{"status":"ready"}', b"") + process.returncode = 0 + output, interrupted = composition.start_development(argv, {}) + self.assertIsNone(interrupted) + self.assertEqual(output.stdout, b'{"status":"ready"}') + self.assertGreater(process.communicate.call_args.kwargs["timeout"], 360) + process.send_signal.assert_not_called() + + def test_timed_out_launch_can_return_a_ready_run_for_cleanup(self): + argv = ["rstack", "dev", "start", "/fixture"] + deadline = subprocess.TimeoutExpired(argv, 390) + with patch.object(composition.subprocess, "Popen") as start: + process = start.return_value.__enter__.return_value + process.communicate.side_effect = [deadline, (b'{"status":"ready"}', b"")] + process.returncode = 0 + output, interrupted = composition.start_development(argv, {}) + process.send_signal.assert_called_once_with(signal.SIGINT) + process.kill.assert_not_called() + self.assertIs(interrupted, deadline) + self.assertEqual(output.returncode, 0) + + def test_stalled_cancellation_reports_uncertain_cleanup(self): + argv = ["rstack", "dev", "start", "/fixture"] + with patch.object(composition.subprocess, "Popen") as start: + process = start.return_value.__enter__.return_value + process.communicate.side_effect = [ + subprocess.TimeoutExpired(argv, 390), + subprocess.TimeoutExpired(argv, 30), + ] + with self.assertRaises(composition.DevCleanupPending): + composition.start_development(argv, {}) + process.send_signal.assert_called_once_with(signal.SIGINT) + process.kill.assert_called_once() + process.wait.assert_called_once() + + def test_ready_run_returned_after_timeout_is_stopped_before_the_error(self): + argv = ["rstack", "dev", "start", "/fixture"] + deadline = subprocess.TimeoutExpired(argv, 390) + run = subprocess.CompletedProcess( + argv, 0, b'{"status":"ready","run_id":"synthetic-run","database":{"mode":"managed"}}', + ) + stopped = subprocess.CompletedProcess(argv, 0, b'{"status":"stopped"}') + binaries = {name: Path(name) for name in ("rstack", "evidence", "evidencectl", "breg", "bregctl")} + with patch.object(composition, "start_development", return_value=(run, deadline)), \ + patch.object(composition.subprocess, "run", return_value=stopped) as launcher: + with self.assertRaises(subprocess.TimeoutExpired): + with composition.managed_product(binaries, Path("/state"), Path("/fixture"), "breg"): + self.fail("the timed-out run must not execute a fixture") + self.assertEqual(launcher.call_args.args[0][-3:], ["stop", "synthetic-run", "--clean"]) + + def test_uncertain_cleanup_preserves_the_private_run_directory(self): + with tempfile.TemporaryDirectory() as parent: + with self.assertRaisesRegex(composition.DevCleanupPending, "Private recovery state"): + with composition.dev_workspace(Path(parent)) as scratch: + raise composition.DevCleanupPending("launcher cancellation did not settle") + self.assertTrue(scratch.is_dir()) + + +if __name__ == "__main__": + unittest.main() diff --git a/products/breg/evidence/tests/verify-composition.py b/products/breg/evidence/tests/verify-composition.py index 9011919dca..b2f040d3c4 100644 --- a/products/breg/evidence/tests/verify-composition.py +++ b/products/breg/evidence/tests/verify-composition.py @@ -13,6 +13,7 @@ import os from pathlib import Path import shutil +import signal import subprocess import tempfile from urllib.error import HTTPError @@ -245,6 +246,43 @@ def verify_public_check(workspace: Path, binaries: dict[str, Path], } +class DevCleanupPending(RuntimeError): + """Keep the private launcher state available for recovery.""" + + +def start_development(command: list[str], env: dict[str, str]): + interrupted = None + with subprocess.Popen(command, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + start_new_session=True) as process: + try: + # The released launcher owns the first deadline (360 seconds). + stdout, stderr = process.communicate(timeout=390) + except (KeyboardInterrupt, subprocess.TimeoutExpired) as error: + interrupted = error + process.send_signal(signal.SIGINT) + try: + stdout, stderr = process.communicate(timeout=30) + except (KeyboardInterrupt, subprocess.TimeoutExpired) as cleanup: + process.kill() + process.wait() + raise DevCleanupPending("launcher cancellation did not settle") from cleanup + return subprocess.CompletedProcess(command, process.returncode, stdout, stderr), interrupted + + +@contextmanager +def dev_workspace(parent: Path): + scratch = Path(tempfile.mkdtemp(prefix="licence-run-", dir=parent)) + preserve = False + try: + yield scratch + except DevCleanupPending as error: + preserve = True + raise DevCleanupPending(f"{error}. Private recovery state: {scratch}") from error + finally: + if not preserve: + shutil.rmtree(scratch) + + @contextmanager def managed_product(binaries: dict[str, Path], state: Path, project: Path, product: str): env = dict(os.environ) @@ -257,27 +295,45 @@ def managed_product(binaries: dict[str, Path], state: Path, project: Path, produ command = [str(binaries["rstack"]), "--install-root", str(state.parent / "install"), "--format", "json", "dev"] - def dev(*args: object) -> dict: - result = subprocess.run( - [*command, *map(str, args)], env=env, capture_output=True, timeout=180, check=False, - ) + def decode(result: subprocess.CompletedProcess, action: str) -> dict: report = json.loads(result.stdout) if result.returncode: - detail = report.get("error", {}).get("message") if args[0] != "token" else None - raise RuntimeError(f"{product} dev {args[0]} exited {result.returncode}: {detail}") + detail = report.get("error", {}).get("message") if action != "token" else None + raise RuntimeError(f"{product} dev {action} exited {result.returncode}: {detail}") return report - started = dev("start", project, "--ttl", "5m") - run_id = started["run_id"] + def dev(action: str, *args: object) -> dict: + result = subprocess.run( + [*command, action, *map(str, args)], env=env, capture_output=True, timeout=180, check=False, + ) + return decode(result, action) + + start, interrupted = start_development([*command, "start", str(project), "--ttl", "5m"], env) + if interrupted is not None and start.returncode: + if start.returncode < 0: + raise DevCleanupPending(f"{product} launcher exited on a signal") from interrupted + raise interrupted + try: + started = decode(start, "start") + run_id = started["run_id"] + except (ValueError, KeyError) as error: + raise DevCleanupPending(f"{product} launcher returned no recoverable run ID") from error + try: + if interrupted is not None: + # Readiness can race cancellation. Stop a run whose ID was returned. + raise interrupted assert started["status"] == "ready" origin = started["products"][product] assert origin.startswith("http://127.0.0.1:") yield origin, lambda alias: dev("token", run_id, "--as", alias) finally: - clean = ["--clean"] if started["database"]["mode"] == "managed" else [] - stopped = dev("stop", run_id, *clean) - assert stopped["status"] == "stopped" + try: + clean = ["--clean"] if started["database"]["mode"] == "managed" else [] + stopped = dev("stop", run_id, *clean) + assert stopped["status"] == "stopped" + except (Exception, KeyboardInterrupt) as error: + raise DevCleanupPending(f"{product} run {run_id} could not be confirmed stopped") from error def verify_live_public_check(workspace: Path, binaries: dict[str, Path]) -> dict: @@ -345,8 +401,7 @@ def verify_live_public_check(workspace: Path, binaries: dict[str, Path]) -> dict ] write(fixture_path, fixture) - with tempfile.TemporaryDirectory(prefix="licence-run-", dir=workspace) as work: - scratch = Path(work) + with dev_workspace(workspace.parent) as scratch: local = scratch / "evidence" shutil.copytree(project, local) with managed_product(binaries, scratch / "breg-state", registry, "breg") as (origin, token): From 4f2a1b67858fc4f6259486bf85bc871c565b6f6a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:13:39 +0000 Subject: [PATCH 05/26] feat(breg): select stored readable fields by classification Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/compiler.rs | 50 +++++++++ .../registry-breg/src/compiler/statistics.rs | 1 + crates/registry-breg/src/contract.rs | 20 +++- .../src/contract/readable_fields.rs | 99 +++++++++++++++++ crates/registry-breg/src/contract/sentinel.rs | 102 ++++++++++++++---- crates/registry-breg/src/external_views.rs | 57 +++++++--- crates/registry-breg/src/fixtures.rs | 1 + crates/registry-breg/src/immediate_actions.rs | 1 + crates/registry-breg/src/odrl_export.rs | 1 + .../registry-breg/tests/compiler_contract.rs | 28 +++++ .../registry-breg/tests/disclosure/fields.rs | 93 +++++++++++++++- crates/registry-breg/tests/external_views.rs | 24 +++++ .../authoring/registry-module.schema.json | 52 +++++---- .../authoring/registry-project.schema.json | 73 +++++++++---- 14 files changed, 520 insertions(+), 82 deletions(-) create mode 100644 crates/registry-breg/src/contract/readable_fields.rs diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index 142294ec20..203c9ccb83 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -329,6 +329,7 @@ pub fn compile_project_with_assets( disclosure::validate_module_access_reason_operations(&sources, &mut diagnostics); let module_profiles = crate::access::module_profile_keys(&sources); expand_project_access(project, &mut sources, &mut diagnostics); + resolve_readable_fields(&mut sources); resolve_vocabularies(project, &mut sources, &mut action_sources, &mut diagnostics); validate_entities( &project.project.id, @@ -4188,6 +4189,7 @@ pub(crate) fn expand_project_access( require_access_reason: profile.require_access_reason, operations: grant.operations.clone(), readable_fields: grant.readable_fields.clone(), + readable_fields_ceiling: grant.readable_fields_ceiling, readable_attachments: grant.readable_attachments.clone(), writable_fields: grant.writable_fields.clone(), filterable_fields: grant.filterable_fields.clone(), @@ -4208,6 +4210,54 @@ pub(crate) fn expand_project_access( } } +// Resolve against the composed record types, so grants include fields supplied +// by extensions and paths see the fields of their target record type. +fn resolve_readable_fields(entities: &mut BTreeMap) { + for id in entities.keys().cloned().collect::>() { + if entities[&id].access_profiles.iter().all(|profile| { + profile.readable_fields_ceiling.is_none() + && profile + .read_paths + .iter() + .all(|grant| grant.readable_fields_ceiling.is_none()) + }) { + continue; + } + let mut profiles = std::mem::take(&mut entities.get_mut(&id).unwrap().access_profiles); + let entity = &entities[&id]; + for profile in &mut profiles { + if let Some(ceiling) = profile.readable_fields_ceiling.take() { + profile.readable_fields = ceiling.select( + entity + .fields + .iter() + .map(|field| (&field.id, field.classification)), + ); + } + for grant in &mut profile.read_paths { + let Some(ceiling) = grant.readable_fields_ceiling.take() else { + continue; + }; + let target = entity + .read_paths + .iter() + .rfind(|path| path.id == grant.path) + .and_then(|path| entities.get(&path.to)); + // Existing path validation reports an unknown path or target. + if let Some(target) = target { + grant.readable_fields = ceiling.select( + target + .fields + .iter() + .map(|field| (&field.id, field.classification)), + ); + } + } + } + entities.get_mut(&id).unwrap().access_profiles = profiles; + } +} + fn resolve_vocabularies( project: &RegistryProject, entities: &mut BTreeMap, diff --git a/crates/registry-breg/src/compiler/statistics.rs b/crates/registry-breg/src/compiler/statistics.rs index 6ae477f835..c885ffb1e3 100644 --- a/crates/registry-breg/src/compiler/statistics.rs +++ b/crates/registry-breg/src/compiler/statistics.rs @@ -810,6 +810,7 @@ fn authentication_profile( required_purposes: profile.required_purposes.clone(), operations: Default::default(), readable_fields: Default::default(), + readable_fields_ceiling: None, readable_attachments: Default::default(), writable_fields: Default::default(), filterable_fields: Default::default(), diff --git a/crates/registry-breg/src/contract.rs b/crates/registry-breg/src/contract.rs index fddf2a5ffb..409b8210a0 100644 --- a/crates/registry-breg/src/contract.rs +++ b/crates/registry-breg/src/contract.rs @@ -19,7 +19,10 @@ use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use crate::diagnostics::{CompileFailure, Diagnostic}; pub use crate::unique_set::UniqueSet; -pub(crate) mod sentinel; +pub(crate) mod readable_fields; +mod sentinel; + +pub use readable_fields::{ExternalReadableFields, ReadableFields, ReadableFieldsCeiling}; /// Serialize a union read by `tagged_union!` in its authored form: one /// mapping whose `tag` member names the variant. `external` is the variant as @@ -5437,6 +5440,8 @@ pub struct AccessProfileSource { pub operations: UniqueSet, #[serde(default)] pub readable_fields: UniqueSet, + #[serde(skip)] + pub(crate) readable_fields_ceiling: Option, /// Record attachment slots the profile may download. Requires `get`. #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] pub readable_attachments: UniqueSet, @@ -5921,7 +5926,8 @@ pub struct PermissionsSource { #[serde(default)] pub datasets: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub external_views: Vec, + pub external_views: + Vec>, #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] pub refresh_external_projections: UniqueSet, } @@ -5999,6 +6005,7 @@ pub struct CompiledTaskGrantPermissionSource { #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde( try_from = "sentinel::AuthoredEntityPermission", + into = "sentinel::AuthoredEntityPermission", rename_all = "camelCase" )] pub struct EntityPermissionSource { @@ -6006,6 +6013,8 @@ pub struct EntityPermissionSource { pub entity: String, pub operations: UniqueSet, pub readable_fields: UniqueSet, + #[serde(skip)] + pub(crate) readable_fields_ceiling: Option, /// Record attachment slots the profile may download. Requires `get`. #[serde(skip_serializing_if = "UniqueSet::is_empty")] pub readable_attachments: UniqueSet, @@ -6096,10 +6105,13 @@ pub enum LookupValueOrigin { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct ReadPathPermissionSource { +pub struct ReadPathPermissionSource> { pub path: String, #[serde(default)] - pub readable_fields: UniqueSet, + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] + pub readable_fields: Fields, + #[serde(skip)] + pub(crate) readable_fields_ceiling: Option, #[serde(default)] pub filterable_fields: UniqueSet, #[serde(default)] diff --git a/crates/registry-breg/src/contract/readable_fields.rs b/crates/registry-breg/src/contract/readable_fields.rs new file mode 100644 index 0000000000..6bdd1718f1 --- /dev/null +++ b/crates/registry-breg/src/contract/readable_fields.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 + +use registry_platform_yaml::{shape_union, LocalId}; +use serde::{Deserialize, Serialize}; + +use super::{Classification, ReadPathPermissionSource, UniqueSet}; + +/// Include stored fields classified at or below this level. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct ReadableFieldsCeiling { + pub up_to_classification: Classification, +} + +impl ReadableFieldsCeiling { + pub(crate) fn select<'a, T: Clone + Ord + 'a>( + self, + fields: impl Iterator, + ) -> UniqueSet { + fields + .filter(|(_, classification)| *classification <= self.up_to_classification) + .map(|(id, _)| id.clone()) + .collect() + } +} + +macro_rules! readable_fields { + ($name:ident, $id:ty) => { + /// An explicit field list or an inclusive ceiling on stored field classification. + #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] + #[derive(Clone, Debug, Eq, PartialEq, Serialize)] + #[serde(untagged)] + pub enum $name { + Explicit(UniqueSet<$id>), + Ceiling(ReadableFieldsCeiling), + } + + shape_union!($name { list => Explicit, mapping => Ceiling }); + }; +} + +readable_fields!(ReadableFields, String); +readable_fields!(ExternalReadableFields, LocalId); + +impl Default for ReadableFields { + fn default() -> Self { + Self::Explicit(UniqueSet::new()) + } +} + +impl ReadableFields { + pub(super) fn into_parts(self) -> (UniqueSet, Option) { + match self { + Self::Explicit(fields) => (fields, None), + Self::Ceiling(ceiling) => (UniqueSet::new(), Some(ceiling)), + } + } + + pub(super) fn from_parts( + fields: UniqueSet, + ceiling: Option, + ) -> Self { + match ceiling { + Some(ceiling) => Self::Ceiling(ceiling), + None => Self::Explicit(fields), + } + } +} + +impl From> for ReadPathPermissionSource { + fn from(authored: ReadPathPermissionSource) -> Self { + let (readable_fields, readable_fields_ceiling) = authored.readable_fields.into_parts(); + Self { + path: authored.path, + readable_fields, + readable_fields_ceiling, + filterable_fields: authored.filterable_fields, + sortable_fields: authored.sortable_fields, + allow_count: authored.allow_count, + } + } +} + +impl From for ReadPathPermissionSource { + fn from(source: ReadPathPermissionSource) -> Self { + Self { + path: source.path, + readable_fields: ReadableFields::from_parts( + source.readable_fields, + source.readable_fields_ceiling, + ), + readable_fields_ceiling: None, + filterable_fields: source.filterable_fields, + sortable_fields: source.sortable_fields, + allow_count: source.allow_count, + } + } +} diff --git a/crates/registry-breg/src/contract/sentinel.rs b/crates/registry-breg/src/contract/sentinel.rs index 49546f7dad..df263029e3 100644 --- a/crates/registry-breg/src/contract/sentinel.rs +++ b/crates/registry-breg/src/contract/sentinel.rs @@ -22,7 +22,7 @@ use super::{ AccessProfileSource, AccessRequirementsSource, ActorKindSource, CompiledTaskGrantSource, ConsentRequirementSource, EntityPermissionSource, LookupPermissionSource, MembershipBoundarySource, Operation, PermissionsSource, ProvenanceFieldSource, - ReadPathPermissionSource, RequiredFilterSource, RowBoundarySource, + ReadPathPermissionSource, ReadableFields, RequiredFilterSource, RowBoundarySource, SpatialQueryPermissionSource, UniqueSet, }; @@ -491,7 +491,7 @@ pub(super) struct AuthoredModuleProfile { require_access_reason: bool, operations: UniqueSet, #[serde(default)] - readable_fields: UniqueSet, + readable_fields: ReadableFields, /// Record attachment slots the profile may download. Requires `get`. #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] readable_attachments: UniqueSet, @@ -531,7 +531,7 @@ pub(super) struct AuthoredModuleProfile { #[serde(default, skip_serializing_if = "Vec::is_empty")] lookups: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] - read_paths: Vec, + read_paths: Vec>, #[serde(default, skip_serializing_if = "super::is_false")] allow_count: bool, #[serde(default)] @@ -552,6 +552,7 @@ pub(super) struct AuthoredModuleProfile { impl From for AccessProfileSource { fn from(authored: AuthoredModuleProfile) -> Self { + let (readable_fields, readable_fields_ceiling) = authored.readable_fields.into_parts(); Self { id: authored.id, display: authored.display, @@ -564,7 +565,8 @@ impl From for AccessProfileSource { required_purposes: authored.required_purposes, require_access_reason: authored.require_access_reason, operations: authored.operations, - readable_fields: authored.readable_fields, + readable_fields, + readable_fields_ceiling, readable_attachments: authored.readable_attachments, writable_fields: authored.writable_fields, filterable_fields: authored.filterable_fields, @@ -575,7 +577,7 @@ impl From for AccessProfileSource { membership_boundaries: authored.membership_boundaries, require_consent: authored.require_consent, lookups: authored.lookups, - read_paths: authored.read_paths, + read_paths: authored.read_paths.into_iter().map(Into::into).collect(), allow_count: authored.allow_count, revision_access: authored.revision_access, provenance_fields: authored.provenance_fields, @@ -598,7 +600,10 @@ impl From for AuthoredModuleProfile { required_purposes: profile.required_purposes, require_access_reason: profile.require_access_reason, operations: profile.operations, - readable_fields: profile.readable_fields, + readable_fields: ReadableFields::from_parts( + profile.readable_fields, + profile.readable_fields_ceiling, + ), readable_attachments: profile.readable_attachments, writable_fields: profile.writable_fields, filterable_fields: profile.filterable_fields, @@ -609,7 +614,7 @@ impl From for AuthoredModuleProfile { membership_boundaries: profile.membership_boundaries, require_consent: profile.require_consent, lookups: profile.lookups, - read_paths: profile.read_paths, + read_paths: profile.read_paths.into_iter().map(Into::into).collect(), allow_count: profile.allow_count, revision_access: profile.revision_access, provenance_fields: profile.provenance_fields, @@ -688,14 +693,14 @@ pub(super) fn permissions<'de, D: Deserializer<'de>>( /// What a profile may do with one entity. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schema", schemars(rename = "EntityPermissionSource"))] -#[derive(Deserialize)] +#[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub(super) struct AuthoredEntityPermission { #[serde(rename = "recordType")] entity: String, operations: UniqueSet, #[serde(default)] - readable_fields: UniqueSet, + readable_fields: ReadableFields, /// Record attachment slots the profile may download. Requires `get`. #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] readable_attachments: UniqueSet, @@ -721,35 +726,57 @@ pub(super) struct AuthoredEntityPermission { required_filters: Vec, #[serde(default)] sortable_fields: UniqueSet, - #[serde(default)] + #[serde(default, skip_serializing_if = "Option::is_none")] spatial_queries: Option, /// Row reach: `unrestricted`, or a list of at least one row boundary. + #[serde(serialize_with = "serialize_entity_rows")] #[cfg_attr(feature = "schema", schemars(with = "RowBoundaries"))] row_boundaries: Option, /// Current active membership required for each stored reference key. - #[serde(default)] + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] membership_boundaries: Vec, /// Current subject-issued consent required for each row, ANDed. - #[serde(default)] + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] require_consent: Vec, - #[serde(default)] + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] lookups: Vec, - #[serde(default)] - read_paths: Vec, - #[serde(default)] + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] + read_paths: Vec>, + #[serde(default, skip_serializing_if = "super::is_false")] + #[cfg_attr(feature = "schema", schemars(extend("default" = false)))] allow_count: bool, #[serde(default)] revision_access: bool, - #[serde(default, deserialize_with = "super::unique_items")] + #[serde( + default, + deserialize_with = "super::unique_items", + skip_serializing_if = "Vec::is_empty" + )] #[cfg_attr( feature = "schema", - schemars(with = "UniqueSet") + schemars(with = "UniqueSet", extend("default" = [])) )] provenance_fields: Vec, #[serde(default)] allow_data_export: bool, } +fn serialize_entity_rows( + rows: &Option, + serializer: S, +) -> Result { + match rows { + Some(RowBoundaries::Unrestricted(_)) => serializer.serialize_str(UNRESTRICTED), + Some(RowBoundaries::Listed(Listed(rows, _))) => rows.serialize(serializer), + Some(RowBoundaries::Reference(_)) => Err(serde::ser::Error::custom(UNRESOLVED_REFERENCE)), + None => serializer.serialize_none(), + } +} + impl TryFrom for EntityPermissionSource { type Error = Invalid; @@ -760,10 +787,12 @@ impl TryFrom for EntityPermissionSource { "Declare rowBoundaries on the permission: list the row boundaries that bind rows to the caller's claims, or write unrestricted to reach every row.", )); }; + let (readable_fields, readable_fields_ceiling) = authored.readable_fields.into_parts(); Ok(Self { entity: authored.entity, operations: authored.operations, - readable_fields: authored.readable_fields, + readable_fields, + readable_fields_ceiling, readable_attachments: authored.readable_attachments, writable_fields: authored.writable_fields, filterable_fields: authored.filterable_fields, @@ -774,7 +803,7 @@ impl TryFrom for EntityPermissionSource { membership_boundaries: authored.membership_boundaries, require_consent: authored.require_consent, lookups: authored.lookups, - read_paths: authored.read_paths, + read_paths: authored.read_paths.into_iter().map(Into::into).collect(), allow_count: authored.allow_count, revision_access: authored.revision_access, provenance_fields: authored.provenance_fields, @@ -782,3 +811,36 @@ impl TryFrom for EntityPermissionSource { }) } } + +impl From for AuthoredEntityPermission { + fn from(source: EntityPermissionSource) -> Self { + let rows = if source.row_boundaries.is_empty() { + RowBoundaries::Unrestricted(Unrestricted(PhantomData)) + } else { + RowBoundaries::Listed(Listed(source.row_boundaries, PhantomData)) + }; + Self { + entity: source.entity, + operations: source.operations, + readable_fields: ReadableFields::from_parts( + source.readable_fields, + source.readable_fields_ceiling, + ), + readable_attachments: source.readable_attachments, + writable_fields: source.writable_fields, + filterable_fields: source.filterable_fields, + required_filters: source.required_filters, + sortable_fields: source.sortable_fields, + spatial_queries: source.spatial_queries, + row_boundaries: Some(rows), + membership_boundaries: source.membership_boundaries, + require_consent: source.require_consent, + lookups: source.lookups, + read_paths: source.read_paths.into_iter().map(Into::into).collect(), + allow_count: source.allow_count, + revision_access: source.revision_access, + provenance_fields: source.provenance_fields, + allow_data_export: source.allow_data_export, + } + } +} diff --git a/crates/registry-breg/src/external_views.rs b/crates/registry-breg/src/external_views.rs index bd36969d36..69cdf0ae0f 100644 --- a/crates/registry-breg/src/external_views.rs +++ b/crates/registry-breg/src/external_views.rs @@ -7,8 +7,8 @@ use registry_platform_yaml::{BoundedU32, ExternalId, LocalId}; use serde::{Deserialize, Serialize}; use crate::contract::{ - ActorKindSource, Classification, DisplaySource, FieldTypeSource, Operation, RegistryProject, - UniqueSet, + ActorKindSource, Classification, DisplaySource, ExternalReadableFields, FieldTypeSource, + Operation, RegistryProject, UniqueSet, }; use crate::diagnostics::Diagnostic; use crate::model::CompiledEntity; @@ -195,17 +195,17 @@ pub struct ExternalLabelSource { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct ExternalViewPermissionSource { +pub struct ExternalViewPermissionSource> { pub view: LocalId, - pub links: Vec, + pub links: Vec>, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct ExternalLinkPermissionSource { +pub struct ExternalLinkPermissionSource> { pub link: LocalId, - pub readable_fields: UniqueSet, + pub readable_fields: Fields, #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] pub filterable_fields: UniqueSet, #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] @@ -619,10 +619,7 @@ pub(crate) fn compile( "Grant get on the local root record type in this same profile.", ); } - if view_grants - .insert(permission.view.as_str().to_owned(), permission.clone()) - .is_some() - { + if view_grants.contains_key(permission.view.as_str()) { error( &mut diagnostics, "duplicate-view-grant", @@ -631,6 +628,7 @@ pub(crate) fn compile( ); } let mut link_grants = BTreeSet::new(); + let mut compiled_links = Vec::new(); for (link_index, grant) in permission.links.iter().enumerate() { let path = format!("{path}/links/{link_index}"); if !link_grants.insert(&grant.link) { @@ -650,8 +648,22 @@ pub(crate) fn compile( ); continue; }; - if grant.readable_fields.is_empty() - || !grant.readable_fields.is_subset(&link.fields) + let projection = projections.get(link.projection.as_str()); + let readable_fields = match &grant.readable_fields { + ExternalReadableFields::Explicit(fields) => fields.clone(), + ExternalReadableFields::Ceiling(ceiling) => ceiling.select( + projection + .and_then(|projection| { + record_types.get(projection.record_type.as_str()) + }) + .into_iter() + .flat_map(|record_type| &record_type.fields) + .filter(|field| link.fields.contains(&field.id)) + .map(|field| (&field.id, field.classification)), + ), + }; + if readable_fields.is_empty() + || !readable_fields.is_subset(&link.fields) || (!grant.label_fields.is_empty() && !link .label @@ -661,8 +673,8 @@ pub(crate) fn compile( error(&mut diagnostics, "invalid-read-grant", path.clone(), "Grant only declared link fields, with an explicit separate grant for labels."); } - if !grant.filterable_fields.is_subset(&grant.readable_fields) - || !grant.sortable_fields.is_subset(&grant.readable_fields) + if !grant.filterable_fields.is_subset(&readable_fields) + || !grant.sortable_fields.is_subset(&readable_fields) { error( &mut diagnostics, @@ -674,7 +686,7 @@ pub(crate) fn compile( let uses_query = !grant.filterable_fields.is_empty() || !grant.sortable_fields.is_empty() || grant.allow_count; - if let Some(projection) = projections.get(link.projection.as_str()) { + if let Some(projection) = projection { if !profile .required_purposes .contains(projection.purpose.as_str()) @@ -706,7 +718,22 @@ pub(crate) fn compile( "Grant list and, for a count, allowCount on the local record type.", ); } + compiled_links.push(ExternalLinkPermissionSource { + link: grant.link.clone(), + readable_fields, + filterable_fields: grant.filterable_fields.clone(), + sortable_fields: grant.sortable_fields.clone(), + allow_count: grant.allow_count, + label_fields: grant.label_fields.clone(), + }); } + view_grants.insert( + permission.view.as_str().to_owned(), + ExternalViewPermissionSource { + view: permission.view.clone(), + links: compiled_links, + }, + ); } if !view_grants.is_empty() { grants.insert(profile.id.clone(), view_grants); diff --git a/crates/registry-breg/src/fixtures.rs b/crates/registry-breg/src/fixtures.rs index 4e1a5e5900..41648f7de5 100644 --- a/crates/registry-breg/src/fixtures.rs +++ b/crates/registry-breg/src/fixtures.rs @@ -1908,6 +1908,7 @@ fn action_profile_from_grant( required_purposes: grant.required_purposes.clone().into(), operations: grant.operations.clone().into(), readable_fields: Default::default(), + readable_fields_ceiling: None, readable_attachments: Default::default(), writable_fields: Default::default(), filterable_fields: Default::default(), diff --git a/crates/registry-breg/src/immediate_actions.rs b/crates/registry-breg/src/immediate_actions.rs index f2f746cba9..c6bb79acc3 100644 --- a/crates/registry-breg/src/immediate_actions.rs +++ b/crates/registry-breg/src/immediate_actions.rs @@ -2653,6 +2653,7 @@ fn validate_permission_access_requirements( require_access_reason: profile.require_access_reason, operations: [Operation::Invoke].into(), readable_fields: Default::default(), + readable_fields_ceiling: None, readable_attachments: Default::default(), writable_fields: Default::default(), filterable_fields: Default::default(), diff --git a/crates/registry-breg/src/odrl_export.rs b/crates/registry-breg/src/odrl_export.rs index b2f853c422..cd537817bd 100644 --- a/crates/registry-breg/src/odrl_export.rs +++ b/crates/registry-breg/src/odrl_export.rs @@ -351,6 +351,7 @@ fn audit_access_profile(access: &AccessProfileSource) { required_purposes: _, operations: _, readable_fields: _, + readable_fields_ceiling: _, // The export describes record field projections only. A profile's // file downloads are not part of the exported permission. readable_attachments: _, diff --git a/crates/registry-breg/tests/compiler_contract.rs b/crates/registry-breg/tests/compiler_contract.rs index a5f3d54153..3a59662e47 100644 --- a/crates/registry-breg/tests/compiler_contract.rs +++ b/crates/registry-breg/tests/compiler_contract.rs @@ -1890,6 +1890,34 @@ fn derived_fields_selectors_and_read_paths_compile_to_route_specific_inventories assert!(path.allow_count); assert!(path.processing_fields.contains(&"household".to_owned())); assert!(path.processing_fields.contains(&"person".to_owned())); + + let compile = |source: &Value| { + compile_json_with_assets( + &serde_json::to_vec(source).unwrap(), + vec![derived_sql_asset("sql/household-demographics.sql", sql)], + ) + }; + let mut source: Value = serde_json::from_slice(project).unwrap(); + source["recordTypes"]["household"]["derived"][0]["fields"][0]["classification"] = + json!("internal"); + let grant = &mut source["accessProfiles"]["operator"]["permissions"]["records"][0]; + grant["readableFields"] = json!([ + "household-code", + "administrative-area", + "local-household-number" + ]); + grant["filterableFields"] = json!([]); + grant["sortableFields"] = json!([]); + let explicit = compile(&source).expect("the explicit stored fields compile"); + let grant = &mut source["accessProfiles"]["operator"]["permissions"]["records"][0]; + grant["readableFields"] = json!({"upToClassification": "internal"}); + grant["readPaths"][0]["readableFields"] = json!({"upToClassification": "internal"}); + let ceiling = compile(&source).expect("the classification ceiling compiles"); + assert_eq!(explicit.revision(), ceiling.revision()); + assert_eq!(explicit.artifacts(), ceiling.artifacts()); + assert!(!ceiling.entities()["household"].access_profiles["operator"] + .readable_fields + .contains("child-count")); } #[test] diff --git a/crates/registry-breg/tests/disclosure/fields.rs b/crates/registry-breg/tests/disclosure/fields.rs index 009c6c06f4..6f01d64af3 100644 --- a/crates/registry-breg/tests/disclosure/fields.rs +++ b/crates/registry-breg/tests/disclosure/fields.rs @@ -65,7 +65,10 @@ fn the_fixture_withholds_contacts_from_the_registrar_only() { /// The fixture project with create and patch granted on `person`. fn writable_project() -> registry_breg::CompiledRegistry { - let mut source = project_source(); + compile_writable_project(project_source()) +} + +fn compile_writable_project(mut source: Value) -> registry_breg::CompiledRegistry { source["recordTypes"]["person"]["batch"] = json!({"maximumItems": 4, "maximumBytes": 8192}); for profile in source["accessProfiles"] .as_object_mut() @@ -92,7 +95,10 @@ impl ReadinessProbe for Ready { /// The fixture rows installed under the writable project, with the router that /// serves them. async fn serve() -> (Fixture, axum::Router) { - let registry = writable_project(); + serve_project(writable_project()).await +} + +async fn serve_project(registry: registry_breg::CompiledRegistry) -> (Fixture, axum::Router) { let database = TestDatabase::create(4).await; let (migration, task) = database.connect_migration().await; install_compiled_schema(&migration, ®istry, &database.runtime_role) @@ -279,6 +285,89 @@ fn api_names(fixture: &Fixture, fields: &[&str]) -> BTreeSet { .collect() } +fn project_with_stored_field_ceiling() -> Value { + let mut source = project_source(); + let fields = source["recordTypes"]["person"]["fields"] + .as_array_mut() + .unwrap(); + fields[0]["classification"] = json!("public"); + fields[4]["classification"] = json!("restricted"); + source["accessProfiles"][REGISTRAR]["permissions"]["records"][0]["readableFields"] = + json!({"upToClassification": "internal"}); + source +} + +#[test] +fn classification_ceiling_keeps_the_authored_shape_and_refuses_unknown_members() { + let mut source = project_with_stored_field_ceiling(); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + assert_eq!( + serde_json::to_value(project).unwrap()["accessProfiles"][REGISTRAR]["permissions"] + ["records"][0]["readableFields"], + json!({"upToClassification": "internal"}) + ); + source["accessProfiles"][REGISTRAR]["permissions"]["records"][0]["readableFields"] + ["unexpected"] = json!("restricted"); + assert!(parse_project_json(&serde_json::to_vec(&source).unwrap()).is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn stored_field_classification_ceiling_limits_the_served_profile() { + let (fixture, app) = + serve_project(compile_writable_project(project_with_stored_field_ceiling())).await; + + let open = send( + &app, + Method::GET, + &person_path(OPEN_PERSON_ID), + REGISTRAR, + &[], + None, + ) + .await; + assert_eq!(open.status, StatusCode::OK, "{}", open.text); + assert_eq!( + data_members(&open), + api_names(&fixture, &PERSON_FIELDS[..4]) + ); + assert_eq!( + find_object(&open.body, "domainData").unwrap()["familyName"], + "Open" + ); + + let protected = send( + &app, + Method::GET, + &person_path(PERSON_ID), + REGISTRAR, + &[], + None, + ) + .await; + assert_eq!(protected.status, StatusCode::OK, "{}", protected.text); + assert_eq!( + find_object(&protected.body, "domainData").unwrap()["emailAddress"], + Value::Null + ); + assert_no_sentinel(&protected.text); + + let officer = send( + &app, + Method::GET, + &person_path(PERSON_ID), + PROTECTION_OFFICER, + &[], + None, + ) + .await; + assert_eq!(officer.status, StatusCode::OK, "{}", officer.text); + assert_eq!( + find_object(&officer.body, "domainData").unwrap()["phoneNumber"], + CANARY_PHONE + ); + fixture.database.cleanup().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_get_nulls_withheld_members_only_while_the_condition_matches() { let (fixture, app) = serve().await; diff --git a/crates/registry-breg/tests/external_views.rs b/crates/registry-breg/tests/external_views.rs index ea7609e71a..eab4656518 100644 --- a/crates/registry-breg/tests/external_views.rs +++ b/crates/registry-breg/tests/external_views.rs @@ -102,6 +102,30 @@ fn external_views_are_compiled_separately_from_owned_fields_and_permissions() { .is_some()); } +#[test] +fn classification_ceiling_selects_only_projected_fields_and_preserves_query_refusals() { + let source = PROJECT.replace( + " - {id: code, type: integer, classification: restricted}", + " - {id: code, type: integer, classification: restricted}\n - {id: outside, type: string, classification: public}", + ); + let explicit = compile(&source).expect("the explicit external field list compiles"); + let ceiling = source.replace( + "readableFields: [label]", + "readableFields: {upToClassification: internal}", + ); + let compiled = compile(&ceiling).expect("the external ceiling compiles"); + assert_eq!(explicit.revision(), compiled.revision()); + assert_eq!(explicit.artifacts(), compiled.artifacts()); + rejects( + &ceiling.replace("filterableFields: [label]", "filterableFields: [code]"), + "breg.external-view.processing-wider-than-read", + ); + rejects( + &ceiling.replace("upToClassification: internal", "upToClassification: public"), + "breg.external-view.invalid-read-grant", + ); +} + #[test] fn query_grant_cannot_use_a_hidden_external_field() { rejects( diff --git a/products/breg/generated/authoring/registry-module.schema.json b/products/breg/generated/authoring/registry-module.schema.json index 49c574bb84..2ae04de68e 100644 --- a/products/breg/generated/authoring/registry-module.schema.json +++ b/products/breg/generated/authoring/registry-module.schema.json @@ -3421,12 +3421,8 @@ "type": "string" }, "readableFields": { - "default": [], - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": true + "$ref": "#/$defs/ReadableFields", + "default": [] }, "sortableFields": { "default": [], @@ -3466,6 +3462,34 @@ ], "type": "object" }, + "ReadableFields": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": true + }, + { + "$ref": "#/$defs/ReadableFieldsCeiling" + } + ], + "description": "An explicit field list or an inclusive ceiling on stored field classification." + }, + "ReadableFieldsCeiling": { + "additionalProperties": false, + "description": "Include stored fields classified at or below this level.", + "properties": { + "upToClassification": { + "$ref": "#/$defs/Classification" + } + }, + "required": [ + "upToClassification" + ], + "type": "object" + }, "RecordAttachmentSlotSource": { "additionalProperties": false, "description": "One file slot on a record type. A file enters it through an immediate\nAction create effect in the same request, or when an applied Proposal\npromotes one of its files. Once written it never changes.", @@ -4538,12 +4562,8 @@ "uniqueItems": true }, "readableFields": { - "default": [], - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": true + "$ref": "#/$defs/ReadableFields", + "default": [] }, "requesterClients": { "description": "The OAuth clients whose tokens may select this profile. Omit to accept every client.", @@ -4844,12 +4864,8 @@ "uniqueItems": true }, "readableFields": { - "default": [], - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": true + "$ref": "#/$defs/ReadableFields", + "default": [] }, "requesterClients": { "description": "The OAuth clients whose tokens may select this profile. Omit to accept every client.", diff --git a/products/breg/generated/authoring/registry-project.schema.json b/products/breg/generated/authoring/registry-project.schema.json index 1357ab5c4f..ca017a2d29 100644 --- a/products/breg/generated/authoring/registry-project.schema.json +++ b/products/breg/generated/authoring/registry-project.schema.json @@ -2349,12 +2349,8 @@ "uniqueItems": true }, "readableFields": { - "default": [], - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": true + "$ref": "#/$defs/ReadableFields", + "default": [] }, "recordType": { "type": "string" @@ -2742,11 +2738,7 @@ "$ref": "#/$defs/LocalId" }, "readableFields": { - "items": { - "$ref": "#/$defs/LocalId" - }, - "type": "array", - "uniqueItems": true + "$ref": "#/$defs/ExternalReadableFields" }, "sortableFields": { "items": { @@ -2769,6 +2761,21 @@ ], "type": "string" }, + "ExternalReadableFields": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/LocalId" + }, + "type": "array", + "uniqueItems": true + }, + { + "$ref": "#/$defs/ReadableFieldsCeiling" + } + ], + "description": "An explicit field list or an inclusive ceiling on stored field classification." + }, "ExternalReferenceSource": { "additionalProperties": false, "properties": { @@ -4493,12 +4500,8 @@ "type": "string" }, "readableFields": { - "default": [], - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": true + "$ref": "#/$defs/ReadableFields", + "default": [] }, "sortableFields": { "default": [], @@ -4538,6 +4541,34 @@ ], "type": "object" }, + "ReadableFields": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": true + }, + { + "$ref": "#/$defs/ReadableFieldsCeiling" + } + ], + "description": "An explicit field list or an inclusive ceiling on stored field classification." + }, + "ReadableFieldsCeiling": { + "additionalProperties": false, + "description": "Include stored fields classified at or below this level.", + "properties": { + "upToClassification": { + "$ref": "#/$defs/Classification" + } + }, + "required": [ + "upToClassification" + ], + "type": "object" + }, "RecipientGroupSource": { "additionalProperties": false, "description": "A frozen, named list of declared organizations. Groups do not nest.", @@ -6451,12 +6482,8 @@ "uniqueItems": true }, "readableFields": { - "default": [], - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": true + "$ref": "#/$defs/ReadableFields", + "default": [] }, "requesterClients": { "description": "The OAuth clients whose tokens may select this profile. Omit to accept every client.", From 7333c3b88e9d9aa72a65b20b7e2b575436157c94 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:27:39 +0000 Subject: [PATCH 06/26] fix(breg): scope classification ceilings to owned stored fields Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/contract.rs | 5 +- .../src/contract/readable_fields.rs | 31 +++----- crates/registry-breg/src/external_views.rs | 57 ++++---------- crates/registry-breg/tests/external_views.rs | 44 +++++------ .../tests/package_change_plan.rs | 75 +++++++++++++++++++ .../tests/postgres_client_relationships.rs | 14 +++- .../content/docs/configure/breg-access.mdx | 10 +++ .../src/content/docs/operate/breg-changes.mdx | 10 +++ docs/site/src/content/docs/security/breg.mdx | 10 +++ .../authoring/registry-project.schema.json | 21 ++---- 10 files changed, 174 insertions(+), 103 deletions(-) diff --git a/crates/registry-breg/src/contract.rs b/crates/registry-breg/src/contract.rs index 409b8210a0..2f64f56487 100644 --- a/crates/registry-breg/src/contract.rs +++ b/crates/registry-breg/src/contract.rs @@ -22,7 +22,7 @@ pub use crate::unique_set::UniqueSet; pub(crate) mod readable_fields; mod sentinel; -pub use readable_fields::{ExternalReadableFields, ReadableFields, ReadableFieldsCeiling}; +pub use readable_fields::{ReadableFields, ReadableFieldsCeiling}; /// Serialize a union read by `tagged_union!` in its authored form: one /// mapping whose `tag` member names the variant. `external` is the variant as @@ -5926,8 +5926,7 @@ pub struct PermissionsSource { #[serde(default)] pub datasets: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub external_views: - Vec>, + pub external_views: Vec, #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] pub refresh_external_projections: UniqueSet, } diff --git a/crates/registry-breg/src/contract/readable_fields.rs b/crates/registry-breg/src/contract/readable_fields.rs index 6bdd1718f1..f49f3676d9 100644 --- a/crates/registry-breg/src/contract/readable_fields.rs +++ b/crates/registry-breg/src/contract/readable_fields.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 -use registry_platform_yaml::{shape_union, LocalId}; +use registry_platform_yaml::shape_union; use serde::{Deserialize, Serialize}; use super::{Classification, ReadPathPermissionSource, UniqueSet}; @@ -14,10 +14,10 @@ pub struct ReadableFieldsCeiling { } impl ReadableFieldsCeiling { - pub(crate) fn select<'a, T: Clone + Ord + 'a>( + pub(crate) fn select<'a>( self, - fields: impl Iterator, - ) -> UniqueSet { + fields: impl Iterator, + ) -> UniqueSet { fields .filter(|(_, classification)| *classification <= self.up_to_classification) .map(|(id, _)| id.clone()) @@ -25,23 +25,16 @@ impl ReadableFieldsCeiling { } } -macro_rules! readable_fields { - ($name:ident, $id:ty) => { - /// An explicit field list or an inclusive ceiling on stored field classification. - #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] - #[derive(Clone, Debug, Eq, PartialEq, Serialize)] - #[serde(untagged)] - pub enum $name { - Explicit(UniqueSet<$id>), - Ceiling(ReadableFieldsCeiling), - } - - shape_union!($name { list => Explicit, mapping => Ceiling }); - }; +/// An explicit field list or an inclusive ceiling on stored field classification. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ReadableFields { + Explicit(UniqueSet), + Ceiling(ReadableFieldsCeiling), } -readable_fields!(ReadableFields, String); -readable_fields!(ExternalReadableFields, LocalId); +shape_union!(ReadableFields { list => Explicit, mapping => Ceiling }); impl Default for ReadableFields { fn default() -> Self { diff --git a/crates/registry-breg/src/external_views.rs b/crates/registry-breg/src/external_views.rs index 69cdf0ae0f..bd36969d36 100644 --- a/crates/registry-breg/src/external_views.rs +++ b/crates/registry-breg/src/external_views.rs @@ -7,8 +7,8 @@ use registry_platform_yaml::{BoundedU32, ExternalId, LocalId}; use serde::{Deserialize, Serialize}; use crate::contract::{ - ActorKindSource, Classification, DisplaySource, ExternalReadableFields, FieldTypeSource, - Operation, RegistryProject, UniqueSet, + ActorKindSource, Classification, DisplaySource, FieldTypeSource, Operation, RegistryProject, + UniqueSet, }; use crate::diagnostics::Diagnostic; use crate::model::CompiledEntity; @@ -195,17 +195,17 @@ pub struct ExternalLabelSource { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct ExternalViewPermissionSource> { +pub struct ExternalViewPermissionSource { pub view: LocalId, - pub links: Vec>, + pub links: Vec, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct ExternalLinkPermissionSource> { +pub struct ExternalLinkPermissionSource { pub link: LocalId, - pub readable_fields: Fields, + pub readable_fields: UniqueSet, #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] pub filterable_fields: UniqueSet, #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] @@ -619,7 +619,10 @@ pub(crate) fn compile( "Grant get on the local root record type in this same profile.", ); } - if view_grants.contains_key(permission.view.as_str()) { + if view_grants + .insert(permission.view.as_str().to_owned(), permission.clone()) + .is_some() + { error( &mut diagnostics, "duplicate-view-grant", @@ -628,7 +631,6 @@ pub(crate) fn compile( ); } let mut link_grants = BTreeSet::new(); - let mut compiled_links = Vec::new(); for (link_index, grant) in permission.links.iter().enumerate() { let path = format!("{path}/links/{link_index}"); if !link_grants.insert(&grant.link) { @@ -648,22 +650,8 @@ pub(crate) fn compile( ); continue; }; - let projection = projections.get(link.projection.as_str()); - let readable_fields = match &grant.readable_fields { - ExternalReadableFields::Explicit(fields) => fields.clone(), - ExternalReadableFields::Ceiling(ceiling) => ceiling.select( - projection - .and_then(|projection| { - record_types.get(projection.record_type.as_str()) - }) - .into_iter() - .flat_map(|record_type| &record_type.fields) - .filter(|field| link.fields.contains(&field.id)) - .map(|field| (&field.id, field.classification)), - ), - }; - if readable_fields.is_empty() - || !readable_fields.is_subset(&link.fields) + if grant.readable_fields.is_empty() + || !grant.readable_fields.is_subset(&link.fields) || (!grant.label_fields.is_empty() && !link .label @@ -673,8 +661,8 @@ pub(crate) fn compile( error(&mut diagnostics, "invalid-read-grant", path.clone(), "Grant only declared link fields, with an explicit separate grant for labels."); } - if !grant.filterable_fields.is_subset(&readable_fields) - || !grant.sortable_fields.is_subset(&readable_fields) + if !grant.filterable_fields.is_subset(&grant.readable_fields) + || !grant.sortable_fields.is_subset(&grant.readable_fields) { error( &mut diagnostics, @@ -686,7 +674,7 @@ pub(crate) fn compile( let uses_query = !grant.filterable_fields.is_empty() || !grant.sortable_fields.is_empty() || grant.allow_count; - if let Some(projection) = projection { + if let Some(projection) = projections.get(link.projection.as_str()) { if !profile .required_purposes .contains(projection.purpose.as_str()) @@ -718,22 +706,7 @@ pub(crate) fn compile( "Grant list and, for a count, allowCount on the local record type.", ); } - compiled_links.push(ExternalLinkPermissionSource { - link: grant.link.clone(), - readable_fields, - filterable_fields: grant.filterable_fields.clone(), - sortable_fields: grant.sortable_fields.clone(), - allow_count: grant.allow_count, - label_fields: grant.label_fields.clone(), - }); } - view_grants.insert( - permission.view.as_str().to_owned(), - ExternalViewPermissionSource { - view: permission.view.clone(), - links: compiled_links, - }, - ); } if !view_grants.is_empty() { grants.insert(profile.id.clone(), view_grants); diff --git a/crates/registry-breg/tests/external_views.rs b/crates/registry-breg/tests/external_views.rs index eab4656518..bdf1fbd2e9 100644 --- a/crates/registry-breg/tests/external_views.rs +++ b/crates/registry-breg/tests/external_views.rs @@ -103,27 +103,29 @@ fn external_views_are_compiled_separately_from_owned_fields_and_permissions() { } #[test] -fn classification_ceiling_selects_only_projected_fields_and_preserves_query_refusals() { - let source = PROJECT.replace( - " - {id: code, type: integer, classification: restricted}", - " - {id: code, type: integer, classification: restricted}\n - {id: outside, type: string, classification: public}", - ); - let explicit = compile(&source).expect("the explicit external field list compiles"); - let ceiling = source.replace( - "readableFields: [label]", - "readableFields: {upToClassification: internal}", - ); - let compiled = compile(&ceiling).expect("the external ceiling compiles"); - assert_eq!(explicit.revision(), compiled.revision()); - assert_eq!(explicit.artifacts(), compiled.artifacts()); - rejects( - &ceiling.replace("filterableFields: [label]", "filterableFields: [code]"), - "breg.external-view.processing-wider-than-read", - ); - rejects( - &ceiling.replace("upToClassification: internal", "upToClassification: public"), - "breg.external-view.invalid-read-grant", - ); +fn both_external_projection_modes_require_explicit_readable_fields() { + let indexed = PROJECT.to_owned(); + let live = PROJECT + .replace("mode: indexed", "mode: live") + .replace(" cacheTtlSeconds: 600\n", "") + .replace(" filterableFields: [label]\n", ""); + for source in [indexed, live] { + compile(&source).expect("an explicit external field list compiles"); + let ceiling = source.replace( + "readableFields: [label]", + "readableFields: {upToClassification: internal}", + ); + let error = + parse_project_yaml(ceiling.as_bytes()).expect_err("external ceiling is refused"); + assert!( + error.diagnostics().iter().any(|diagnostic| { + diagnostic.code == "config.invalid-type" + && diagnostic.path + == "project.accessProfiles.reader.permissions.externalViews[0].links[0].readableFields" + }), + "{error:?}" + ); + } } #[test] diff --git a/crates/registry-breg/tests/package_change_plan.rs b/crates/registry-breg/tests/package_change_plan.rs index dc9f3ab060..6ef2b819db 100644 --- a/crates/registry-breg/tests/package_change_plan.rs +++ b/crates/registry-breg/tests/package_change_plan.rs @@ -96,6 +96,81 @@ fn geojson_binding_changes_are_classified_as_disclosure_even_for_get_only_profil } } +#[cfg(feature = "tooling")] +#[test] +fn stored_field_ceiling_widens_compiled_access_on_successor_field_changes() { + use registry_breg::tooling::{ + classify_registry_diff, AccessChangeDirection, DiffClassification, + }; + + let source = json!({ + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", + "kind":"BRegProject", + "project":{"id":"ceiling-change", "version":"1", "defaultLanguage":"en", + "canonicalBaseIri":"https://ceiling.example.test"}, + "datasets":{"records":{}}, + "recordTypes":{"record":{ + "primaryDataset":"records","route":"records", + "mutationMode":"mutable","classification":"internal", + "fields":[{"id":"label","type":"string","maximumLength":64,"classification":"internal"}] + }}, + "accessProfiles":{"reader":{ + "principalClaim":"sub","requiredScopes":["records:read"], + "permissions":{"records":[{ + "recordType":"record","operations":["get"],"rowBoundaries":"unrestricted", + "readableFields":{"upToClassification":"internal"} + }]} + }} + }); + let compile = |value: &serde_json::Value| { + let project = parse_project_json(&serde_json::to_vec(value).unwrap()).unwrap(); + compile_project(&project, &[], CompileProfile::Authoring).unwrap() + }; + let mut restricted = source.clone(); + restricted["recordTypes"]["record"]["fields"] + .as_array_mut() + .unwrap() + .push( + json!({"id":"note","type":"string","maximumLength":64,"classification":"restricted"}), + ); + let mut included = restricted.clone(); + included["recordTypes"]["record"]["fields"][1]["classification"] = json!("internal"); + let candidate = compile(&included); + for predecessor in [source, restricted] { + assert_eq!(predecessor["accessProfiles"], included["accessProfiles"]); + let previous = compile(&predecessor); + assert!(!previous.entities()["record"].access_profiles["reader"] + .readable_fields + .contains("note")); + assert!(candidate.entities()["record"].access_profiles["reader"] + .readable_fields + .contains("note")); + let diff = classify_registry_diff(&previous, &candidate, PRIOR_REVISION); + let change = diff + .changes + .iter() + .find(|change| change.change.code == CompiledRegistryChangeCode::AccessProfileChanged) + .expect("the unchanged authored ceiling widens the compiled grant"); + assert_eq!( + change.classification, + DiffClassification::DisclosureWidening + ); + assert_eq!( + change.change.target.record_type_id.as_deref(), + Some("record") + ); + assert_eq!(change.change.target.member_id.as_deref(), Some("reader")); + let detail = change + .access_details + .iter() + .find(|detail| detail.field == "readableFields") + .expect("the report identifies the field grant that widens"); + assert_eq!(detail.direction, AccessChangeDirection::Widening); + assert_eq!(detail.before, json!(["label"])); + assert_eq!(detail.after, json!(["label", "note"])); + } +} + #[cfg(feature = "tooling")] #[test] fn geojson_only_successor_uses_existing_metadata_review_without_dummy_sql() { diff --git a/crates/registry-breg/tests/postgres_client_relationships.rs b/crates/registry-breg/tests/postgres_client_relationships.rs index e07e559127..650d3d02fe 100644 --- a/crates/registry-breg/tests/postgres_client_relationships.rs +++ b/crates/registry-breg/tests/postgres_client_relationships.rs @@ -168,6 +168,16 @@ async fn sdk_relationship_continuation_keeps_source_path_authority_and_target_pr } assert_eq!(seen, linked_ids); assert!(!seen.contains(&unlinked.value.data.record_id)); + let refused = client + .list_relationship_records( + "households", + &household.value.data.record_id, + "people", + &relationship_request("operator", "sensitiveNote"), + ) + .await + .expect_err("an explicit select cannot exceed the path's classification ceiling"); + assert_eq!(refused.status(), Some(400)); fixture.finish().await; } @@ -399,7 +409,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { }, "person": {"primaryDataset":"test-dataset","route":"people","mutationMode":"mutable","classification":"restricted", "fields":[ - {"id":"person-code","type":"string","required":true,"maximumLength":64,"classification":"restricted"}, + {"id":"person-code","type":"string","required":true,"maximumLength":64,"classification":"internal"}, {"id":"sensitive-note","type":"string","required":true,"maximumLength":64,"classification":"restricted"} ] } @@ -411,7 +421,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { { "recordType":"household","rowBoundaries":"unrestricted","operations":["create","get","list"], "readableFields":["household-code"],"writableFields":["household-code"], - "readPaths":[{"path":"people","readableFields":["person-code"],"sortableFields":["person-code"],"allowCount":true}] + "readPaths":[{"path":"people","readableFields":{"upToClassification":"internal"},"sortableFields":["person-code"],"allowCount":true}] }, {"recordType":"membership","rowBoundaries":"unrestricted","operations":["create"],"readableFields":["household","person"],"writableFields":["household","person"]}, { diff --git a/docs/site/src/content/docs/configure/breg-access.mdx b/docs/site/src/content/docs/configure/breg-access.mdx index e24d3a7e6a..49d88d3c5b 100644 --- a/docs/site/src/content/docs/configure/breg-access.mdx +++ b/docs/site/src/content/docs/configure/breg-access.mdx @@ -114,6 +114,16 @@ response discloses and `writableFields` what a create or patch may set; `filtera `sortableFields`, and `allowCount` each enable one query feature. Field lists use the field `id`, not its `apiName`. A write never reveals a field the profile cannot read. +For stored fields, you can write `readableFields: {upToClassification: internal}`. +BReg includes fields whose classification is at or below your ceiling. +On a read path, the ceiling applies to stored fields of the target Record type. +Name derived fields and external view fields in explicit lists. +Review the resulting grants when you [apply a successor package](../../operate/breg-changes/#compare-the-candidate-with-the-active-package). + +{/* Evidence: crates/registry-breg/src/contract/readable_fields.rs, ReadableFieldsCeiling; + crates/registry-breg/src/compiler.rs, resolve_readable_fields(); + crates/registry-breg/tests/postgres_client_relationships.rs, sdk_relationship_continuation_keeps_source_path_authority_and_target_projection. */} + A [row boundary](../../reference/glossary/#row-boundary) compares a Record field with a token claim. `equals` compares with one scalar claim value. `in` requires a claim whose value is a JSON array; in a development plan, write the array as a YAML sequence under `claims.breg`. diff --git a/docs/site/src/content/docs/operate/breg-changes.mdx b/docs/site/src/content/docs/operate/breg-changes.mdx index 554b8f4952..bbfb76153d 100644 --- a/docs/site/src/content/docs/operate/breg-changes.mdx +++ b/docs/site/src/content/docs/operate/breg-changes.mdx @@ -122,6 +122,16 @@ credentials; the report says `integrity-only`. Pass `--runtime-config` instead t the package the database has activated. For an access change the diff also marks each detail as `widening`, `narrowing`, or `review-required`. +When a permission uses `readableFields.upToClassification`, compare its compiled grant in both packages. +A new stored field within the ceiling enters the successor grant automatically. +Lowering a stored field's classification can also bring it into the grant. +The diff lists a widened direct field grant as `widening` and a changed read path as `review-required`. +The holder of the migration credential reviews the changed access before applying the successor. + +{/* Evidence: crates/registry-breg/src/compiler.rs, resolve_readable_fields(); + crates/registry-breg/src/tooling.rs, classify_registry_diff(); + crates/registry-breg/tests/package_change_plan.rs, stored_field_ceiling_widens_compiled_access_on_successor_field_changes. */} + Removing a field or a Record type is not erasure. The successor drops the live column or table, but every earlier revision snapshot and every backup still holds the removed values, and the diff warns with `diff.history.removed-values-retained`. When the removal is for data minimisation, also diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 898775d3f2..2bd4b3ffae 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -270,6 +270,16 @@ Review the public Source, the Evidence derivation and the target activation toge ### Disclosure conditions +BReg resolves a stored-field classification ceiling to field IDs at package compilation. +The ceiling applies to owned Record fields on a direct grant or at the target of a read path. +Existing row and field disclosure checks still apply to the resolved grant. +Field additions and reclassification can widen the next compiled grant. +Review that change before activation. [Compare the candidate with the active package](../../operate/breg-changes/#compare-the-candidate-with-the-active-package). + +{/* Evidence: crates/registry-breg/src/compiler.rs, resolve_readable_fields(); + crates/registry-breg/tests/disclosure/fields.rs, stored_field_classification_ceiling_limits_the_served_profile; + crates/registry-breg/tests/package_change_plan.rs, stored_field_ceiling_widens_compiled_access_on_successor_field_changes. */} + A disclosure condition withholds a Record, its history, or named fields from every access profile it does not exempt, while the Record's current values match the condition. A `record` condition is a restrictive row-level security policy on the Record table. diff --git a/products/breg/generated/authoring/registry-project.schema.json b/products/breg/generated/authoring/registry-project.schema.json index ca017a2d29..d660e07e08 100644 --- a/products/breg/generated/authoring/registry-project.schema.json +++ b/products/breg/generated/authoring/registry-project.schema.json @@ -2738,7 +2738,11 @@ "$ref": "#/$defs/LocalId" }, "readableFields": { - "$ref": "#/$defs/ExternalReadableFields" + "items": { + "$ref": "#/$defs/LocalId" + }, + "type": "array", + "uniqueItems": true }, "sortableFields": { "items": { @@ -2761,21 +2765,6 @@ ], "type": "string" }, - "ExternalReadableFields": { - "anyOf": [ - { - "items": { - "$ref": "#/$defs/LocalId" - }, - "type": "array", - "uniqueItems": true - }, - { - "$ref": "#/$defs/ReadableFieldsCeiling" - } - ], - "description": "An explicit field list or an inclusive ceiling on stored field classification." - }, "ExternalReferenceSource": { "additionalProperties": false, "properties": { From a2aacc748a32aea5a8f79b4d22b2b481bee28f02 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:11:42 +0000 Subject: [PATCH 07/26] test(breg): cover module ceilings and default traversal Signed-off-by: Jeremi Joslin --- .../registry-breg/tests/compiler_contract.rs | 84 ++++++++++++++++++- .../tests/postgres_client_relationships.rs | 44 ++++++++++ 2 files changed, 124 insertions(+), 4 deletions(-) diff --git a/crates/registry-breg/tests/compiler_contract.rs b/crates/registry-breg/tests/compiler_contract.rs index 3a59662e47..a3e539191d 100644 --- a/crates/registry-breg/tests/compiler_contract.rs +++ b/crates/registry-breg/tests/compiler_contract.rs @@ -1702,9 +1702,7 @@ fn constraint_unions_refuse_at_the_member_inside_the_form() { } } -#[test] -fn derived_fields_selectors_and_read_paths_compile_to_route_specific_inventories() { - let project = br#"{"datasets":{"test-dataset": {}}, +const DERIVED_HOUSEHOLD_PROJECT: &[u8] = br#"{"datasets":{"test-dataset": {}}, "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", "kind":"BRegProject", "project":{"id":"household-demo","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://authoring.example.test"}, @@ -1761,7 +1759,85 @@ fn derived_fields_selectors_and_read_paths_compile_to_route_specific_inventories }]} }} }"#; - let sql = "SELECT h.id AS id, count(p.id)::bigint AS child_count, false AS single_headed, 1::bigint AS registry_derived_key_cardinality FROM registry_source.household h LEFT JOIN registry_source.group_membership gm ON gm.household = h.id LEFT JOIN registry_source.person p ON p.id = gm.person GROUP BY h.id"; +const DERIVED_HOUSEHOLD_SQL: &str = "SELECT h.id AS id, count(p.id)::bigint AS child_count, false AS single_headed, 1::bigint AS registry_derived_key_cardinality FROM registry_source.household h LEFT JOIN registry_source.group_membership gm ON gm.household = h.id LEFT JOIN registry_source.person p ON p.id = gm.person GROUP BY h.id"; + +#[test] +fn a_module_ceiling_round_trips_and_selects_only_eligible_stored_fields() { + let mut source: Value = serde_json::from_slice(DERIVED_HOUSEHOLD_PROJECT).unwrap(); + let mut derived = source["recordTypes"]["household"] + .as_object_mut() + .unwrap() + .remove("derived") + .unwrap(); + derived[0]["fields"][0]["classification"] = json!("internal"); + let ceiling = json!({"upToClassification": "internal"}); + let module_source = json!({ + "apiVersion": "id.registrystack.org/formats/breg/module/v1alpha1", + "kind": "BRegModule", + "id": "disclosure-extension", + "version": "1", + "extendRecordTypes": {"household": { + "fields": [ + {"id": "extension-note", "type": "string", "maximumLength": 64, "classification": "internal"}, + {"id": "restricted-note", "type": "string", "maximumLength": 64, "classification": "restricted"} + ], + "derived": derived, + "accessProfiles": {"module-reader": { + "principalClaim": "registry_principal", "requiredScopes": ["module:read"], + "operations": ["get", "list"], "rowBoundaries": "unrestricted", + "readableFields": ceiling + }} + }} + }); + let module = parse_module_json(&serde_json::to_vec(&module_source).unwrap()).unwrap(); + let mut round_trip: Value = + serde_json::from_slice(&source_bytes::source_bytes(&module)).unwrap(); + round_trip["apiVersion"] = json!(MODULE_API_VERSION); + round_trip["kind"] = json!(MODULE_KIND); + assert_eq!( + round_trip["extendRecordTypes"]["household"]["accessProfiles"]["module-reader"] + ["readableFields"], + ceiling, + ); + let reread = parse_module_json(&serde_json::to_vec(&round_trip).unwrap()).unwrap(); + assert_eq!(reread, module); + let assets = [ModuleAssetSource { + module: Some("disclosure-extension".to_owned()), + path: "sql/household-demographics.sql".to_owned(), + bytes: DERIVED_HOUSEHOLD_SQL.as_bytes().to_vec(), + }]; + let digest = registry_breg::compiler::module_digest_with_assets(&reread, &assets); + source["modules"] = json!({"disclosure-extension": {"version": "1", "digest": digest}}); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let compiled = + compile_project_with_assets(&project, &[reread], &assets, CompileProfile::Authoring) + .expect("the module extension and its lock compile after round trip"); + let household = &compiled.entities()["household"]; + assert!(household.fields.contains_key("restricted-note")); + assert!(household.derived_fields.contains_key("child-count")); + + let openapi = &compiled + .artifacts() + .get("generated/openapi.json") + .unwrap() + .bytes; + let openapi = parse_json_strict(openapi).unwrap(); + assert_eq!( + openapi["paths"]["/v1/records/households"]["get"]["x-registry-queryProfiles"] + ["module-reader"]["selectableProperties"], + json!([ + "administrativeArea", + "extensionNote", + "householdCode", + "localHouseholdNumber" + ]), + ); +} + +#[test] +fn derived_fields_selectors_and_read_paths_compile_to_route_specific_inventories() { + let project = DERIVED_HOUSEHOLD_PROJECT; + let sql = DERIVED_HOUSEHOLD_SQL; let compiled = compile_json_with_assets( project, vec![derived_sql_asset("sql/household-demographics.sql", sql)], diff --git a/crates/registry-breg/tests/postgres_client_relationships.rs b/crates/registry-breg/tests/postgres_client_relationships.rs index 650d3d02fe..53fe6690cb 100644 --- a/crates/registry-breg/tests/postgres_client_relationships.rs +++ b/crates/registry-breg/tests/postgres_client_relationships.rs @@ -105,6 +105,50 @@ async fn sdk_relationship_continuation_keeps_source_path_authority_and_target_pr .iter() .all(|record| !record.domain_data.contains_key("personCode"))); + let openapi: Value = serde_json::from_slice( + &fixture + .registry + .artifacts() + .get("generated/openapi.json") + .unwrap() + .bytes, + ) + .unwrap(); + let selectable = openapi["paths"]["/v1/records/households/{record_id}/people"]["get"] + ["x-registry-queryProfiles"]["operator"]["selectableProperties"] + .as_array() + .unwrap() + .iter() + .map(|field| field.as_str().unwrap()) + .collect::>(); + assert_eq!(selectable, BTreeSet::from(["personCode"])); + let default_page = client + .list_relationship_records( + "households", + &household.value.data.record_id, + "people", + &BRegRelationshipListRequest::default().options( + BRegRecordOptions::default() + .access_profile("operator") + .unwrap(), + ), + ) + .await + .unwrap(); + let mut default_ids = BTreeSet::new(); + for record in default_page.value.value.items { + assert!(default_ids.insert(record.record_id)); + assert_eq!( + record + .domain_data + .keys() + .map(String::as_str) + .collect::>(), + selectable, + ); + } + assert_eq!(default_ids, linked_ids); + let request = BRegRelationshipListRequest::default() .options( BRegRecordOptions::default() From 57dfbe72117be567e62b9368dd9f81ddd3f40619 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:19:35 +0000 Subject: [PATCH 08/26] fix(breg): keep consent-scoped field grants explicit Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/compiler.rs | 26 +++++- .../registry-breg/tests/compiler_contract.rs | 43 +++++++-- crates/registry-breg/tests/consent_access.rs | 26 ++++++ .../tests/package_change_plan.rs | 90 +++++++++++++++++++ .../content/docs/configure/breg-access.mdx | 1 + .../src/content/docs/operate/breg-changes.mdx | 8 +- docs/site/src/content/docs/security/breg.mdx | 25 +++--- products/breg/CHANGELOG.md | 4 + 8 files changed, 200 insertions(+), 23 deletions(-) diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index 203c9ccb83..97f8008b7e 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -329,7 +329,7 @@ pub fn compile_project_with_assets( disclosure::validate_module_access_reason_operations(&sources, &mut diagnostics); let module_profiles = crate::access::module_profile_keys(&sources); expand_project_access(project, &mut sources, &mut diagnostics); - resolve_readable_fields(&mut sources); + resolve_readable_fields(&mut sources, &mut diagnostics); resolve_vocabularies(project, &mut sources, &mut action_sources, &mut diagnostics); validate_entities( &project.project.id, @@ -4212,7 +4212,10 @@ pub(crate) fn expand_project_access( // Resolve against the composed record types, so grants include fields supplied // by extensions and paths see the fields of their target record type. -fn resolve_readable_fields(entities: &mut BTreeMap) { +fn resolve_readable_fields( + entities: &mut BTreeMap, + errors: &mut Vec, +) { for id in entities.keys().cloned().collect::>() { if entities[&id].access_profiles.iter().all(|profile| { profile.readable_fields_ceiling.is_none() @@ -4226,7 +4229,12 @@ fn resolve_readable_fields(entities: &mut BTreeMap) { let mut profiles = std::mem::take(&mut entities.get_mut(&id).unwrap().access_profiles); let entity = &entities[&id]; for profile in &mut profiles { + let consent_scope = (!profile.require_consent.is_empty()) + .then(|| format!("recordTypes[id={id}].accessProfiles[id={}]", profile.id)); if let Some(ceiling) = profile.readable_fields_ceiling.take() { + if let Some(path) = &consent_scope { + errors.push(consent_ceiling_refusal(format!("{path}.readableFields"))); + } profile.readable_fields = ceiling.select( entity .fields @@ -4238,6 +4246,12 @@ fn resolve_readable_fields(entities: &mut BTreeMap) { let Some(ceiling) = grant.readable_fields_ceiling.take() else { continue; }; + if let Some(path) = &consent_scope { + errors.push(consent_ceiling_refusal(format!( + "{path}.readPaths[path={}].readableFields", + grant.path + ))); + } let target = entity .read_paths .iter() @@ -4258,6 +4272,14 @@ fn resolve_readable_fields(entities: &mut BTreeMap) { } } +fn consent_ceiling_refusal(path: String) -> Diagnostic { + Diagnostic::error( + "breg.consent.readable-fields-explicit-required", + path, + "a permission with requireConsent needs an explicit readableFields list for it and its read paths, so the existing consent scope cannot grow when fields change", + ) +} + fn resolve_vocabularies( project: &RegistryProject, entities: &mut BTreeMap, diff --git a/crates/registry-breg/tests/compiler_contract.rs b/crates/registry-breg/tests/compiler_contract.rs index a3e539191d..f8a763d765 100644 --- a/crates/registry-breg/tests/compiler_contract.rs +++ b/crates/registry-breg/tests/compiler_contract.rs @@ -1771,7 +1771,7 @@ fn a_module_ceiling_round_trips_and_selects_only_eligible_stored_fields() { .unwrap(); derived[0]["fields"][0]["classification"] = json!("internal"); let ceiling = json!({"upToClassification": "internal"}); - let module_source = json!({ + let mut module_source = json!({ "apiVersion": "id.registrystack.org/formats/breg/module/v1alpha1", "kind": "BRegModule", "id": "disclosure-extension", @@ -1806,12 +1806,41 @@ fn a_module_ceiling_round_trips_and_selects_only_eligible_stored_fields() { path: "sql/household-demographics.sql".to_owned(), bytes: DERIVED_HOUSEHOLD_SQL.as_bytes().to_vec(), }]; - let digest = registry_breg::compiler::module_digest_with_assets(&reread, &assets); - source["modules"] = json!({"disclosure-extension": {"version": "1", "digest": digest}}); - let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); - let compiled = - compile_project_with_assets(&project, &[reread], &assets, CompileProfile::Authoring) - .expect("the module extension and its lock compile after round trip"); + let mut compile_module = |module| { + let digest = registry_breg::compiler::module_digest_with_assets(&module, &assets); + source["modules"] = json!({"disclosure-extension": {"version": "1", "digest": digest}}); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + compile_project_with_assets(&project, &[module], &assets, CompileProfile::Authoring) + .expect("the module extension and its lock compile") + }; + let compiled = compile_module(reread); + module_source["extendRecordTypes"]["household"]["accessProfiles"]["module-reader"] + ["readableFields"] = json!([ + "administrative-area", + "extension-note", + "household-code", + "local-household-number" + ]); + let explicit = + compile_module(parse_module_json(&serde_json::to_vec(&module_source).unwrap()).unwrap()); + assert_eq!(compiled.access(), explicit.access()); + assert_ne!( + compiled.revision(), + explicit.revision(), + "the authored module lock changes" + ); + assert_eq!( + compiled + .artifacts() + .get("generated/openapi.json") + .unwrap() + .bytes, + explicit + .artifacts() + .get("generated/openapi.json") + .unwrap() + .bytes, + ); let household = &compiled.entities()["household"]; assert!(household.fields.contains_key("restricted-note")); assert!(household.derived_fields.contains_key("child-count")); diff --git a/crates/registry-breg/tests/consent_access.rs b/crates/registry-breg/tests/consent_access.rs index 0da8cd5d28..8c62320169 100644 --- a/crates/registry-breg/tests/consent_access.rs +++ b/crates/registry-breg/tests/consent_access.rs @@ -547,6 +547,32 @@ fn gated_permissions_refuse_spatial_queries() { assert_refused(&value, "breg.consent.require-spatial-unsupported"); } +#[test] +fn a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths() { + compile(&source()).expect("the explicit direct and path grants remain valid"); + let base = "recordTypes[id=person].accessProfiles[id=food-targeting]"; + for (member, expected) in [ + ("/readableFields", format!("{base}.readableFields")), + ( + "/readPaths/0/readableFields", + format!("{base}.readPaths[path=households].readableFields"), + ), + ] { + let mut value = source(); + let grant = &mut value["accessProfiles"][FOOD_TARGETING]["permissions"]["records"][0]; + *grant.pointer_mut(member).unwrap() = json!({"upToClassification": "restricted"}); + let Err(failure) = compile(&value) else { + panic!("the consent scope must keep explicit fields at {expected}"); + }; + let finding = failure + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "breg.consent.readable-fields-explicit-required") + .expect("the compiler identifies the ceiling on the consent scope"); + assert_eq!(finding.path, expected); + } +} + #[test] fn gated_permissions_refuse_data_export() { let mut value = source(); diff --git a/crates/registry-breg/tests/package_change_plan.rs b/crates/registry-breg/tests/package_change_plan.rs index 6ef2b819db..a1fa365883 100644 --- a/crates/registry-breg/tests/package_change_plan.rs +++ b/crates/registry-breg/tests/package_change_plan.rs @@ -171,6 +171,96 @@ fn stored_field_ceiling_widens_compiled_access_on_successor_field_changes() { } } +#[cfg(feature = "tooling")] +#[test] +fn a_widened_list_or_read_path_ceiling_requires_review_before_apply() { + use serde_json::Value; + + let fixture = json!({ + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", + "kind":"BRegProject", + "project":{"id":"ceiling-change", "version":"1", "defaultLanguage":"en", + "canonicalBaseIri":"https://ceiling.example.test"}, + "package":{"sourceRevision":SOURCE_REVISION}, + "datasets":{"records":{}}, + "recordTypes":{ + "record":{"primaryDataset":"records","route":"records","mutationMode":"mutable", + "fields":[{"id":"label","type":"string","maximumLength":64,"classification":"internal"}]}, + "target":{"primaryDataset":"records","route":"targets","mutationMode":"mutable", + "fields":[{"id":"label","type":"string","maximumLength":64,"classification":"internal"}]}, + "link":{"primaryDataset":"records","route":"links","mutationMode":"mutable","fields":[ + {"id":"record","type":"reference","target":"record","classification":"internal"}, + {"id":"target","type":"reference","target":"target","classification":"internal"} + ]} + }, + "accessProfiles":{"reader":{ + "principalClaim":"sub","requiredScopes":["records:read"], + "permissions":{"records":[{ + "recordType":"record","operations":["get"],"rowBoundaries":"unrestricted", + "readableFields":["label"] + }]} + }} + }); + let compile = |value: &Value| { + let project = parse_project_json(&serde_json::to_vec(value).unwrap()).unwrap(); + compile_project(&project, &[], CompileProfile::Production).unwrap() + }; + for (record, query) in [ + ("record", "records.record.reader.list"), + ("target", "records.record.reader.path.targets"), + ] { + let mut before = fixture.clone(); + let ceiling = json!({"upToClassification": "internal"}); + if record == "record" { + let grant = &mut before["accessProfiles"]["reader"]["permissions"]["records"][0]; + grant["operations"] = json!(["get", "list"]); + grant["readableFields"] = ceiling; + } else { + before["recordTypes"]["record"]["readPaths"] = + json!([{"id":"targets","route":"targets","through":"link","to":"target"}]); + before["accessProfiles"]["reader"]["permissions"]["records"][0]["readPaths"] = + json!([{"path":"targets","readableFields":ceiling}]); + } + let mut after = before.clone(); + after["recordTypes"][record]["fields"] + .as_array_mut() + .unwrap() + .push( + json!({"id":"note","type":"string","maximumLength":64,"classification":"internal"}), + ); + let previous = compile(&before); + let candidate = compile(&after); + let change_set = compiled_registry_change_set(&previous, &candidate, PRIOR_REVISION); + assert!( + change_set.changes.iter().any(|change| { + change.code == CompiledRegistryChangeCode::QueryInventoryChanged + && change.target.member_id.as_deref() == Some(query) + }), + "the existing query projection changes for {query}" + ); + assert_eq!( + change_set_to_applicable_migration_plan(&change_set), + Err(PackageError::MigrationPlan), + "an automatic apply plan must refuse this change for {query}" + ); + + let mut request = build_request( + Some(PRIOR_REVISION), + serde_json::to_vec(&after).unwrap(), + Vec::new(), + PackageMigrationPlanInput::Successor { + prior_registry: Box::new(previous), + }, + ); + request.modules.clear(); + assert_eq!( + prepare_package(request).unwrap_err(), + PackageError::MigrationPlan, + "a package suitable for apply needs a reviewed migration for {query}" + ); + } +} + #[cfg(feature = "tooling")] #[test] fn geojson_only_successor_uses_existing_metadata_review_without_dummy_sql() { diff --git a/docs/site/src/content/docs/configure/breg-access.mdx b/docs/site/src/content/docs/configure/breg-access.mdx index 49d88d3c5b..fefeb9de0f 100644 --- a/docs/site/src/content/docs/configure/breg-access.mdx +++ b/docs/site/src/content/docs/configure/breg-access.mdx @@ -118,6 +118,7 @@ For stored fields, you can write `readableFields: {upToClassification: internal} BReg includes fields whose classification is at or below your ceiling. On a read path, the ceiling applies to stored fields of the target Record type. Name derived fields and external view fields in explicit lists. +For a permission with `requireConsent`, list the direct and read-path fields explicitly. Review the resulting grants when you [apply a successor package](../../operate/breg-changes/#compare-the-candidate-with-the-active-package). {/* Evidence: crates/registry-breg/src/contract/readable_fields.rs, ReadableFieldsCeiling; diff --git a/docs/site/src/content/docs/operate/breg-changes.mdx b/docs/site/src/content/docs/operate/breg-changes.mdx index bbfb76153d..a7f812fbb7 100644 --- a/docs/site/src/content/docs/operate/breg-changes.mdx +++ b/docs/site/src/content/docs/operate/breg-changes.mdx @@ -123,14 +123,16 @@ the package the database has activated. For an access change the diff also marks `widening`, `narrowing`, or `review-required`. When a permission uses `readableFields.upToClassification`, compare its compiled grant in both packages. -A new stored field within the ceiling enters the successor grant automatically. -Lowering a stored field's classification can also bring it into the grant. +The compiler includes newly eligible stored fields in the successor grant. +A field addition or a lower classification can make a field eligible. The diff lists a widened direct field grant as `widening` and a changed read path as `review-required`. +If the ceiling changes an existing list or read-path query's projection, prepare a reviewed migration before applying the successor. The holder of the migration credential reviews the changed access before applying the successor. {/* Evidence: crates/registry-breg/src/compiler.rs, resolve_readable_fields(); crates/registry-breg/src/tooling.rs, classify_registry_diff(); - crates/registry-breg/tests/package_change_plan.rs, stored_field_ceiling_widens_compiled_access_on_successor_field_changes. */} + crates/registry-breg/tests/package_change_plan.rs, stored_field_ceiling_widens_compiled_access_on_successor_field_changes, + a_widened_list_or_read_path_ceiling_requires_review_before_apply. */} Removing a field or a Record type is not erasure. The successor drops the live column or table, but every earlier revision snapshot and every backup still holds the removed values, and the diff warns diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 2bd4b3ffae..2f3d46a8f2 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -270,16 +270,6 @@ Review the public Source, the Evidence derivation and the target activation toge ### Disclosure conditions -BReg resolves a stored-field classification ceiling to field IDs at package compilation. -The ceiling applies to owned Record fields on a direct grant or at the target of a read path. -Existing row and field disclosure checks still apply to the resolved grant. -Field additions and reclassification can widen the next compiled grant. -Review that change before activation. [Compare the candidate with the active package](../../operate/breg-changes/#compare-the-candidate-with-the-active-package). - -{/* Evidence: crates/registry-breg/src/compiler.rs, resolve_readable_fields(); - crates/registry-breg/tests/disclosure/fields.rs, stored_field_classification_ceiling_limits_the_served_profile; - crates/registry-breg/tests/package_change_plan.rs, stored_field_ceiling_widens_compiled_access_on_successor_field_changes. */} - A disclosure condition withholds a Record, its history, or named fields from every access profile it does not exempt, while the Record's current values match the condition. A `record` condition is a restrictive row-level security policy on the Record table. @@ -872,6 +862,19 @@ and its ancestors. Deny other write access in every posture and group write acce If data subjects must see Proposal review reads and attachment downloads, cover them in your own audit, because they write no subject-log entry. +23. Review compiled classification ceilings before applying a successor. + BReg resolves the ceiling to stored Record fields at package compilation and applies the usual disclosure checks. + As the migration credential holder, compare the effective fields of each affected direct grant and read path. + Additions and reclassification can widen the grant under the same authored ceiling. + Revisions use the current grant, so lowering a classification can expose earlier values to a profile with history access. + Keep the direct and path field grants for each consent scope in explicit lists, as the compiler requires. + [Compare the candidate with the active package](../../operate/breg-changes/#compare-the-candidate-with-the-active-package). + {/* Evidence: crates/registry-breg/src/compiler.rs, resolve_readable_fields(), consent_ceiling_refusal(); + crates/registry-breg/src/postgres/history_read.rs, readable_fields; + crates/registry-breg/tests/disclosure/fields.rs, stored_field_classification_ceiling_limits_the_served_profile; + crates/registry-breg/tests/consent_access.rs, a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths; + crates/registry-breg/tests/package_change_plan.rs, stored_field_ceiling_widens_compiled_access_on_successor_field_changes. */} + ## Accepted residuals The residuals are ordered by operator impact. @@ -923,7 +926,7 @@ Each lists the condition, the consequence, the mitigation, and the related matri A database restored to an earlier activation names that activation's package as active, so the successor applied after it applies again; it is the same transition. - Mitigation: guard the migration credential, pin `--expected-digest`, and check release provenance - in the deploy step. + in the deploy step. Review effective field changes under classification ceilings (obligation 23). - Related: `BREG-SEC-02`, `BREG-SEC-120`, `BREG-SEC-121`. {/* Evidence: crates/registry-breg/tests/postgres_package.rs, diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 5f688e05c8..dcedadc563 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- Record and read-path permissions can select stored fields with + `readableFields.upToClassification`. Consent-gated permissions require + explicit fields. + ## 0.49.0 - 2026-12-01 - BREAKING: `bregctl data export` JSONL uses `recordId` and `revisionId` in place of v0.48.0's `recordIdentifier` and `revisionIdentifier`. Migration: Update export file consumers for both keys. Finish an in-progress export with the matching v0.48.0 `bregctl`, serving runtime, and compiled package before upgrading, or start a fresh output and checkpoint pair after upgrading. Convert archived exports on a separate copy to preserve any checkpoint digest. From cea7026aa441aa9240956c4354e1535c25c19713 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:59:19 +0000 Subject: [PATCH 09/26] test(breg): bind consent ceiling guidance to apply controls Signed-off-by: Jeremi Joslin --- crates/registry-breg/tests/package_change_plan.rs | 14 ++++++++++++++ .../src/content/docs/configure/breg-consent.mdx | 2 ++ docs/site/src/content/docs/security/breg.mdx | 2 +- .../breg/contracts/security-invariant-matrix.yaml | 1 + .../breg/contracts/security-test-traceability.yaml | 1 + products/breg/scripts/test_validate_product.py | 2 +- products/breg/scripts/validate_product.py | 2 +- 7 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/registry-breg/tests/package_change_plan.rs b/crates/registry-breg/tests/package_change_plan.rs index a1fa365883..2be5fc3237 100644 --- a/crates/registry-breg/tests/package_change_plan.rs +++ b/crates/registry-breg/tests/package_change_plan.rs @@ -230,6 +230,20 @@ fn a_widened_list_or_read_path_ceiling_requires_review_before_apply() { ); let previous = compile(&before); let candidate = compile(&after); + let mut explicit = after.clone(); + let pointers = "/accessProfiles/reader/permissions/records/0"; + let readable_fields = if record == "record" { + format!("{pointers}/readableFields") + } else { + format!("{pointers}/readPaths/0/readableFields") + }; + *explicit.pointer_mut(&readable_fields).unwrap() = json!(["label"]); + let explicit = compile(&explicit); + let control = compiled_registry_change_set(&previous, &explicit, PRIOR_REVISION); + assert!( + change_set_to_applicable_migration_plan(&control).is_ok(), + "the same new field stays automatic when an explicit grant leaves the query unchanged: {query}" + ); let change_set = compiled_registry_change_set(&previous, &candidate, PRIOR_REVISION); assert!( change_set.changes.iter().any(|change| { diff --git a/docs/site/src/content/docs/configure/breg-consent.mdx b/docs/site/src/content/docs/configure/breg-consent.mdx index 660cf8248a..5d401e0004 100644 --- a/docs/site/src/content/docs/configure/breg-consent.mdx +++ b/docs/site/src/content/docs/configure/breg-consent.mdx @@ -340,6 +340,7 @@ Enforced, and refused at compilation where the shape is configuration: - Gated Record permissions are read-only (`breg.consent.require-read-only`). Writes, Actions, and Proposal lifecycle operations require separate authority. A gated profile may grant `get-review-context`: Record and Changes projections still apply current ordinary disclosure and consent to each snapshot, while Input projections require their own explicit context-field grant. +- Each gated permission needs explicit `readableFields` lists for its direct reads and read paths (`breg.consent.readable-fields-explicit-required`). - Spatial bbox queries are refused on gated permissions (`breg.consent.require-spatial-unsupported`), because they run under a separate database authority role that cannot evaluate consent. - Bulk data export is refused (`breg.consent.require-export-unsupported`), and so is exporting a gated profile as an Evidence source (`breg.consent.require-evidence-source-unsupported`). - A read path cannot reach a gated Record type through an intermediate or target step (`breg.consent.require-read-path-target`). @@ -367,6 +368,7 @@ Not enforced: The self Actions answer an unknown subject exactly like a subject the caller's link does not cover, so a self Action is not an existence oracle. {/* Evidence: crates/registry-breg/tests/consent_access.rs gated_permissions_are_read_only; + crates/registry-breg/tests/consent_access.rs a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths; crates/registry-breg/tests/consent_access.rs gated_permissions_refuse_spatial_queries; crates/registry-breg/tests/consent_access.rs gated_permissions_refuse_data_export; crates/registry-breg/tests/consent_access.rs breg.consent.require-read-path-target; diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 2f3d46a8f2..db85899f9b 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -867,7 +867,7 @@ and its ancestors. Deny other write access in every posture and group write acce As the migration credential holder, compare the effective fields of each affected direct grant and read path. Additions and reclassification can widen the grant under the same authored ceiling. Revisions use the current grant, so lowering a classification can expose earlier values to a profile with history access. - Keep the direct and path field grants for each consent scope in explicit lists, as the compiler requires. + For each permission with `requireConsent`, list the direct and path fields explicitly. [Compare the candidate with the active package](../../operate/breg-changes/#compare-the-candidate-with-the-active-package). {/* Evidence: crates/registry-breg/src/compiler.rs, resolve_readable_fields(), consent_ceiling_refusal(); crates/registry-breg/src/postgres/history_read.rs, readable_fields; diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index 7c25b6c224..f2fcaf4178 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -261,3 +261,4 @@ invariants: - {"id":"BREG-SEC-242","state":"enforced","targetWave":"W4","threat":"A claim, ask or decide preflight discloses answers and audits a disclosure nobody displayed.","enforcementPoint":"Single review-context read includes intrinsic answers only with include=answers and existing human review authority.","refusal":"Omit asks and their disclosure marker on preflight; audit actual displayed answers.","negativeId":"BREG-NEG-242","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"only_an_explicit_display_read_serves_and_audits_intrinsic_answers"}} - {"id":"BREG-SEC-243","state":"enforced","targetWave":"W4","threat":"Pruning value-free dedupe receipts causes a cursor reset to fetch or duplicate a retained ask.","enforcementPoint":"Maintenance uses the observation recovery window; feed processing checks the stored mirror before network I/O.","refusal":"Prune exact bounded receipt counts while preserving mirrored questions and answers and skipping stored observations.","negativeId":"BREG-NEG-243","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask"}} - {id: BREG-SEC-244, state: enforced, targetWave: W5, threat: "A signed hook is sent in plaintext to a non-loopback destination.", enforcementPoint: "BReg networkProfile decoding and shared destination policy construction before key resolution.", refusal: "Refuse non-loopback HTTP in both postures, including when the origin falls within allowedPrivateCidrs.", negativeId: BREG-NEG-244, negativeTest: {path: crates/registry-breg/tests/runtime_config.rs, name: event_destinations_refuse_non_loopback_plaintext_in_both_postures}} + - {id: BREG-SEC-245, state: enforced, targetWave: W5, threat: "A field addition or reclassification widens a gated permission under the same consent scope.", enforcementPoint: "The compiler checks direct and read-path readableFields on every composed permission with requireConsent.", refusal: "Refuse a classification ceiling with breg.consent.readable-fields-explicit-required. Require explicit field lists on the gated permission.", negativeId: BREG-NEG-245, negativeTest: {path: crates/registry-breg/tests/consent_access.rs, name: a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths}} diff --git a/products/breg/contracts/security-test-traceability.yaml b/products/breg/contracts/security-test-traceability.yaml index 93605c4fa7..e30f32be5a 100644 --- a/products/breg/contracts/security-test-traceability.yaml +++ b/products/breg/contracts/security-test-traceability.yaml @@ -302,3 +302,4 @@ traceability: - {"id":"BREG-SEC-242","state":"enforced","negativeId":"BREG-NEG-242","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"only_an_explicit_display_read_serves_and_audits_intrinsic_answers"}} - {"id":"BREG-SEC-243","state":"enforced","negativeId":"BREG-NEG-243","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask"}} - {id: BREG-SEC-244, state: enforced, negativeId: BREG-NEG-244, negativeTest: {path: crates/registry-breg/tests/runtime_config.rs, name: event_destinations_refuse_non_loopback_plaintext_in_both_postures}} + - {id: BREG-SEC-245, state: enforced, negativeId: BREG-NEG-245, negativeTest: {path: crates/registry-breg/tests/consent_access.rs, name: a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths}} diff --git a/products/breg/scripts/test_validate_product.py b/products/breg/scripts/test_validate_product.py index 7db7fbf2dc..f7610da015 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_and_negative_ids_are_closed(self) -> None: ) extension_rows = matrix["invariants"][24:] self.assertEqual( - [f"BREG-NEG-{index:02d}" for index in range(25, 245) if index not in {61, 62}], + [f"BREG-NEG-{index:02d}" for index in range(25, 246) 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 c8d8b8949d..0082f48510 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, 245) if index not in {61, 62}) +SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 246) 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"), From 1ee03268005f5ae561e11486f1fccf507336af2b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:54:03 +0000 Subject: [PATCH 10/26] test(breg): verify the native role facts writer against compiled grants Signed-off-by: Jeremi Joslin --- .../registry-bregctl/tests/identity_facts.rs | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/crates/registry-bregctl/tests/identity_facts.rs b/crates/registry-bregctl/tests/identity_facts.rs index 945e5ece46..b4f47b19fd 100644 --- a/crates/registry-bregctl/tests/identity_facts.rs +++ b/crates/registry-bregctl/tests/identity_facts.rs @@ -151,6 +151,177 @@ fn an_existing_output_is_refused_and_left_unchanged() { assert_eq!(std::fs::read_to_string(&output).unwrap(), "keep"); } +#[test] +fn native_inventory_report_matches_the_independently_compiled_external_views_project() { + use std::collections::{BTreeMap, BTreeSet}; + use std::fmt::Write as _; + use std::process::Command; + + use registry_breg::compiler::{compile_project, CompileProfile}; + use registry_breg::contract::parse_project_yaml; + use registry_thunderid_tooling::identity_facts::ClaimType; + use serde_json::{json, Value}; + use sha2::{Digest, Sha256}; + + // The archived witness used a copy of this project. Check the maintained + // source directly so the publisher and witness exercise the same input. + let project = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/breg/examples/external-views") + .canonicalize() + .unwrap(); + let authored = parse_project_yaml(&std::fs::read(project.join("registry.yaml")).unwrap()) + .expect("the donor is readable"); + let compiled = compile_project(&authored, &[], CompileProfile::Authoring) + .expect("the separate compiler produces the donor inventory"); + let scratch = tempfile::tempdir().unwrap(); + let runtime = runtime(scratch.path()); + edit_runtime( + &runtime, + "allowedClients: [generic-registry-client]", + "allowedClients: [officer, restricted, licensing-refresh, staff-app]", + ); + let first = scratch.path().join("first-facts.yaml"); + let second = scratch.path().join("second-facts.yaml"); + let native = |output: &Path| { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(["--format", "json", "generate", "identity-facts"]) + .arg(&project) + .arg("--runtime-config") + .arg(&runtime) + .arg("--output") + .arg(output) + .env_remove("REGISTRY_STACK_POSTURE") + .output() + .expect("native bregctl starts") + }; + let report = |output: &Path| { + let result = native(output); + assert!(result.status.success(), "native writer refused the fixture"); + assert!(result.stderr.is_empty(), "unexpected native writer stderr"); + let mut report: Value = registry_platform_canonical_json::parse_json_strict(&result.stdout) + .expect("the completed report is unique-member JSON"); + assert_eq!(report["kind"], "BRegCtlReport"); + assert_eq!( + report["apiVersion"], + registry_bregctl::CTL_REPORT_API_VERSION + ); + assert_eq!(report["command"], "generate"); + assert_eq!(report["status"], "complete"); + assert_eq!(report["ok"], true); + assert_eq!(report["revision"], compiled.revision()); + let bytes = std::fs::read(output).unwrap(); + let mut digest = String::new(); + for byte in Sha256::digest(&bytes) { + write!(digest, "{byte:02x}").unwrap(); + } + let artifact = &mut report["artifacts"][0]; + assert_eq!( + *artifact, + json!({ + "path": output, + "byteLength": bytes.len(), + "mediaType": "application/yaml", + "sha256": digest, + }) + ); + artifact["path"] = json!("identity-facts.yaml"); + (bytes, report) + }; + let (facts_bytes, first_report) = report(&first); + assert_eq!((facts_bytes.clone(), first_report.clone()), report(&second)); + let facts = read_facts(&first); + assert_eq!( + first_report["explanation"]["identityFacts"], + json!({"accessProfiles": facts.access_profiles.len(), "claims": facts.claims.len()}) + ); + + let mut expected = BTreeMap::new(); + for entity in compiled.entities().values() { + for profile in entity.access_profiles.values() { + let entry = expected.entry(profile.id.as_str()).or_insert_with(|| { + ( + profile.required_scopes.as_set(), + profile.required_purposes.as_set(), + profile.requester_clients.as_set(), + BTreeSet::new(), + ) + }); + entry.3.insert(profile.principal_claim.as_str()); + entry.3.extend( + profile + .row_boundaries + .iter() + .map(|boundary| boundary.claim.as_str()), + ); + } + } + assert_eq!(facts.access_profiles.len(), expected.len()); + for profile in &facts.access_profiles { + let (scopes, purposes, clients, required_claims) = &expected[profile.id.as_str()]; + assert_eq!( + profile.scopes.iter().cloned().collect::>(), + **scopes + ); + assert_eq!( + profile.purposes.iter().cloned().collect::>(), + **purposes + ); + assert_eq!( + profile + .requester_clients + .iter() + .flatten() + .cloned() + .collect::>(), + **clients, + ); + assert_eq!( + profile + .required_claims + .iter() + .map(String::as_str) + .collect::>(), + *required_claims, + ); + } + let authority = registry_breg::authority::authority_inventory(&compiled).unwrap(); + for (name, claim) in authority.direct_claims { + let kind = if claim.multi_value { + ClaimType::StringArray + } else { + ClaimType::String + }; + assert_eq!(facts.claims[&name], kind); + } + + let schema = serde_json::from_str(include_str!( + "../../../products/platform/schemas/identity-facts.schema.json" + )) + .unwrap(); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .unwrap(); + let facts_value = serde_json::to_value(facts).unwrap(); + assert!(validator.is_valid(&facts_value)); + let mut malformed = facts_value; + malformed["unrecognized"] = json!("synthetic-refusal"); + assert!(!validator.is_valid(&malformed)); + assert!(registry_thunderid_tooling::identity_facts::read( + "malformed", + &serde_json::to_vec(&malformed).unwrap(), + ) + .is_err()); + let refusal = native(&first); + assert_eq!(refusal.status.code(), Some(1)); + let refusal = registry_platform_canonical_json::parse_json_strict(&refusal.stdout).unwrap(); + assert_eq!( + refusal["diagnostics"][0]["code"], + "identity-facts.output-exists" + ); + assert_eq!(std::fs::read(first).unwrap(), facts_bytes); +} + #[test] fn an_unrestricted_runtime_states_unrestricted_admission() { let scratch = tempfile::tempdir().unwrap(); From 345516f92a7c7245db428a424820a7014cb6d2ab Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:33:35 +0000 Subject: [PATCH 11/26] feat(bregctl): publish completed identity facts report schema Signed-off-by: Jeremi Joslin --- crates/registry-bregctl/src/check.rs | 1 + crates/registry-bregctl/src/identity_facts.rs | 8 +- crates/registry-bregctl/src/lib.rs | 6 +- crates/registry-bregctl/src/tool_schema.rs | 134 +++++++- .../registry-bregctl/tests/identity_facts.rs | 14 + crates/registry-bregctl/tests/tool_schema.rs | 65 +++- .../formats/identity-facts-report.json | 44 +++ .../tools/ctl-report.v1alpha1.schema.json | 319 ++++++++++++++++++ products/platform/config-formats.yaml | 11 +- 9 files changed, 581 insertions(+), 21 deletions(-) create mode 100644 products/breg/examples/formats/identity-facts-report.json create mode 100644 products/breg/generated/tools/ctl-report.v1alpha1.schema.json diff --git a/crates/registry-bregctl/src/check.rs b/crates/registry-bregctl/src/check.rs index a0386cd661..b7802f0f00 100644 --- a/crates/registry-bregctl/src/check.rs +++ b/crates/registry-bregctl/src/check.rs @@ -100,6 +100,7 @@ pub(super) struct RankedDiagnostic<'a> { } #[derive(Clone, Copy, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] pub(super) enum FindingRank { WidensAccess, diff --git a/crates/registry-bregctl/src/identity_facts.rs b/crates/registry-bregctl/src/identity_facts.rs index e53df5460b..d359a0f2ad 100644 --- a/crates/registry-bregctl/src/identity_facts.rs +++ b/crates/registry-bregctl/src/identity_facts.rs @@ -565,13 +565,15 @@ fn refuse_unissuable_claim( ))) } -/// Write `facts` to a new file. An existing file is never replaced. -pub(crate) fn write(facts: &IdentityFacts, output: &Path) -> Result<(), FactsError> { +/// Write `facts` to a new file and return the exact YAML written. +/// An existing file is never replaced. +pub(crate) fn write(facts: &IdentityFacts, output: &Path) -> Result { let yaml = facts.to_yaml().map_err(|_| FactsError::Encode)?; let mut file = OpenOptions::new() .write(true) .create_new(true) .open(output) .map_err(FactsError::Write)?; - file.write_all(yaml.as_bytes()).map_err(FactsError::Write) + file.write_all(yaml.as_bytes()).map_err(FactsError::Write)?; + Ok(yaml) } diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 05cb3335ea..064bcde286 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -1965,6 +1965,7 @@ enum ExplainSubject { } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "snake_case")] enum ProfileArg { #[default] @@ -2224,6 +2225,7 @@ where } #[derive(Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] struct RankedProjectFinding<'a> { #[serde(flatten)] diagnostic: &'a registry_platform_yaml::Diagnostic, @@ -10035,7 +10037,7 @@ fn generate_identity_facts( ) })?; let facts = stated.facts; - identity_facts::write(&facts, &args.output).map_err(|error| { + let yaml = identity_facts::write(&facts, &args.output).map_err(|error| { fail( error.code(), &error.to_string(), @@ -10057,7 +10059,7 @@ fn generate_identity_facts( artifacts: vec![artifact_report( &args.output.display().to_string(), "application/yaml", - facts.to_yaml().unwrap_or_default().as_bytes(), + yaml.as_bytes(), )], explanation: Some(json!({ "identityFacts": { diff --git a/crates/registry-bregctl/src/tool_schema.rs b/crates/registry-bregctl/src/tool_schema.rs index 46c675b886..32a22191e6 100644 --- a/crates/registry-bregctl/src/tool_schema.rs +++ b/crates/registry-bregctl/src/tool_schema.rs @@ -1,22 +1,34 @@ // SPDX-License-Identifier: Apache-2.0 -//! Generated JSON Schemas for the tool files `bregctl` reads. +//! Generated JSON Schemas for BReg tooling contracts. //! -//! Each schema is derived from the types its reader decodes and published -//! with the header the reader checks before decoding them. The committed -//! copies under `products/breg/generated/tools` come from the `tool-schema` -//! example; `products/breg/scripts/check-tool-schemas.sh` fails when they -//! differ from what the reader types generate. +//! Each schema publishes the version and kind a reader checks along with the +//! members it accepts. The committed copies under `products/breg/generated/tools` +//! come from the `tool-schema` example and are checked by +//! `products/breg/scripts/check-tool-schemas.sh`. use std::collections::BTreeMap; use registry_breg::{fixtures, migration_plan}; -use registry_platform_yaml::{EnvelopeRule, FormatSpec, VersionStatus}; +use registry_platform_config::identity_facts::{MAXIMUM_CLAIMS, MAXIMUM_PROFILES}; +use registry_platform_yaml::{ApiVersion, EnvelopeRule, FormatSpec, VersionStatus}; +use schemars::generate::SchemaSettings; use serde_json::{json, Map, Value}; -use crate::{examples, init_from_model, test_lifecycle}; +use crate::{ + examples, init_from_model, test_lifecycle, ProfileArg, RankedProjectFinding, + CTL_REPORT_API_VERSION, CTL_REPORT_KIND, +}; const SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema"; const SCHEMA_ID_BASE: &str = "https://id.registrystack.org/schemas/"; +const CTL_REPORT_FORMAT: FormatSpec<'static> = FormatSpec { + kind: CTL_REPORT_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(CTL_REPORT_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; /// One published tool schema. struct Tool { @@ -28,7 +40,7 @@ struct Tool { members: fn() -> schemars::Schema, } -fn tools() -> [Tool; 6] { +fn tools() -> [Tool; 7] { [ Tool { namespace: "breg", @@ -72,9 +84,108 @@ fn tools() -> [Tool; 6] { spec: migration_plan::MIGRATION_DESCRIPTOR_FORMAT, members: migration_plan::migration_descriptor_schema, }, + Tool { + namespace: "breg", + format: "ctl-report", + title: "Completed BReg identity facts command report", + spec: CTL_REPORT_FORMAT, + members: completed_identity_facts_report_schema, + }, ] } +fn completed_identity_facts_report_schema() -> schemars::Schema { + let mut generator = SchemaSettings::draft2020_12() + .for_serialize() + .into_generator(); + let profile = generator.subschema_for::(); + let diagnostic = generator.subschema_for::>(); + let definitions = generator.take_definitions(true); + let mut schema = json!({ + "type": "object", + "additionalProperties": false, + "description": "The completed report from bregctl generate identity-facts. Validation describes the report structure; its artifact metadata does not establish the path or contents of a file.", + "required": ["ok", "command", "status", "version", "profile", "revision", "posture", "diagnostics", "artifacts", "explanation"], + "properties": { + "ok": {"type": "boolean", "const": true}, + "command": {"type": "string", "const": "generate"}, + "status": {"type": "string", "const": registry_cli_report::Status::Complete.as_str()}, + "version": {"type": "string", "minLength": 1}, + "profile": profile, + "revision": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$", "minLength": 71, "maxLength": 71}, + "posture": { + "type": "object", "additionalProperties": false, + "required": ["value", "source"], + "properties": { + "value": {"type": "string", "enum": ["production", "development"]}, + "source": {"type": "string", "enum": ["default", "environment", "flag"]} + } + }, + "diagnostics": {"type": "array", "items": diagnostic}, + "artifacts": { + "type": "array", "minItems": 1, "maxItems": 1, + "items": { + "type": "object", "additionalProperties": false, + "required": ["path", "mediaType", "byteLength", "sha256"], + "properties": { + "path": {"type": "string", "minLength": 1}, + "mediaType": {"type": "string", "const": "application/yaml"}, + "byteLength": {"type": "integer", "minimum": 1, "maximum": registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$", "minLength": 64, "maxLength": 64} + } + } + }, + "explanation": { + "type": "object", "additionalProperties": false, + "required": ["identityFacts"], + "properties": { + "identityFacts": { + "type": "object", "additionalProperties": false, + "required": ["accessProfiles", "claims"], + "properties": { + "accessProfiles": {"type": "integer", "minimum": 0, "maximum": MAXIMUM_PROFILES}, + "claims": {"type": "integer", "minimum": 0, "maximum": MAXIMUM_CLAIMS} + } + } + } + }, + "nextSteps": {"type": "array", "minItems": 1, "items": {"type": "string"}} + }, + "$defs": definitions + }); + close_diagnostic_objects(&mut schema["$defs"]); + // Positioned findings point into a bounded source or runtime document. + // Coordinates start at one and may point just past its last character. + let maximum_coordinate = registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES + 1; + for definition in ["Source", "Related"] { + let properties = &mut schema["$defs"][definition]["properties"]; + for name in ["line", "column"] { + let coordinate = properties + .get_mut(name) + .expect("diagnostic source defines this coordinate"); + coordinate["minimum"] = json!(1); + coordinate["maximum"] = json!(maximum_coordinate); + } + } + schemars::Schema::try_from(schema).expect("the report schema is an object") +} + +/// Saved reports require exact members even for the shared diagnostic types. +fn close_diagnostic_objects(schema: &mut Value) { + match schema { + Value::Object(object) => { + if object.contains_key("properties") { + object.insert("additionalProperties".to_owned(), Value::Bool(false)); + } + for value in object.values_mut() { + close_diagnostic_objects(value); + } + } + Value::Array(values) => values.iter_mut().for_each(close_diagnostic_objects), + _ => {} + } +} + /// Every tool schema under its committed file name, /// `..schema.json`. pub fn documents() -> Result, serde_json::Error> { @@ -112,9 +223,8 @@ fn current_api_version(spec: &FormatSpec<'static>) -> &'static str { } } -/// The reader checks `apiVersion` and `kind` and removes them before it -/// decodes the members, so the derived schema lacks them; the published one -/// requires both, each with the one value this release reads. +/// Require the envelope in the published schema. The member definition covers +/// the body that remains after the reader checks the version and kind. fn with_header(mut derived: Value, api_version: &str, kind: &str) -> Value { let Value::Object(object) = &mut derived else { unreachable!("a reader type derives an object schema") diff --git a/crates/registry-bregctl/tests/identity_facts.rs b/crates/registry-bregctl/tests/identity_facts.rs index b4f47b19fd..05ec8c6f38 100644 --- a/crates/registry-bregctl/tests/identity_facts.rs +++ b/crates/registry-bregctl/tests/identity_facts.rs @@ -209,6 +209,20 @@ fn native_inventory_report_matches_the_independently_compiled_external_views_pro assert_eq!(report["status"], "complete"); assert_eq!(report["ok"], true); assert_eq!(report["revision"], compiled.revision()); + #[cfg(feature = "schema")] + { + let schemas = registry_bregctl::tool_schema::documents().unwrap(); + let schema = serde_json::from_str(&schemas["ctl-report.v1alpha1.schema.json"]) + .expect("generated report schema is JSON"); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .expect("generated report schema compiles"); + assert!( + validator.is_valid(&report), + "native report violates its schema" + ); + } let bytes = std::fs::read(output).unwrap(); let mut digest = String::new(); for byte in Sha256::digest(&bytes) { diff --git a/crates/registry-bregctl/tests/tool_schema.rs b/crates/registry-bregctl/tests/tool_schema.rs index 365c9b3737..d4f6bbc454 100644 --- a/crates/registry-bregctl/tests/tool_schema.rs +++ b/crates/registry-bregctl/tests/tool_schema.rs @@ -36,6 +36,10 @@ const EXAMPLES: &[(&str, &str)] = &[ "products/breg/examples/formats/retire-legacy-field-binding.json", ), ("migration-descriptor.v1alpha1.schema.json", DESCRIPTOR), + ( + "ctl-report.v1alpha1.schema.json", + "products/breg/examples/formats/identity-facts-report.json", + ), ]; const DESCRIPTOR: &str = "products/breg/examples/formats/reviewed-migrations/modules/asset-site-placement-core/migrations/read-maintenance-note/descriptor.json"; @@ -79,6 +83,64 @@ fn every_committed_example_satisfies_its_generated_schema() { } } +#[test] +fn identity_facts_report_schema_refuses_other_reports_and_undeclared_members() { + let documents = documents().expect("the tool schemas generate"); + let schema = compile(&documents["ctl-report.v1alpha1.schema.json"]); + let valid = example("products/breg/examples/formats/identity-facts-report.json"); + for (path, refused) in [ + ("/kind", json!("PlatformIdentityFacts")), + ("/command", json!("check")), + ("/status", json!("domain-refusal")), + ("/ok", json!(false)), + ("/artifacts", json!([])), + ("/artifacts/0/byteLength", json!(-1)), + ("/artifacts/0/sha256", json!("unexpected")), + ("/explanation/identityFacts/accessProfiles", json!("3")), + ("/explanation/identityFacts/accessProfiles", json!(65)), + ( + "/diagnostics/0/source", + json!({"file": "registry.yaml", "extra": true}), + ), + ] { + let mut changed = valid.clone(); + *changed + .pointer_mut(path) + .expect("member is present in fixture") = refused; + assert!(!schema.is_valid(&changed), "accepted a change at {path}"); + } + let mut extra = valid.clone(); + extra["explanation"]["identityFacts"]["unrecognised"] = json!(true); + assert!(!schema.is_valid(&extra)); + let mut missing = valid; + missing.as_object_mut().unwrap().remove("explanation"); + assert!(!schema.is_valid(&missing)); +} + +#[test] +fn identity_facts_report_schema_bounds_document_coordinates() { + let documents = documents().expect("the tool schemas generate"); + let schema = compile(&documents["ctl-report.v1alpha1.schema.json"]); + let mut report = example("products/breg/examples/formats/identity-facts-report.json"); + report["diagnostics"][0]["related"] = json!([{ + "file": "registry.yaml", "path": "", "message": "Check the project", "line": 1, "column": 1 + }]); + let maximum = registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES + 1; + for path in [ + "/diagnostics/0/source/line", + "/diagnostics/0/source/column", + "/diagnostics/0/related/0/line", + "/diagnostics/0/related/0/column", + ] { + for (coordinate, admitted) in [(0, false), (1, true), (maximum, true), (maximum + 1, false)] + { + let mut changed = report.clone(); + *changed.pointer_mut(path).expect("coordinate exists") = json!(coordinate); + assert_eq!(schema.is_valid(&changed), admitted, "{path}: {coordinate}"); + } + } +} + #[test] fn example_scenario_schema_uses_bounded_display_text() { let documents = documents().expect("the tool schemas generate"); @@ -382,8 +444,9 @@ fn a_wrong_header_a_missing_header_and_an_explicit_null_are_refused() { } /// The identifiers the catalog records, in file-name order. -const IDENTIFIERS: [&str; 6] = [ +const IDENTIFIERS: [&str; 7] = [ "https://id.registrystack.org/schemas/breg/backup-binding/backup-binding.v1alpha1.schema.json", + "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", "https://id.registrystack.org/schemas/breg/example-scenarios/example-scenarios.v1alpha1.schema.json", "https://id.registrystack.org/schemas/breg/journeys/journeys.v1.schema.json", "https://id.registrystack.org/schemas/breg/migration-descriptor/migration-descriptor.v1alpha1.schema.json", diff --git a/products/breg/examples/formats/identity-facts-report.json b/products/breg/examples/formats/identity-facts-report.json new file mode 100644 index 0000000000..d9dd14156c --- /dev/null +++ b/products/breg/examples/formats/identity-facts-report.json @@ -0,0 +1,44 @@ +{ + "ok": true, + "command": "generate", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + "kind": "BRegCtlReport", + "version": "0.49.0", + "artifacts": [ + { + "byteLength": 802, + "mediaType": "application/yaml", + "path": "identity-facts.yaml", + "sha256": "d6061ec53e023e24401cbff448cfea3f900c78747956ec97265b6b3da64a4f62" + } + ], + "explanation": { + "identityFacts": { + "accessProfiles": 3, + "claims": 4 + } + }, + "profile": "authoring", + "revision": "sha256:a850cc821c54ce783ab57c4d271edb7e8f8d2fc16fc8dca172bc6320f137a385", + "posture": { + "value": "production", + "source": "default" + }, + "diagnostics": [ + { + "artifact": "BRegModule", + "code": "breg.record-type.stored-field-unfillable", + "message": "this optional stored field has no writable access grant, fixed Action set, function-plan write, or import that can supply a value; add the field to one of those writers, or remove the field", + "path": "/extendRecordTypes/record/fields/0", + "rank": "hygiene", + "severity": "warning", + "source": { + "column": 9, + "file": "modules/record-notes/module.yaml", + "line": 19 + }, + "suggestedAction": "Add the field to a grant's writableFields, a fixed Action set, a function plan write, or an import permission, or remove the field." + } + ] +} diff --git a/products/breg/generated/tools/ctl-report.v1alpha1.schema.json b/products/breg/generated/tools/ctl-report.v1alpha1.schema.json new file mode 100644 index 0000000000..5642d5ce12 --- /dev/null +++ b/products/breg/generated/tools/ctl-report.v1alpha1.schema.json @@ -0,0 +1,319 @@ +{ + "$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" + }, + "FindingRank": { + "enum": [ + "widens-access", + "performance", + "hygiene" + ], + "type": "string" + }, + "ProfileArg": { + "enum": [ + "authoring", + "production" + ], + "type": "string" + }, + "RankedProjectFinding": { + "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" + }, + "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" + }, + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "RFC 6901 JSON pointer into the document as written; `\"\"` is the root.", + "type": "string" + }, + "rank": { + "$ref": "#/$defs/FindingRank" + }, + "related": { + "items": { + "$ref": "#/$defs/Related" + }, + "type": "array" + }, + "scope": { + "$ref": "#/$defs/CheckScope", + "description": "Project-relative identity copied into a check acceptance." + }, + "severity": { + "$ref": "#/$defs/Severity" + }, + "source": { + "$ref": "#/$defs/Source" + }, + "suggestedAction": { + "type": "string" + } + }, + "required": [ + "severity", + "code", + "path", + "message", + "suggestedAction", + "rank" + ], + "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": 1048577, + "minimum": 1, + "type": "integer" + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + }, + "message": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "file", + "path", + "message" + ], + "type": "object" + }, + "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": 1048577, + "minimum": 1, + "type": "integer" + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "file" + ], + "type": "object" + } + }, + "$id": "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The completed report from bregctl generate identity-facts. Validation describes the report structure; its artifact metadata does not establish the path or contents of a file.", + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + "description": "The format and version this file is written in.", + "type": "string" + }, + "artifacts": { + "items": { + "additionalProperties": false, + "properties": { + "byteLength": { + "maximum": 1048576, + "minimum": 1, + "type": "integer" + }, + "mediaType": { + "const": "application/yaml", + "type": "string" + }, + "path": { + "minLength": 1, + "type": "string" + }, + "sha256": { + "maxLength": 64, + "minLength": 64, + "pattern": "^[0-9a-f]{64}$", + "type": "string" + } + }, + "required": [ + "path", + "mediaType", + "byteLength", + "sha256" + ], + "type": "object" + }, + "maxItems": 1, + "minItems": 1, + "type": "array" + }, + "command": { + "const": "generate", + "type": "string" + }, + "diagnostics": { + "items": { + "$ref": "#/$defs/RankedProjectFinding" + }, + "type": "array" + }, + "explanation": { + "additionalProperties": false, + "properties": { + "identityFacts": { + "additionalProperties": false, + "properties": { + "accessProfiles": { + "maximum": 64, + "minimum": 0, + "type": "integer" + }, + "claims": { + "maximum": 64, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "accessProfiles", + "claims" + ], + "type": "object" + } + }, + "required": [ + "identityFacts" + ], + "type": "object" + }, + "kind": { + "const": "BRegCtlReport", + "description": "The kind of document this file is.", + "type": "string" + }, + "nextSteps": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "ok": { + "const": true, + "type": "boolean" + }, + "posture": { + "additionalProperties": false, + "properties": { + "source": { + "enum": [ + "default", + "environment", + "flag" + ], + "type": "string" + }, + "value": { + "enum": [ + "production", + "development" + ], + "type": "string" + } + }, + "required": [ + "value", + "source" + ], + "type": "object" + }, + "profile": { + "$ref": "#/$defs/ProfileArg" + }, + "revision": { + "maxLength": 71, + "minLength": 71, + "pattern": "^sha256:[0-9a-f]{64}$", + "type": "string" + }, + "status": { + "const": "complete", + "type": "string" + }, + "version": { + "minLength": 1, + "type": "string" + } + }, + "required": [ + "apiVersion", + "kind", + "ok", + "command", + "status", + "version", + "profile", + "revision", + "posture", + "diagnostics", + "artifacts", + "explanation" + ], + "title": "Completed BReg identity facts command report", + "type": "object" +} diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index c507fc67da..dec8050c23 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -1400,7 +1400,7 @@ formats: restrictingMembers: [] - id: breg/ctl-report product: breg - title: bregctl --format json report + title: Completed bregctl generate identity-facts JSON report files: [] syntax: json audience: generated @@ -1414,13 +1414,18 @@ formats: target: apiVersion: id.registrystack.org/formats/breg/ctl-report/v1alpha1 kind: BRegCtlReport - schema: none + schema: + path: products/breg/generated/tools/ctl-report.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-bregctl --features schema --example tool-schema -- --output products/breg/generated/tools + driftCheck: products/breg/scripts/check-tool-schemas.sh reader: none emittedBy: file: crates/registry-bregctl/src/lib.rs symbol: write_ctl_report check: none - example: products/breg/examples/formats/ctl-report.json + example: products/breg/examples/formats/identity-facts-report.json conformance: none securityMembers: [] restrictingMembers: [] From 5b528c04eb8fe0f7482776c758e37e6669b933ad Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 18:52:06 +0000 Subject: [PATCH 12/26] fix(identity): validate product references in unused roles Signed-off-by: Jeremi Joslin --- .../src/service_roles.rs | 28 +++++++++- .../src/service_roles/tests.rs | 37 +++++++++++++ crates/registry-rstack/tests/dev_run.rs | 37 +++++++++++++ .../src/identity_check.rs | 55 +++++++++++++++++-- .../run-a-project-with-rstack-dev.mdx | 10 +++- 5 files changed, 160 insertions(+), 7 deletions(-) diff --git a/crates/registry-platform-config/src/service_roles.rs b/crates/registry-platform-config/src/service_roles.rs index 507da8e82e..a7063aa0e1 100644 --- a/crates/registry-platform-config/src/service_roles.rs +++ b/crates/registry-platform-config/src/service_roles.rs @@ -123,8 +123,8 @@ impl RoleDocument { Ok(Self { roles, document }) } - /// Validate profiles against the products with supplied facts. Assigned roles - /// also require facts for every product they reference. + /// Validate every product reference and check profiles wherever facts are supplied. + /// Assigned roles also require facts for each product they reference. pub fn validate_references( &self, assigned: &BTreeSet<&str>, @@ -141,6 +141,11 @@ impl RoleDocument { "The role names a product with no identity facts.", "Supply identity facts for this product or change the role in service.yaml.", )), + None if !known_role_product(product) => Some(( + "identity.deployment.unknown-product", + "The role names an unknown product.", + "Use a recognized product or supply its identity facts to the hosted check.", + )), Some(false) => Some(( "identity.deployment.unknown-profile", "The product declares no identity facts for this access profile.", @@ -173,6 +178,25 @@ impl RoleDocument { } } +/// Native service role products remain known when a check loads only some facts. +/// A supplied facts document can also identify an external product. +fn known_role_product(product: &str) -> bool { + matches!( + product, + "adapter" + | "breg" + | "breg-mcp" + | "casework" + | "coordinator" + | "discovery" + | "documents" + | "evidence" + | "messaging" + | "render" + | "scheduling" + ) +} + /// Validate the roles section of a service document read by a caller. pub fn roles_from_document(document: &Document) -> Result { if document.root().get("roles").is_none() { diff --git a/crates/registry-platform-config/src/service_roles/tests.rs b/crates/registry-platform-config/src/service_roles/tests.rs index 72cf796140..ce4e71a660 100644 --- a/crates/registry-platform-config/src/service_roles/tests.rs +++ b/crates/registry-platform-config/src/service_roles/tests.rs @@ -79,6 +79,43 @@ fn validates_profiles_for_supplied_products_and_requires_facts_for_assigned_role assert_eq!(diagnostic.path, "/roles/reader/accessProfiles/breg"); } +#[test] +fn an_unassigned_role_requires_a_known_product_or_supplied_facts() { + let authored = |product| { + format!( + "{HEADER}roles:\n unused:\n actorKind: human\n accessProfiles:\n {product}: [read]\n" + ) + }; + let assigned = BTreeSet::new(); + let known = authored("messaging"); + decode_role_document("service.yaml", known.as_bytes()) + .unwrap() + .validate_references(&assigned, |_, _| None) + .unwrap(); + + let external = authored("external-registry"); + let document = decode_role_document("service.yaml", external.as_bytes()).unwrap(); + let refused = document + .validate_references(&assigned, |_, _| None) + .unwrap_err(); + let [diagnostic] = refused.diagnostics() else { + panic!("expected one service reference diagnostic: {refused}"); + }; + assert_eq!(diagnostic.code, "identity.deployment.unknown-product"); + assert_eq!( + diagnostic.path, + "/roles/unused/accessProfiles/external-registry" + ); + let source = diagnostic.source.as_ref().unwrap(); + assert_eq!(source.file, "service.yaml"); + assert_eq!((source.line, source.column), (Some(7), Some(7))); + document + .validate_references(&assigned, |product, profile| { + (product == "external-registry").then_some(profile == "read") + }) + .unwrap(); +} + #[test] fn rejects_empty_duplicate_and_authority_bearing_role_members() { for body in [ diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index ad381c9433..7ee71e429c 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -2153,6 +2153,43 @@ fn semantic_diagnostic_escapes_authored_mapping_keys_only_in_its_pointer() { assert!(!state.exists()); } +#[test] +fn dev_check_reports_unknown_products_in_unassigned_service_roles() { + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + semantic_project(scratch.path(), "breg", ""); + for (product, code) in [("casework", 0), ("unknown-role-product", 1)] { + service( + scratch.path(), + &format!( + " operator: {{actorKind: service, accessProfiles: {{breg: [operator]}}}}\n unused:\n actorKind: human\n accessProfiles:\n {product}: [private-profile-marker]\n" + ), + ); + let checked = check(scratch.path(), &state, true); + assert_eq!(checked.status.code(), Some(code), "{checked:?}"); + let report: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap(); + if code == 1 { + let [diagnostic] = report["diagnostics"].as_array().unwrap().as_slice() else { + panic!("expected one service reference diagnostic: {report}"); + }; + assert_eq!(diagnostic["code"], "identity.deployment.unknown-product"); + assert_eq!(diagnostic["artifact"], "RStackService"); + assert_eq!( + diagnostic["path"], + "/roles/unused/accessProfiles/unknown-role-product" + ); + assert_eq!( + diagnostic["source"]["file"], + utf8(&scratch.path().join("service.yaml")) + ); + assert_eq!(diagnostic["source"]["line"], 8); + assert_eq!(diagnostic["source"]["column"], 7); + assert!(!diagnostic.to_string().contains("private-profile-marker")); + } + assert!(!state.exists()); + } +} + #[test] fn start_reports_an_actionable_value_free_role_for_an_unstarted_product() { let scratch = tempfile::tempdir().unwrap(); diff --git a/crates/registry-thunderid-tooling/src/identity_check.rs b/crates/registry-thunderid-tooling/src/identity_check.rs index 340bcc214f..951a725a0f 100644 --- a/crates/registry-thunderid-tooling/src/identity_check.rs +++ b/crates/registry-thunderid-tooling/src/identity_check.rs @@ -10,7 +10,10 @@ //! the cross-file rules too (grants against admitted clients, claim types, //! issuer), writing nothing. -use std::path::{Path, PathBuf}; +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, +}; use registry_platform_yaml::{Diagnostic, Expect, Reader, Report, Severity, Source}; @@ -64,16 +67,19 @@ fn check_bytes(file: &str, bytes: &[u8], path: &Path, facts: &[PathBuf]) -> Repo bytes: &service_bytes, }; if facts.is_empty() { - let roles = match registry_platform_config::service_roles::decode_service_roles( + let service = match registry_platform_config::service_roles::decode_role_document( service.label, service.bytes, ) { - Ok(roles) => roles, + Ok(service) => service, Err(refused) => { report.extend(refused); return report; } }; + if let Err(refused) = service.validate_references(&BTreeSet::new(), |_, _| None) { + report.extend(refused); + } for (group, principals) in [ ( "clients", @@ -110,7 +116,7 @@ fn check_bytes(file: &str, bytes: &[u8], path: &Path, facts: &[PathBuf]) -> Repo ] { for (index, ids) in principals.into_iter().enumerate() { if let Err(error) = - registry_platform_config::service_roles::assign_roles(&roles, ids) + registry_platform_config::service_roles::assign_roles(&service.roles, ids) { report.push(document.diagnostic_at_value( Severity::Error, @@ -323,6 +329,47 @@ mod tests { ); } + #[test] + fn hosted_check_reports_unknown_products_in_unassigned_service_roles() { + for facts in [Vec::new(), vec![example("identity-facts.yaml")]] { + let dir = deployment_dir(|text| text); + let deployment = dir.path().join("deployment.yaml"); + let service = dir.path().join("service.yaml"); + let original = std::fs::read_to_string(&service).unwrap(); + let unused = |product| { + format!( + "{original} unused:\n actorKind: human\n accessProfiles:\n {product}: [private-profile-marker]\n" + ) + }; + std::fs::write(&service, unused("messaging")).unwrap(); + let checked = check_file(&deployment, &facts); + assert!(!checked.report.has_errors(), "{}", checked.report); + + std::fs::write(&service, unused("unknown-role-product")).unwrap(); + let checked = check_file(&deployment, &facts); + let [diagnostic] = checked.report.diagnostics() else { + panic!( + "expected one service reference diagnostic: {}", + checked.report + ); + }; + assert_eq!(diagnostic.code, "identity.deployment.unknown-product"); + assert_eq!(diagnostic.artifact.as_deref(), Some("RStackService")); + assert_eq!( + diagnostic.path, + "/roles/unused/accessProfiles/unknown-role-product" + ); + let source = diagnostic.source.as_ref().unwrap(); + assert_eq!(source.file, service.to_string_lossy()); + assert_eq!(source.line, Some(original.lines().count() + 4)); + assert_eq!(source.column, Some(7)); + assert!(!checked + .report + .render_human() + .contains("private-profile-marker")); + } + } + #[test] fn a_facts_document_is_checked_beyond_its_types() { let dir = tempfile::tempdir().unwrap(); diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index b9bd5b2f13..7d779b321f 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -634,7 +634,15 @@ When each step names its actor and the run uses its own issuer, the rehearsal ob The run obtains the normal schema-test receipt before packaging. A role may refer to a profile that grants only proposal permissions. -Dev runs and hosted identity generation check all role references for products whose identity facts they load, including references in unassigned roles. Every assigned role must have identity facts for each product it names. Invalid references point to the corresponding `accessProfiles` entry in `service.yaml`. +Dev runs and hosted identity checks validate product references even in unassigned roles. +A known product can appear in an unassigned role when its identity facts are outside the current run. +The checks validate access profiles wherever they load identity facts. +Every assigned role must have facts for each product it names when you run a full identity check. +An invalid reference points to its `accessProfiles` entry in `service.yaml`. + +{/* Evidence: crates/registry-platform-config/src/service_roles.rs, RoleDocument::validate_references(); + crates/registry-rstack/tests/dev_run.rs, dev_check_reports_unknown_products_in_unassigned_service_roles; + crates/registry-thunderid-tooling/src/identity_check.rs, hosted_check_reports_unknown_products_in_unassigned_service_roles. */} When migrating an existing plan, move profile references to `service.yaml` and replace each person's `grants` with their role IDs. Remove the per-person scopes and actor kind. From d96f215a2c902577e005860fb71f22dd58beec77 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:03:24 +0000 Subject: [PATCH 13/26] fix(identity): point role diagnostics to their authoring inputs Signed-off-by: Jeremi Joslin --- .../src/service_roles.rs | 70 +++++++++++++------ crates/registry-rstack-dev/src/roles.rs | 2 +- crates/registry-rstack/tests/dev_run.rs | 13 +++- .../src/identity_check.rs | 4 ++ .../run-a-project-with-rstack-dev.mdx | 7 +- 5 files changed, 71 insertions(+), 25 deletions(-) diff --git a/crates/registry-platform-config/src/service_roles.rs b/crates/registry-platform-config/src/service_roles.rs index a7063aa0e1..6a55da1787 100644 --- a/crates/registry-platform-config/src/service_roles.rs +++ b/crates/registry-platform-config/src/service_roles.rs @@ -129,30 +129,60 @@ impl RoleDocument { &self, assigned: &BTreeSet<&str>, has_profile: impl Fn(&str, &str) -> Option, + ) -> Result<(), Report> { + self.validate_references_with_actions( + assigned, + has_profile, + "Supply identity facts for this product or change the role in service.yaml.", + "Use a recognized product or supply its identity facts to the hosted check.", + ) + } + + /// Apply the same role validation with remedies for a development plan. + pub fn validate_development_references( + &self, + assigned: &BTreeSet<&str>, + has_profile: impl Fn(&str, &str) -> Option, + ) -> Result<(), Report> { + self.validate_references_with_actions( + assigned, + has_profile, + "List this product in dev.yaml if supported, or change the role in service.yaml.", + "Use a recognized product key in service.yaml or remove this reference.", + ) + } + + fn validate_references_with_actions( + &self, + assigned: &BTreeSet<&str>, + has_profile: impl Fn(&str, &str) -> Option, + missing_facts_action: &str, + unknown_product_action: &str, ) -> Result<(), Report> { let mut findings = Vec::new(); for (role_id, role) in &self.roles { for (product, profiles) in &role.access_profiles { - let Some((code, message, action)) = profiles - .iter() - .find_map(|profile| match has_profile(product, profile) { - None if assigned.contains(role_id.as_str()) => Some(( - "identity.deployment.unknown-product", - "The role names a product with no identity facts.", - "Supply identity facts for this product or change the role in service.yaml.", - )), - None if !known_role_product(product) => Some(( - "identity.deployment.unknown-product", - "The role names an unknown product.", - "Use a recognized product or supply its identity facts to the hosted check.", - )), - Some(false) => Some(( - "identity.deployment.unknown-profile", - "The product declares no identity facts for this access profile.", - "Use a profile declared in the product's identity facts.", - )), - _ => None, - }) + let Some((code, message, action)) = + profiles + .iter() + .find_map(|profile| match has_profile(product, profile) { + None if assigned.contains(role_id.as_str()) => Some(( + "identity.deployment.unknown-product", + "The role names a product with no identity facts.", + missing_facts_action, + )), + None if !known_role_product(product) => Some(( + "identity.deployment.unknown-product", + "The role names an unknown product.", + unknown_product_action, + )), + Some(false) => Some(( + "identity.deployment.unknown-profile", + "The product declares no identity facts for this access profile.", + "Use a profile declared in the product's identity facts.", + )), + _ => None, + }) else { continue; }; diff --git a/crates/registry-rstack-dev/src/roles.rs b/crates/registry-rstack-dev/src/roles.rs index 292c02571f..5a4b0c28ad 100644 --- a/crates/registry-rstack-dev/src/roles.rs +++ b/crates/registry-rstack-dev/src/roles.rs @@ -236,7 +236,7 @@ pub(super) fn resolve( .values() .flat_map(|person| person.roles.iter().map(String::as_str)) .collect(); - service.validate_references(&assigned, |product, id| { + service.validate_development_references(&assigned, |product, id| { facts.get(product).map(|facts| { facts .facts diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index 7ee71e429c..ad5f858371 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -2184,6 +2184,10 @@ fn dev_check_reports_unknown_products_in_unassigned_service_roles() { ); assert_eq!(diagnostic["source"]["line"], 8); assert_eq!(diagnostic["source"]["column"], 7); + assert_eq!( + diagnostic["suggestedAction"], + "Use a recognized product key in service.yaml or remove this reference." + ); assert!(!diagnostic.to_string().contains("private-profile-marker")); } assert!(!state.exists()); @@ -2209,6 +2213,10 @@ fn start_reports_an_actionable_value_free_role_for_an_unstarted_product() { .as_str() .unwrap() .ends_with("/service.yaml")); + assert_eq!( + diagnostic["suggestedAction"], + "List this product in dev.yaml if supported, or change the role in service.yaml." + ); assert!(!diagnostic.to_string().contains("private-profile-marker")); assert!(!state.exists()); @@ -2228,8 +2236,9 @@ fn start_reports_an_actionable_value_free_role_for_an_unstarted_product() { "{error}" ); assert!( - error - .contains("Supply identity facts for this product or change the role in service.yaml."), + error.contains( + "List this product in dev.yaml if supported, or change the role in service.yaml." + ), "{error}" ); for supplied in [ diff --git a/crates/registry-thunderid-tooling/src/identity_check.rs b/crates/registry-thunderid-tooling/src/identity_check.rs index 951a725a0f..1245f7c281 100644 --- a/crates/registry-thunderid-tooling/src/identity_check.rs +++ b/crates/registry-thunderid-tooling/src/identity_check.rs @@ -354,6 +354,10 @@ mod tests { ); }; assert_eq!(diagnostic.code, "identity.deployment.unknown-product"); + assert_eq!( + diagnostic.suggested_action, + "Use a recognized product or supply its identity facts to the hosted check." + ); assert_eq!(diagnostic.artifact.as_deref(), Some("RStackService")); assert_eq!( diagnostic.path, diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 7d779b321f..8120ec7716 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -634,13 +634,16 @@ When each step names its actor and the run uses its own issuer, the rehearsal ob The run obtains the normal schema-test receipt before packaging. A role may refer to a profile that grants only proposal permissions. -Dev runs and hosted identity checks validate product references even in unassigned roles. +Dev loads the sibling `service.yaml` when `dev.yaml` declares at least one test person. +Dev and hosted identity checks validate product references in that role file, including references in unassigned roles. A known product can appear in an unassigned role when its identity facts are outside the current run. The checks validate access profiles wherever they load identity facts. Every assigned role must have facts for each product it names when you run a full identity check. An invalid reference points to its `accessProfiles` entry in `service.yaml`. -{/* Evidence: crates/registry-platform-config/src/service_roles.rs, RoleDocument::validate_references(); +{/* Evidence: crates/registry-platform-config/src/service_roles.rs, RoleDocument::validate_references(), + RoleDocument::validate_development_references(); + crates/registry-rstack-dev/src/roles.rs, resolve; crates/registry-rstack/tests/dev_run.rs, dev_check_reports_unknown_products_in_unassigned_service_roles; crates/registry-thunderid-tooling/src/identity_check.rs, hosted_check_reports_unknown_products_in_unassigned_service_roles. */} When migrating an existing plan, move profile references to `service.yaml` and replace each From 4d5616c64ebe300fdfefab6edacf9e0693a4feac Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:21:56 +0000 Subject: [PATCH 14/26] feat(rstack-dev): verify offline owner role evidence Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/dev_facts.rs | 456 +++++++++++++++++- crates/registry-rstack-dev/src/plan.rs | 8 +- crates/registry-rstack-dev/src/products.rs | 31 +- crates/registry-rstack-dev/src/roles.rs | 2 + .../run-a-project-with-rstack-dev.mdx | 10 + 5 files changed, 479 insertions(+), 28 deletions(-) diff --git a/crates/registry-rstack-dev/src/dev_facts.rs b/crates/registry-rstack-dev/src/dev_facts.rs index a1f471cd14..d0a67241e9 100644 --- a/crates/registry-rstack-dev/src/dev_facts.rs +++ b/crates/registry-rstack-dev/src/dev_facts.rs @@ -4,6 +4,9 @@ use std::{ collections::{BTreeMap, BTreeSet}, ffi::OsStr, + fs::{File, OpenOptions}, + io::Read, + os::unix::fs::OpenOptionsExt, path::Path, process::Stdio, sync::atomic::{AtomicBool, Ordering}, @@ -14,14 +17,19 @@ use anyhow::{anyhow, ensure, Context, Result}; use registry_platform_config::identity_facts::{ self, AccessProfile, ActorKind, Admission, ClaimType, IdentityFacts, }; +use registry_platform_config::package::{verify_package, PackageLimits}; use registry_platform_yaml::{Reader, MAXIMUM_DOCUMENT_BYTES}; use serde::Deserialize; use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; use super::{ plan::{self, Plan, Product, ProductPlan}, product_tool, - products::{child_command, inspection_failed, issuer_set, tool_report, wait_for_tool}, + products::{ + child_command, inspection_failed, issuer_set, strict_tool_report, tool_report, + wait_for_tool, + }, signals, write_private, }; @@ -40,6 +48,7 @@ pub(super) fn load( external_jwks_uri: Option<&str>, products: &[ProductPlan], clients: &BTreeSet, + offline_check: bool, ) -> Result> { let scratch = tempfile::tempdir()?; let scratch_root = scratch.path().canonicalize()?; @@ -73,6 +82,7 @@ pub(super) fn load( external_jwks_uri, clients, &terminate, + offline_check, ) })(); let result = facts_result.map_err(|error: anyhow::Error| { @@ -106,6 +116,7 @@ fn load_product_facts( external_jwks_uri: Option<&str>, clients: &BTreeSet, terminate: &AtomicBool, + offline_check: bool, ) -> Result { let product = plan.product; if product == Product::Breg { @@ -115,11 +126,12 @@ fn load_product_facts( "explain", &[OsStr::new("access"), project.as_os_str()], terminate, + offline_check, )?; return breg_explanation(&report["explanation"], issuer, &plan.audience); } let file = scratch.join(format!("{}-identity-facts.yaml", product.name())); - native_facts( + let report = native_facts( tool, plan, project, @@ -129,19 +141,27 @@ fn load_product_facts( clients, &file, terminate, + offline_check, )?; - let bytes = plan::read(&file, MAXIMUM_DOCUMENT_BYTES as u64)?; + let bytes = if offline_check { + read_offline_facts(&file)? + } else { + plan::read(&file, MAXIMUM_DOCUMENT_BYTES as u64)? + }; let facts = identity_facts::read(&file.to_string_lossy(), &bytes)?; - ensure!( - facts.product == product.name(), - "the owning tool wrote facts for a different product" - ); - ensure!( - facts.issuer == issuer && facts.audience == plan.audience, - "the owning tool wrote facts for a different issuer or audience" - ); + validate_facts_context(&facts, product, issuer, &plan.audience)?; + if let Some(report) = report { + validate_written_facts(product, &report, &file, &facts)?; + } let principal_claims = if product == Product::Casework { - let report = checked_report(tool, product, "explain", &[project.as_os_str()], terminate)?; + let report = checked_report( + tool, + product, + "explain", + &[project.as_os_str()], + terminate, + offline_check, + )?; principals(&report)? } else { BTreeMap::new() @@ -164,8 +184,17 @@ fn checked_report( command: &str, args: &[&OsStr], terminate: &AtomicBool, + offline_check: bool, ) -> Result { - let (status, report) = tool_report(tool, product.name(), command, args, terminate)?; + let read = if offline_check { + strict_tool_report + } else { + tool_report + }; + let (status, report) = read(tool, product.name(), command, args, terminate)?; + if offline_check && (status.success() || status.code() == Some(1)) { + validate_offline_report(&report, product, command, status.success())?; + } if !status.success() { let codes: Vec<_> = report["diagnostics"] .as_array() @@ -207,11 +236,15 @@ fn native_facts( clients: &BTreeSet, output: &Path, terminate: &AtomicBool, -) -> Result<()> { + offline_check: bool, +) -> Result> { let product = plan.product; let package = scratch.join(format!("{}-package", product.name())); - if matches!(product, Product::Messaging | Product::Scheduling) { - checked_report( + let messaging_tool = (offline_check && product == Product::Messaging) + .then(|| tool_digest(tool)) + .transpose()?; + let package_report = if matches!(product, Product::Messaging | Product::Scheduling) { + let report = checked_report( tool, product, "package", @@ -221,15 +254,45 @@ fn native_facts( package.as_os_str(), ], terminate, + offline_check, )?; - } + if offline_check { + ensure!( + package + .to_str() + .is_some_and(|path| report["output"] == path) + && report["dryRun"] == false, + "the owning tool reported a different package output" + ); + } + Some(report) + } else { + None + }; let runtime = scratch.join(format!("{}-runtime.yaml", product.name())); - let config_file = if product == Product::Evidence { - evidence_target(project, scratch, issuer, external_jwks_uri, &plan.audience)? + let (config_file, messaging_pins) = if product == Product::Evidence { + ( + evidence_target(project, scratch, issuer, external_jwks_uri, &plan.audience)?, + None, + ) } else { let config = runtime_for_facts(plan, project, scratch, &package, issuer, clients)?; - write_private(&runtime, &serde_json::to_vec(&config)?)?; - runtime + let bytes = serde_json::to_vec(&config)?; + write_private(&runtime, &bytes)?; + let pins = if let Some(tool) = messaging_tool { + let digest = package_report + .as_ref() + .and_then(|report| report["projectDigest"].as_str()) + .context("missing Messaging package digest")?; + Some(MessagingPins { + tool, + runtime: Sha256::digest(&bytes).into(), + package: digest.to_owned(), + }) + } else { + None + }; + (runtime, pins) }; let mut args = vec![OsStr::new("identity-facts")]; if matches!( @@ -273,12 +336,188 @@ fn native_facts( status.success(), "Render refused the development facts input" ); + return Ok(None); + } + if let Some(pins) = &messaging_pins { + pins.check(tool, &package, &config_file)?; + } + let report = checked_report(tool, product, "generate", &args, terminate, offline_check); + if let Some(pins) = &messaging_pins { + pins.check(tool, &package, &config_file)?; + } + Ok(offline_check.then_some(report?)) +} + +fn validate_facts_context( + facts: &IdentityFacts, + product: Product, + issuer: &str, + audience: &str, +) -> Result<()> { + ensure!( + facts.product == product.name(), + "the owning tool wrote facts for a different product" + ); + ensure!( + facts.issuer == issuer && facts.audience == audience, + "the owning tool wrote facts for a different issuer or audience" + ); + Ok(()) +} + +fn validate_offline_report( + report: &Value, + product: Product, + command: &str, + success: bool, +) -> Result<()> { + let (kind, format) = match product { + Product::Adapter => ("AdapterCtlReport", "adapter/ctl-report/v1alpha1"), + Product::Breg => ("BRegCtlReport", "breg/ctl-report/v1alpha1"), + Product::Casework => ("CaseworkReport", "casework/report/v1alpha2"), + Product::Coordinator => ("CoordinatorCtlReport", "coordinator/ctl-report/v1alpha1"), + Product::Documents => ("DocumentsCtlReport", "documents/ctl-report/v1alpha1"), + Product::Evidence => ("EvidenceCtlReport", "evidence/ctl-report/v1alpha1"), + Product::Messaging => ("MessagingCtlReport", "messaging/ctl-report/v1alpha1"), + Product::Scheduling => ("SchedulingCtlReport", "scheduling/ctl-report/v1alpha1"), + Product::Discovery | Product::Render => unreachable!("no JSON owner facts receipt"), + }; + let status = if !success { + "domain-refusal" + } else if product == Product::Coordinator && command == "generate" { + "generated" } else { - checked_report(tool, product, "generate", &args, terminate)?; + "complete" + }; + let command = match (product, command) { + (Product::Casework, "generate") => "generate-identity-facts", + (_, "generate") => "generate identity-facts", + (_, other) => other, + }; + let version = format!("id.registrystack.org/formats/{format}"); + ensure!( + report["kind"] == kind + && report["apiVersion"] == version + && report["command"] == command + && report["status"] == status + && report["ok"] == success, + "the owning tool did not return the expected offline report" + ); + Ok(()) +} + +fn validate_written_facts( + product: Product, + report: &Value, + output: &Path, + facts: &IdentityFacts, +) -> Result<()> { + ensure!( + output.to_str().is_some_and(|path| report["output"] == path), + "the owning tool reported a different identity facts output" + ); + // Coordinator's receipt names the output. The shared typed file carries + // the actual inventory, as it does for the other writers. + if product != Product::Coordinator { + ensure!( + report["accessProfiles"].as_u64() == Some(facts.access_profiles.len() as u64) + && report["claims"].as_u64() == Some(facts.claims.len() as u64), + "the owning tool report does not match the written identity facts inventory" + ); + } + if matches!(product, Product::Casework | Product::Evidence) { + ensure!( + report["product"] == product.name() + && report["assertionIssuers"].as_u64() + == Some(facts.assertion_issuers.len() as u64), + "the owning tool report does not match the written assertion issuer inventory" + ); } Ok(()) } +struct MessagingPins { + tool: [u8; 32], + runtime: [u8; 32], + package: String, +} + +impl MessagingPins { + fn check(&self, tool: &Path, package: &Path, runtime: &Path) -> Result<()> { + ensure!( + tool_digest(tool)? == self.tool, + "the Messaging owner tool changed" + ); + ensure!( + runtime_digest(runtime)? == self.runtime, + "the Messaging runtime input changed" + ); + let verified = + verify_package(package, &PackageLimits::default(), "messagingctl package") + .map_err(|_| anyhow!("the Messaging package changed or could not be verified"))?; + ensure!( + verified.digest() == self.package, + "the Messaging package changed" + ); + Ok(()) + } +} + +fn open_offline_file(path: &Path) -> Result { + let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK; + let file = OpenOptions::new() + .read(true) + .custom_flags(flags.bits() as i32) + .open(path)?; + ensure!( + file.metadata()?.is_file(), + "the offline inspection input is not a regular file" + ); + Ok(file) +} + +fn read_offline_facts(path: &Path) -> Result> { + let limit = MAXIMUM_DOCUMENT_BYTES as u64; + let mut bytes = Vec::new(); + open_offline_file(path)? + .take(limit + 1) + .read_to_end(&mut bytes)?; + ensure!( + bytes.len() as u64 <= limit, + "the offline identity facts exceed their read bound" + ); + Ok(bytes) +} + +fn file_digest(path: &Path, limit: u64) -> Result<[u8; 32]> { + let mut file = open_offline_file(path)?.take(limit + 1); + let mut hasher = Sha256::new(); + let mut buffer = [0; 8192]; + loop { + let count = file.read(&mut buffer)?; + if count == 0 { + break; + } + hasher.update(&buffer[..count]); + } + ensure!( + file.limit() > 0, + "the offline inspection input exceeds its read bound" + ); + Ok(hasher.finalize().into()) +} + +fn tool_digest(tool: &Path) -> Result<[u8; 32]> { + // Includes debug tools while bounding read time and memory for this offline check. + const MAX_TOOL_BYTES: u64 = 512 * 1024 * 1024; + file_digest(tool, MAX_TOOL_BYTES).context("cannot read the Messaging owner tool") +} + +fn runtime_digest(runtime: &Path) -> Result<[u8; 32]> { + file_digest(runtime, MAXIMUM_DOCUMENT_BYTES as u64) + .context("cannot read the Messaging runtime input") +} + fn evidence_target( project: &Path, scratch: &Path, @@ -704,6 +943,179 @@ fn breg_explanation(explanation: &Value, issuer: &str, audience: &str) -> Result mod tests { use super::*; + #[test] + fn offline_owner_report_refuses_an_incomplete_or_outdated_report() { + let complete = json!({ + "apiVersion": "id.registrystack.org/formats/casework/report/v1alpha2", + "kind": "CaseworkReport", "command": "generate-identity-facts", + "status": "complete", "ok": true, "product": "casework", + "output": "/fixture/facts.yaml", "accessProfiles": 2, "claims": 3, + "assertionIssuers": 0 + }); + validate_offline_report(&complete, Product::Casework, "generate", true).unwrap(); + let mut incomplete = complete.clone(); + incomplete.as_object_mut().unwrap().remove("ok"); + assert!(validate_offline_report(&incomplete, Product::Casework, "generate", true).is_err()); + for (field, wrong) in [ + ( + "apiVersion", + json!("id.registrystack.org/formats/casework/report/v1alpha1"), + ), + ("kind", json!("OtherReport")), + ("command", json!("explain")), + ("status", json!("domain-refusal")), + ("ok", json!(false)), + ] { + let mut outdated = complete.clone(); + outdated[field] = wrong; + assert!( + validate_offline_report(&outdated, Product::Casework, "generate", true).is_err(), + "{field}" + ); + } + let mut refusal = complete; + refusal["ok"] = json!(false); + refusal["status"] = json!("domain-refusal"); + refusal["diagnostics"] = json!([{"code": "casework.identity.refused"}]); + validate_offline_report(&refusal, Product::Casework, "generate", false).unwrap(); + } + + #[test] + fn offline_report_requires_unique_members_from_owner_subprocess() { + use std::{fs, os::unix::fs::PermissionsExt}; + + let scratch = tempfile::tempdir().unwrap(); + let tool = scratch.path().join("offline-report"); + let body = r#"{"ok":false,"ok":true,"command":"explain","status":"complete", + "kind":"BRegCtlReport","apiVersion":"id.registrystack.org/formats/breg/ctl-report/v1alpha1"}"#; + fs::write(&tool, format!("#!/bin/sh\nprintf '%s' '{body}'\n")).unwrap(); + fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap(); + let terminate = AtomicBool::new(false); + checked_report(&tool, Product::Breg, "explain", &[], &terminate, false).unwrap(); + let error = + checked_report(&tool, Product::Breg, "explain", &[], &terminate, true).unwrap_err(); + assert_eq!(error.to_string(), "breg explain did not emit a JSON report"); + } + + #[test] + fn offline_owner_report_correlates_exact_output_and_facts() { + let product = Product::Messaging; + let output = Path::new("/fixture/facts.yaml"); + let facts = IdentityFacts::new( + product.name(), + "https://issuer.example.test", + "urn:fixture:messages", + Admission::Unrestricted, + ); + let report = json!({"output": output, "accessProfiles": 0, "claims": 0}); + validate_written_facts(product, &report, output, &facts).unwrap(); + for (field, value) in [ + ("output", json!("/other/facts.yaml")), + ("accessProfiles", json!(1)), + ("claims", json!(1)), + ] { + let mut stale = report.clone(); + stale[field] = value; + assert!( + validate_written_facts(product, &stale, output, &facts).is_err(), + "{field}" + ); + } + for (issuer, audience) in [ + ("https://outdated.example.test", facts.audience.as_str()), + (facts.issuer.as_str(), "urn:outdated"), + ] { + assert!(validate_facts_context(&facts, product, issuer, audience).is_err()); + } + validate_facts_context(&facts, product, &facts.issuer, &facts.audience).unwrap(); + } + + #[test] + fn offline_messaging_pins_refuse_independent_changes() { + use registry_platform_config::package::write_package; + + let scratch = tempfile::tempdir().unwrap(); + let package = scratch.path().join("package"); + let manifest = package.join("messaging.yaml"); + let tool = scratch.path().join("messagingctl"); + let runtime = scratch.path().join("runtime.yaml"); + let verified = write_package( + &package, + &BTreeMap::from([("messaging.yaml".to_owned(), b"package".to_vec())]), + None, + &PackageLimits::default(), + "messagingctl package", + ) + .unwrap(); + std::fs::write(&tool, b"owner tool").unwrap(); + std::fs::write(&runtime, b"runtime").unwrap(); + let pins = MessagingPins { + tool: tool_digest(&tool).unwrap(), + runtime: runtime_digest(&runtime).unwrap(), + package: verified.digest().to_owned(), + }; + pins.check(&tool, &package, &runtime).unwrap(); + for (path, expected) in [ + (&tool, "tool changed"), + (&runtime, "runtime input changed"), + (&manifest, "package changed"), + ] { + let original = std::fs::read(path).unwrap(); + std::fs::write(path, b"outdated").unwrap(); + assert!(pins + .check(&tool, &package, &runtime) + .unwrap_err() + .to_string() + .contains(expected)); + std::fs::write(path, original).unwrap(); + } + pins.check(&tool, &package, &runtime).unwrap(); + } + + #[test] + #[ignore = "requires the matched messagingctl via RSTACK_MESSAGINGCTL_BIN"] + fn offline_messaging_native_facts_retain_actorless_owner_profile() { + use identity_facts::ACTOR_KIND_CLAIM; + + let project = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/messaging/examples/starter") + .canonicalize() + .unwrap(); + let scratch = tempfile::tempdir().unwrap(); + let plan = ProductPlan { + product: Product::Messaging, + project: ".".into(), + audience: "urn:example:messaging".into(), + }; + let observed = load_product_facts( + &product_tool(Product::Messaging).unwrap(), + &plan, + &project, + &scratch.path().canonicalize().unwrap(), + "https://issuer.example.test", + None, + &BTreeSet::new(), + &AtomicBool::new(false), + true, + ) + .unwrap(); + let operation = observed + .facts + .access_profiles + .iter() + .find(|profile| profile.id == "operations") + .unwrap(); + assert_eq!(operation.scopes, ["messaging:operate"]); + assert!(operation.actor_kind.is_none()); + assert!(operation.admitted_actor_kinds.is_empty()); + assert!(!operation.selected_by.contains_key(ACTOR_KIND_CLAIM)); + assert!(!operation + .required_claims + .iter() + .chain(&operation.refused_claims) + .any(|claim| claim == ACTOR_KIND_CLAIM)); + } + #[test] fn breg_facts_keep_exact_empty_scopes_and_claim_types() { let explanation = json!({ diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 2508dd2f53..951eee14ee 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -1032,7 +1032,7 @@ struct AuthoredPlan { sources: Option, } -fn read_plan(root: &Path) -> Result<(AuthoredPlan, AuthoredDigests)> { +fn read_plan(root: &Path, offline_check: bool) -> Result<(AuthoredPlan, AuthoredDigests)> { let (authored, dev) = decode_authored_plan(root)?; authored .value @@ -1060,7 +1060,7 @@ fn read_plan(root: &Path) -> Result<(AuthoredPlan, AuthoredDigests)> { document, sources, } = authored; - let resolved = super::roles::resolve(root, &document, value); + let resolved = super::roles::resolve(root, &document, value, offline_check); if resolved.is_err() { if let Some((source, expected)) = native_source.as_deref().zip(preview_native) { super::preview::verify_native_source(source, expected)?; @@ -1211,7 +1211,7 @@ pub(super) struct LoadedPlan { } pub(crate) fn check(root: &Path) -> Result { - let (decoded, authored_digests) = read_plan(root)?; + let (decoded, authored_digests) = read_plan(root, true)?; validate_plan(root, &decoded)?; read_journeys(root, &decoded.value)?; let preview = preview_plan(root, &decoded, &authored_digests)?; @@ -1238,7 +1238,7 @@ pub(crate) fn check(root: &Path) -> Result { } pub(super) fn load(root: &Path) -> Result { - let (decoded, authored_digests) = read_plan(root)?; + let (decoded, authored_digests) = read_plan(root, false)?; validate_plan(root, &decoded)?; let (scenarios, scenario_digest) = read_journeys(root, &decoded.value)?; let preview = preview_plan(root, &decoded, &authored_digests)?; diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 667e2caeef..b6d93ef07a 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -2966,6 +2966,29 @@ pub(super) fn tool_report( command: &str, arguments: &[&std::ffi::OsStr], terminate: &AtomicBool, +) -> Result<(ExitStatus, Value)> { + read_tool_report(tool, name, command, arguments, terminate, false) +} + +/// The offline owner check uses unique-member JSON while preserving existing +/// readers for other product inspection paths. +pub(super) fn strict_tool_report( + tool: &Path, + name: &str, + command: &str, + arguments: &[&std::ffi::OsStr], + terminate: &AtomicBool, +) -> Result<(ExitStatus, Value)> { + read_tool_report(tool, name, command, arguments, terminate, true) +} + +fn read_tool_report( + tool: &Path, + name: &str, + command: &str, + arguments: &[&std::ffi::OsStr], + terminate: &AtomicBool, + strict: bool, ) -> Result<(ExitStatus, Value)> { let mut child = child_command(tool) .args(["--format", "json", command]) @@ -2995,8 +3018,12 @@ pub(super) fn tool_report( bytes.len() as u64 <= MAX_TOOL_REPORT, "the {name} {command} report exceeds the size limit" ); - let report = serde_json::from_slice(&bytes) - .map_err(|_| anyhow::anyhow!("{name} {command} did not emit a JSON report"))?; + let malformed = || anyhow::anyhow!("{name} {command} did not emit a JSON report"); + let report = if strict { + registry_platform_crypto::parse_json_strict(&bytes).map_err(|_| malformed())? + } else { + serde_json::from_slice(&bytes).map_err(|_| malformed())? + }; Ok((status, report)) } diff --git a/crates/registry-rstack-dev/src/roles.rs b/crates/registry-rstack-dev/src/roles.rs index 5a4b0c28ad..1d0bbf4c8e 100644 --- a/crates/registry-rstack-dev/src/roles.rs +++ b/crates/registry-rstack-dev/src/roles.rs @@ -163,6 +163,7 @@ pub(super) fn resolve( root: &Path, document: &Document, authored: Plan, + offline_check: bool, ) -> Result<(Plan, Option)> { let Plan { issuer, @@ -229,6 +230,7 @@ pub(super) fn resolve( .values() .map(|person| person.client.clone()) .collect(), + offline_check, )? }; if let Some(service) = &service_roles { diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 8120ec7716..d13675d190 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -649,6 +649,16 @@ An invalid reference points to its `accessProfiles` entry in `service.yaml`. When migrating an existing plan, move profile references to `service.yaml` and replace each person's `grants` with their role IDs. Remove the per-person scopes and actor kind. +Use the matching product tools when you run `rstack dev check`. The offline check verifies the +owner reports it uses and matches generated identity facts to the run's issuer and product audience. +For BReg it reads the compiled access explanation and takes issuer and audience from your development plan. +For Render it reads the generated identity facts file. For Messaging it also checks the staged package, +runtime input and owner tool for changes around facts generation. +If the check reports an incompatible owner report, select the matching product tool and run the check again. + +{/* Evidence: crates/registry-rstack-dev/src/dev_facts.rs load_product_facts, + validate_offline_report, validate_facts_context, validate_written_facts, MessagingPins. */} + For synthetic refusal fixtures, a person can narrow the derived scopes or omit a claim using `tokenFixtures` under the product key. The facility statistics acceptance test also uses this field to carry a purpose for audit and cursor context. The purpose must not qualify the bearer From b63fbc62a1ca9ed158f8424e06375ba5a82fc62a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:00:18 +0000 Subject: [PATCH 15/26] test(rstack-dev): pin offline reports to owner formats Signed-off-by: Jeremi Joslin --- crates/registry-adapterctl/src/report.rs | 6 + crates/registry-rstack-dev/src/dev_facts.rs | 12 +- .../src/dev_facts/offline_tests.rs | 218 ++++++++++++++++++ .../adapter/examples/formats/ctl-report.json | 16 ++ products/platform/CHANGELOG.md | 3 + 5 files changed, 254 insertions(+), 1 deletion(-) create mode 100644 crates/registry-rstack-dev/src/dev_facts/offline_tests.rs create mode 100644 products/adapter/examples/formats/ctl-report.json diff --git a/crates/registry-adapterctl/src/report.rs b/crates/registry-adapterctl/src/report.rs index 45ec3e6462..3756ef71d3 100644 --- a/crates/registry-adapterctl/src/report.rs +++ b/crates/registry-adapterctl/src/report.rs @@ -311,6 +311,12 @@ mod tests { let report: Value = serde_json::from_slice(&out).unwrap(); assert_eq!(report["apiVersion"], ADAPTER_CTL_REPORT_API_VERSION); assert_eq!(report["kind"], ADAPTER_CTL_REPORT_KIND); + let example: Value = serde_json::from_slice(include_bytes!( + "../../../products/adapter/examples/formats/ctl-report.json" + )) + .unwrap(); + assert_eq!(example["apiVersion"], report["apiVersion"]); + assert_eq!(example["kind"], report["kind"]); assert_eq!(report.as_object().unwrap().len(), 5); } diff --git a/crates/registry-rstack-dev/src/dev_facts.rs b/crates/registry-rstack-dev/src/dev_facts.rs index d0a67241e9..233ce5de95 100644 --- a/crates/registry-rstack-dev/src/dev_facts.rs +++ b/crates/registry-rstack-dev/src/dev_facts.rs @@ -380,7 +380,12 @@ fn validate_offline_report( Product::Evidence => ("EvidenceCtlReport", "evidence/ctl-report/v1alpha1"), Product::Messaging => ("MessagingCtlReport", "messaging/ctl-report/v1alpha1"), Product::Scheduling => ("SchedulingCtlReport", "scheduling/ctl-report/v1alpha1"), - Product::Discovery | Product::Render => unreachable!("no JSON owner facts receipt"), + Product::Discovery | Product::Render => { + anyhow::bail!( + "{} has no JSON owner identity facts receipt", + product.name() + ) + } }; let status = if !success { "domain-refusal" @@ -436,6 +441,7 @@ fn validate_written_facts( Ok(()) } +// Messaging derives admitted clients from the package built for this inspection. struct MessagingPins { tool: [u8; 32], runtime: [u8; 32], @@ -939,6 +945,10 @@ fn breg_explanation(explanation: &Value, issuer: &str, audience: &str) -> Result }) } +#[cfg(test)] +#[path = "dev_facts/offline_tests.rs"] +mod offline_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-rstack-dev/src/dev_facts/offline_tests.rs b/crates/registry-rstack-dev/src/dev_facts/offline_tests.rs new file mode 100644 index 0000000000..f6a05c71a4 --- /dev/null +++ b/crates/registry-rstack-dev/src/dev_facts/offline_tests.rs @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: Apache-2.0 + +use registry_platform_config::service_roles::{self, decode_role_document}; + +use super::*; + +const ISSUER: &str = "https://issuer.example.test"; +const PROFILE: &str = "fixture-reader"; +const AUDIENCE: &str = "urn:fixture:owner"; + +fn parse(bytes: &[u8]) -> Value { + serde_json::from_slice(bytes).expect("owner artifact is JSON") +} + +fn casework_generator_envelope() -> Value { + let contract = parse(include_bytes!( + "../../../../products/casework/contracts/cli/report.schema.json" + )); + let properties = contract["oneOf"] + .as_array() + .unwrap() + .iter() + .find(|branch| branch["properties"]["command"]["const"] == "generate-identity-facts") + .expect("Casework's maintained schema names the facts writer") + .get("properties") + .unwrap(); + json!({ + "kind": properties["kind"]["const"], + "apiVersion": properties["apiVersion"]["const"], + "command": properties["command"]["const"], + }) +} + +#[test] +fn offline_role_checks_match_the_nine_owner_contracts() { + // The envelopes are read from owner artifacts. The facts and the related + // role assignment are synthetic so this matrix runs without owner tools. + let owners = [ + ( + Product::Adapter, + Some(parse(include_bytes!( + "../../../../products/adapter/examples/formats/ctl-report.json" + ))), + ), + ( + Product::Breg, + Some(parse(include_bytes!( + "../../../../products/breg/examples/formats/ctl-report.json" + ))), + ), + (Product::Casework, Some(casework_generator_envelope())), + ( + Product::Coordinator, + Some(parse(include_bytes!( + "../../../../products/coordinator/examples/formats/ctl-report.json" + ))), + ), + ( + Product::Documents, + Some(parse(include_bytes!( + "../../../../products/documents/examples/formats/ctl-report.json" + ))), + ), + ( + Product::Evidence, + Some(parse(include_bytes!( + "../../../../products/evidence/examples/formats/ctl-report.json" + ))), + ), + ( + Product::Messaging, + Some(parse(include_bytes!( + "../../../../products/messaging/examples/formats/ctl-report.json" + ))), + ), + ( + Product::Scheduling, + Some(parse(include_bytes!( + "../../../../products/scheduling/examples/formats/ctl-report.json" + ))), + ), + (Product::Render, None), + ]; + for (product, report) in owners { + let facts = + if product == Product::Breg { + breg_explanation(&json!({ + "claimContract": {"principalClaims": ["sub"], "directClaims": {}}, + "recordTypes": [{"profiles": [{ + "id": PROFILE, "requiredScopes": ["records:read"], "principalClaim": "sub" + }]}], + "statisticalDatasets": [], "actions": {"actions": []}, + }), ISSUER, AUDIENCE).unwrap().facts + } else { + let facts = json!({ + "apiVersion": "id.registrystack.org/formats/platform/identity-facts/v1", + "kind": "PlatformIdentityFacts", + "product": product.name(), + "issuer": ISSUER, + "audience": AUDIENCE, + "allowedClients": ["fixture-client"], + "accessProfiles": [{"id": PROFILE, "scopes": ["records:read"]}] + }); + identity_facts::read("facts.yaml", &serde_json::to_vec(&facts).unwrap()) + .expect("the product facts decode on the native typed reader") + }; + validate_facts_context(&facts, product, ISSUER, AUDIENCE).unwrap(); + assert!( + validate_facts_context(&facts, product, "https://stale.example.test", AUDIENCE) + .is_err(), + "{} outdated issuer", + product.name(), + ); + assert!( + validate_facts_context(&facts, product, ISSUER, "urn:stale").is_err(), + "{} outdated audience", + product.name(), + ); + if let Some(report) = report { + check_receipt_and_drift(report, product, &facts); + } else { + assert!( + validate_offline_report(&Value::Null, product, "generate", true) + .unwrap_err() + .to_string() + .contains("has no JSON owner identity facts receipt") + ); + } + + let service = |profile| { + json!({ + "apiVersion": service_roles::API_VERSION, + "kind": service_roles::KIND, + "roles": {"fixture-role": { + "actorKind": "human", + "accessProfiles": {(product.name()): [profile]} + }} + }) + }; + let decode_service = |profile| { + decode_role_document( + "service.yaml", + &serde_json::to_vec(&service(profile)).unwrap(), + ) + .expect("the authored service roles decode") + }; + let has_profile = |name: &str, profile: &str| { + (name == facts.product).then(|| { + facts + .access_profiles + .iter() + .any(|entry| entry.id == profile) + }) + }; + let assigned = BTreeSet::from(["fixture-role"]); + decode_service(PROFILE) + .validate_references(&assigned, has_profile) + .unwrap(); + let failure = decode_service("absent-profile") + .validate_references(&assigned, has_profile) + .unwrap_err(); + let [diagnostic] = failure.diagnostics() else { + panic!("expected one assignment diagnostic for {}", product.name()); + }; + assert_eq!(diagnostic.code, "identity.deployment.unknown-profile"); + assert_eq!( + diagnostic.path, + format!("/roles/fixture-role/accessProfiles/{}", product.name()) + ); + } +} + +fn check_receipt_and_drift(mut report: Value, product: Product, facts: &IdentityFacts) { + // Casework derives its command from the exact selected schema branch. + if product != Product::Casework { + report["command"] = json!(if product == Product::Breg { + "explain" + } else { + "generate identity-facts" + }); + } + report["ok"] = json!(true); + report["status"] = json!(if product == Product::Coordinator { + "generated" + } else { + "complete" + }); + let command = if product == Product::Breg { + "explain" + } else { + "generate" + }; + validate_offline_report(&report, product, command, true).unwrap_or_else(|error| { + panic!( + "{} report differs from the owner artifact: {error}", + product.name() + ) + }); + + let mut incomplete = report.clone(); + incomplete.as_object_mut().unwrap().remove("ok"); + assert!(validate_offline_report(&incomplete, product, command, true).is_err()); + let mut old = report.clone(); + old["apiVersion"] = json!("id.registrystack.org/formats/stale/report/v1"); + assert!(validate_offline_report(&old, product, command, true).is_err()); + + if product != Product::Breg { + let output = Path::new("/fixture/facts.yaml"); + report["output"] = json!(output); + report["product"] = json!(product.name()); + report["accessProfiles"] = json!(facts.access_profiles.len()); + report["claims"] = json!(facts.claims.len()); + report["assertionIssuers"] = json!(facts.assertion_issuers.len()); + validate_written_facts(product, &report, output, facts).unwrap(); + report["output"] = json!("/stale/facts.yaml"); + assert!(validate_written_facts(product, &report, output, facts).is_err()); + } +} diff --git a/products/adapter/examples/formats/ctl-report.json b/products/adapter/examples/formats/ctl-report.json new file mode 100644 index 0000000000..2d742aafb2 --- /dev/null +++ b/products/adapter/examples/formats/ctl-report.json @@ -0,0 +1,16 @@ +{ + "ok": true, + "command": "check", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/adapter/ctl-report/v1alpha1", + "kind": "AdapterCtlReport", + "diagnostics": [], + "filesChecked": 4, + "fixtures": "contracts only, replay not run", + "posture": { + "source": "default", + "value": "production" + }, + "explicitProductionSettings": [], + "project": "." +} diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index c8768fa0a8..6c9c5c95b0 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- `rstack dev check` refuses incompatible owner reports and mismatched identity facts. + For Messaging it also checks the staged package, runtime input and tool around facts generation. + ## 0.50.0 - 2026-12-01 - BREAKING: Projects with authored development people must replace their grants with roles defined in `service.yaml` and assigned under `people..roles` in `dev.yaml`. See the [Stack migration notes](../../release/notes/v0.50.0.md#service-roles). From 839efb88c37ce4494c1315e0d1282266fc8f3ccc Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 19:37:22 +0000 Subject: [PATCH 16/26] test(auth): cover browser callback tokens in both postures Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 1 + crates/registry-breg-review/Cargo.toml | 2 +- .../tests/review_pages.rs | 3 + .../review_pages/token_characterisation.rs | 187 ++++++++++++++++++ .../registry-breg-review/tests/support/mod.rs | 180 +++++++++++++---- .../src/access/token_characterisation.rs | 25 ++- .../platform/conformance/tokens/README.md | 19 +- .../tokens/browser-callback-expected.json | 18 ++ 8 files changed, 386 insertions(+), 49 deletions(-) create mode 100644 crates/registry-breg-review/tests/review_pages/token_characterisation.rs create mode 100644 products/platform/conformance/tokens/browser-callback-expected.json diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 870a0ef228..a34c187610 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -223,6 +223,7 @@ "registry-platform-testing", "registry-adapter", "registry-breg", + "registry-breg-review", "registry-casework", "registry-coordinator", "registry-documents", diff --git a/crates/registry-breg-review/Cargo.toml b/crates/registry-breg-review/Cargo.toml index d57a86b809..673a26e344 100644 --- a/crates/registry-breg-review/Cargo.toml +++ b/crates/registry-breg-review/Cargo.toml @@ -59,7 +59,7 @@ zeroize.workspace = true [dev-dependencies] jsonschema.workspace = true registry-platform-canonical-json.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 tempfile.workspace = true diff --git a/crates/registry-breg-review/tests/review_pages.rs b/crates/registry-breg-review/tests/review_pages.rs index 44f6386d7f..6b0818512b 100644 --- a/crates/registry-breg-review/tests/review_pages.rs +++ b/crates/registry-breg-review/tests/review_pages.rs @@ -4,6 +4,9 @@ mod support; +#[path = "review_pages/token_characterisation.rs"] +mod token_characterisation; + use std::time::Duration; use axum::http::StatusCode; diff --git a/crates/registry-breg-review/tests/review_pages/token_characterisation.rs b/crates/registry-breg-review/tests/review_pages/token_characterisation.rs new file mode 100644 index 0000000000..43fca21968 --- /dev/null +++ b/crates/registry-breg-review/tests/review_pages/token_characterisation.rs @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Authorization-code callback outcomes for the shared token shapes. The +//! bearer expectations stay in the shared resource-server corpus. + +use std::{collections::BTreeSet, sync::Arc}; + +use registry_platform_config::Posture; +use registry_platform_testing::{TokenCorpus, TokenSigner}; +use serde::Deserialize; + +use super::*; +use support::Callback; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "kebab-case")] +enum Outcome { + SignedIn, + Refused, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PostureOutcomes { + production: Outcome, + development: Outcome, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Row { + fixture: String, + callback: Callback, + #[serde(rename = "breg-review")] + review: PostureOutcomes, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Expectations { + schema: String, + rows: Vec, +} + +#[tokio::test] +async fn review_callback_matches_the_browser_token_corpus() { + use support::start_callback_corpus_provider; + + let corpus = TokenCorpus::load().expect("the bearer token corpus is valid"); + let source = include_bytes!( + "../../../../products/platform/conformance/tokens/browser-callback-expected.json" + ); + let strict = registry_platform_canonical_json::parse_json_strict(source) + .expect("the callback table is unique-member JSON"); + let expectations: Expectations = + serde_json::from_value(strict).expect("the callback table is well formed"); + assert_eq!( + expectations.schema, + "registry.browser-callback-expectations/v1" + ); + let mut keys = BTreeSet::new(); + for row in &expectations.rows { + assert!( + keys.insert((row.fixture.as_str(), row.callback)), + "duplicate callback row" + ); + let fixture = corpus + .fixture(&row.fixture) + .expect("unknown callback fixture"); + if fixture.token_use != "id" { + assert_eq!(row.review.production, Outcome::Refused); + assert_eq!(row.review.development, Outcome::Refused); + } + } + for fixture in corpus + .fixtures() + .iter() + .filter(|fixture| fixture.token_use == "id") + { + assert!( + keys.iter().any(|(id, _)| *id == fixture.id), + "missing callback row for {}", + fixture.id + ); + } + + let signer = Arc::new(TokenSigner::new()); + for posture in [Posture::Production, Posture::Development] { + let mut signed_in = 0; + let mut refused = 0; + for row in &expectations.rows { + let fixture = corpus.fixture(&row.fixture).unwrap().clone(); + let provider = + start_callback_corpus_provider(Arc::clone(&signer), fixture, row.callback).await; + let page = build_custom_issuer_page(&provider.issuer, posture, false) + .await + .unwrap(); + let response = redeem_corpus_callback(&page, &provider).await; + let expected = match posture { + Posture::Production => row.review.production, + Posture::Development => row.review.development, + }; + let context = format!("{posture:?} / {} / {:?}", row.fixture, row.callback); + assert_eq!(provider.token_calls(), 1, "{context}"); + let session_cookie_name = match posture { + Posture::Production => "__Host-breg-review-session", + Posture::Development => "breg-review-session", + }; + let cookie = response.set_cookie(session_cookie_name); + let audit = std::fs::read_to_string(&page.audit_path).unwrap(); + let terminal: serde_json::Value = + serde_json::from_str(audit.lines().last().expect("terminal callback audit")) + .unwrap(); + assert_eq!(terminal["phase"], "response", "{context}"); + assert_eq!(terminal["record"]["action"], "sign-in", "{context}"); + match expected { + Outcome::SignedIn => { + signed_in += 1; + assert_eq!(response.status, StatusCode::OK, "{context}"); + let cookie = cookie.expect("successful callback issues a session cookie"); + assert!(cookie.contains("HttpOnly"), "{context}"); + assert_eq!( + cookie.contains("; Secure"), + posture == Posture::Production, + "{context}" + ); + assert_eq!(terminal["record"]["outcome"], "ok", "{context}"); + } + Outcome::Refused => { + refused += 1; + assert_eq!(response.status, StatusCode::BAD_REQUEST, "{context}"); + assert_eq!(response.error_code(), Some("sign-in-refused"), "{context}"); + assert!(cookie.is_none(), "{context}"); + assert_eq!(terminal["record"]["outcome"], "refused", "{context}"); + } + } + } + assert!(signed_in > 0 && refused > 0); + println!("breg-review callback {posture:?}: {signed_in} signed in, {refused} refused"); + } +} + +async fn redeem_corpus_callback( + page: &CustomIssuerPage, + provider: &support::NarrowScopeProvider, +) -> support::Page { + let sign_in = page + .http + .get(format!("{}{}", page.origin, sign_in_location())) + .send() + .await + .unwrap(); + assert_eq!(sign_in.status(), StatusCode::SEE_OTHER); + let cookie = cookie_pair( + sign_in.headers()[reqwest::header::SET_COOKIE] + .to_str() + .unwrap(), + ); + // The test provider gives the browser a local authorization code. In + // production-shaped runtime config its advertised redirect is HTTPS. + let redirect = url::Url::parse( + sign_in.headers()[reqwest::header::LOCATION] + .to_str() + .unwrap(), + ) + .unwrap(); + let state = redirect + .query_pairs() + .find(|(key, _)| key == "state") + .unwrap() + .1; + let nonce = redirect + .query_pairs() + .find(|(key, _)| key == "nonce") + .unwrap() + .1; + let code = provider.issue_code(&nonce); + let callback = page + .http + .get(format!("{}/signin/callback", page.origin)) + .query(&[("state", state.as_ref()), ("code", &code)]) + .header(reqwest::header::COOKIE, cookie) + .send() + .await + .unwrap(); + support::page(callback).await +} diff --git a/crates/registry-breg-review/tests/support/mod.rs b/crates/registry-breg-review/tests/support/mod.rs index 4edfcb3fd9..04eacacd8b 100644 --- a/crates/registry-breg-review/tests/support/mod.rs +++ b/crates/registry-breg-review/tests/support/mod.rs @@ -821,20 +821,22 @@ struct NarrowScopeCode { redirect_uri: String, } -/// A minimal single-origin OpenID Connect provider whose token response -/// always states a scope narrower than the one the request asked for. -/// -/// The shared `TestAuthorizationServer` always echoes back exactly the scope -/// a request asked for, so it cannot produce this response; this provider -/// exists only to prove the sign-in client refuses a narrowed grant. +type IssueIdToken = dyn Fn(&str, NarrowScopeCode) -> String + Send + Sync; + +struct CallbackTokens { + jwks: Value, + issue: Box, +} + +/// A minimal OpenID Connect provider for callback responses the shared +/// authorization test server cannot issue. struct NarrowScopeState { issuer: String, authorization_endpoint: String, - signing_key: registry_platform_crypto::PrivateJwk, + tokens: CallbackTokens, codes: Arc>>, token_calls: Arc, scope: &'static str, - development_id_token: bool, } pub struct NarrowScopeProvider { @@ -880,21 +882,108 @@ pub async fn start_narrow_scope_provider() -> NarrowScopeProvider { pub async fn start_narrow_scope_provider_with_authorization( authorization_endpoint: Option<&str>, ) -> NarrowScopeProvider { - start_custom_provider(authorization_endpoint, "citizen:profile", false).await + start_custom_provider( + authorization_endpoint, + "citizen:profile", + synthetic_callback_tokens(false), + ) + .await } pub async fn start_development_id_token_provider( authorization_endpoint: Option<&str>, ) -> NarrowScopeProvider { - start_custom_provider(authorization_endpoint, SCOPE, true).await + start_custom_provider( + authorization_endpoint, + SCOPE, + synthetic_callback_tokens(true), + ) + .await +} + +#[derive(Clone, Copy, Debug, serde::Deserialize, Eq, Ord, PartialEq, PartialOrd)] +#[serde(rename_all = "kebab-case")] +pub enum Callback { + Bound, + ForeignIssuer, + MissingNonce, + WrongNonce, + WrongAudience, + DevelopmentMarked, +} + +pub async fn start_callback_corpus_provider( + signer: Arc, + fixture: registry_platform_testing::TokenFixture, + callback: Callback, +) -> NarrowScopeProvider { + use registry_platform_testing::{BindTarget, Binding, ClaimValue}; + + let tokens = CallbackTokens { + jwks: signer.public_key_set(), + issue: Box::new(move |issuer, pending| { + let mut projected = fixture.clone(); + // The test issues the provider's claim shape for the actual + // callback client and the pending browser exchange. + let expected_audience = if callback == Callback::WrongAudience { + "other-browser-client" + } else { + CLIENT_ID + }; + projected + .claims + .insert("aud".to_owned(), ClaimValue::Bind(BindTarget::Audience)); + if let Some(azp) = projected.claims.get_mut("azp") { + *azp = ClaimValue::Literal(json!(CLIENT_ID)); + } + if callback != Callback::ForeignIssuer { + projected + .claims + .insert("iss".to_owned(), ClaimValue::Bind(BindTarget::Issuer)); + } + projected.claims.remove("nonce"); + match callback { + Callback::MissingNonce => {} + Callback::WrongNonce => { + projected.claims.insert( + "nonce".to_owned(), + ClaimValue::Literal(json!("other-callback-nonce")), + ); + } + _ => { + let nonce = pending.nonce.expect("the page requested a nonce"); + projected + .claims + .insert("nonce".to_owned(), ClaimValue::Literal(json!(nonce))); + } + } + if callback == Callback::DevelopmentMarked { + projected.claims.insert( + "registry_posture".to_owned(), + ClaimValue::Literal(json!(registry_platform_config::DEVELOPMENT)), + ); + } + signer + .sign( + &projected, + &Binding { + issuer: issuer.to_owned(), + audience: expected_audience.to_owned(), + }, + ) + .expect("sign local callback fixture") + .expose() + .to_owned() + }), + }; + start_custom_provider(Some("https://issuer.example/authorize"), SCOPE, tokens).await } async fn start_custom_provider( authorization_endpoint: Option<&str>, scope: &'static str, - development_id_token: bool, + tokens: CallbackTokens, ) -> NarrowScopeProvider { - let (signing_key, _) = fixtures::ed25519_pair(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let issuer = format!("http://{address}"); @@ -904,11 +993,10 @@ async fn start_custom_provider( issuer: issuer.clone(), authorization_endpoint: authorization_endpoint .map_or_else(|| format!("{issuer}/authorize"), str::to_owned), - signing_key, + tokens, codes: Arc::clone(&codes), token_calls: Arc::clone(&token_calls), scope, - development_id_token, }); let app = Router::new() .route( @@ -943,11 +1031,7 @@ async fn narrow_scope_metadata(State(state): State>) -> Re } async fn narrow_scope_jwks(State(state): State>) -> Response { - json_response( - StatusCode::OK, - ®istry_platform_testing::jwks_from_private_jwk(&state.signing_key), - &[], - ) + json_response(StatusCode::OK, &state.tokens.jwks, &[]) } async fn narrow_scope_authorize( @@ -1007,30 +1091,7 @@ async fn narrow_scope_token(State(state): State>, body: By &[], ); }; - let now = narrow_scope_unix_now(); - let expires_at = now + 300; - let mut id_claims = serde_json::Map::new(); - id_claims.insert("iss".to_owned(), json!(state.issuer)); - id_claims.insert("sub".to_owned(), json!(pending.subject)); - id_claims.insert("aud".to_owned(), json!(CLIENT_ID)); - id_claims.insert("azp".to_owned(), json!(CLIENT_ID)); - id_claims.insert("exp".to_owned(), json!(expires_at)); - id_claims.insert("iat".to_owned(), json!(now)); - if let Some(nonce) = &pending.nonce { - id_claims.insert("nonce".to_owned(), json!(nonce)); - } - if state.development_id_token { - id_claims.insert( - "registry_posture".to_owned(), - json!(registry_platform_config::DEVELOPMENT), - ); - } - let id_token = registry_platform_testing::sign_ed25519_compact_jwt_with_key( - &state.signing_key, - "JWT", - "registry-platform-testing-ed25519-1", - Value::Object(id_claims), - ); + let id_token = (state.tokens.issue)(&state.issuer, pending); json_response( StatusCode::OK, &json!({ @@ -1044,6 +1105,39 @@ async fn narrow_scope_token(State(state): State>, body: By ) } +fn synthetic_callback_tokens(development: bool) -> CallbackTokens { + let (signing_key, _) = fixtures::ed25519_pair(); + CallbackTokens { + jwks: registry_platform_testing::jwks_from_private_jwk(&signing_key), + issue: Box::new(move |issuer, pending| { + let now = narrow_scope_unix_now(); + let expires_at = now + 300; + let mut id_claims = serde_json::Map::new(); + id_claims.insert("iss".to_owned(), json!(issuer)); + id_claims.insert("sub".to_owned(), json!(pending.subject)); + id_claims.insert("aud".to_owned(), json!(CLIENT_ID)); + id_claims.insert("azp".to_owned(), json!(CLIENT_ID)); + id_claims.insert("exp".to_owned(), json!(expires_at)); + id_claims.insert("iat".to_owned(), json!(now)); + if let Some(nonce) = &pending.nonce { + id_claims.insert("nonce".to_owned(), json!(nonce)); + } + if development { + id_claims.insert( + "registry_posture".to_owned(), + json!(registry_platform_config::DEVELOPMENT), + ); + } + registry_platform_testing::sign_ed25519_compact_jwt_with_key( + &signing_key, + "JWT", + "registry-platform-testing-ed25519-1", + Value::Object(id_claims), + ) + }), + } +} + pub struct Options { pub token_lifetime: Duration, /// Top-level blocks appended to the runtime document, such as `rateLimits`. diff --git a/crates/registry-coordinator/src/access/token_characterisation.rs b/crates/registry-coordinator/src/access/token_characterisation.rs index 8773788073..94bc03bcf8 100644 --- a/crates/registry-coordinator/src/access/token_characterisation.rs +++ b/crates/registry-coordinator/src/access/token_characterisation.rs @@ -15,8 +15,8 @@ use registry_platform_config::{DeclaredPosture, Posture, PostureSource}; use registry_platform_oidc::ActorKind; use registry_platform_testing::{ assert_token_refusal, golden_with_request_trace, request_token_route, Binding, ClaimValue, - Configuration, FixtureCase, FixtureClass, Observation, Outcome, Stage, TokenCorpus, - TokenFixture, TokenSigner, + Configuration, FixtureCase, FixtureClass, Observation, Outcome, RowConfiguration, Stage, + TokenCorpus, TokenFixture, TokenSigner, }; use serde_json::json; use serde_json::Value; @@ -394,6 +394,27 @@ async fn caller_authentication_matches_the_token_corpus() { ) .await .expect("the corpus runs"); + for (fixture, stage) in [ + ("thunderid-id-token", Stage::Audience), + ("keycloak-id-token", Stage::Audience), + ("supabase-id-token", Stage::Audience), + ("entra-id-token", Stage::TokenType), + ] { + let row = report + .rows + .iter() + .find(|row| { + row.fixture == fixture + && row.against == registry_platform_testing::Against::PlainRead + && row.configuration == RowConfiguration::JwtAccepted + }) + .expect("each ID-token refusal has a JWT-accepted row"); + assert_eq!( + row.observed, + Some(Outcome::Refused(stage)), + "{posture:?} / {fixture}" + ); + } report.print_counts(posture); reports.push(report); } diff --git a/products/platform/conformance/tokens/README.md b/products/platform/conformance/tokens/README.md index c69844bd00..7d9f10402e 100644 --- a/products/platform/conformance/tokens/README.md +++ b/products/platform/conformance/tokens/README.md @@ -9,7 +9,8 @@ A fixture is data. The test loader signs it in memory when a test runs. Each con | Path | Content | | --- | --- | | `fixtures/.json` | One decoded token shape per file. | -| `expected.yaml` | The expected result for each fixture, product and configuration. | +| `expected.yaml` | The expected bearer result for each fixture, product and configuration. | +| `browser-callback-expected.json` | The BReg Review callback column, using the same token shapes in the authorization-code response. | | `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. @@ -18,7 +19,7 @@ The loader, the signer and the test driver live in `crates/registry-platform-tes 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. +A **negative** bearer fixture is a token that every resource server must refuse in every corpus configuration. Examples include an ID token, a refresh token, an API key and a token from an issuer that no product trusts. Bearer admission of any negative fixture is a security defect. Report it through `SECURITY.md`. Do not open a public issue or pull request. ## Providers covered @@ -116,6 +117,17 @@ The head of `expected.yaml` lists the choices the driver makes for every row, su 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 and every row has every product, and that negative fixtures have no admission expectations. +## BReg Review sign-in callback + +The browser callback table gives BReg Review its own column in production and development. +An authorization-code response carries an ID token for the Review client. The callback verifies the token and creates a browser session. +The bearer table continues to refuse those same ID token shapes at resource servers. + +The callback test reuses the loaded corpus fixtures and binds the test issuer, the Review client audience and the pending browser nonce. +A foreign-issuer row retains the fixture's literal issuer. The fixture records use synthetic values. +The test crosses the actual callback and code redemption over loopback. +It asserts the HTML result, session cookie and terminal sign-in audit, including no cookie after a refusal. + ## Surfaces with dedicated credential tests | Surface | Credential and test that verifies it | @@ -131,7 +143,7 @@ The head of `expected.yaml` lists the choices the driver makes for every row, su | Coordinator signed webhook ingress | Signed event and correlated delivery envelope. [Event trigger tests](../../../../crates/registry-coordinator/src/event_trigger_tests.rs). | | BReg signed webhook ingress | Signed review completion bound to its recipient. [Authentication refusal goldens](../../../../crates/registry-breg/tests/authentication_refusals.rs). | | Messaging provider callbacks | Provider-configured HMAC or path token. [PostgreSQL callback tests](../../../../crates/registry-messaging/tests/postgres_callbacks.rs). | -| BReg Review browser routes | Authorization-code sign-in, callback state and browser session cookies. [Review page tests](../../../../crates/registry-breg-review/tests/review_pages.rs). | +| BReg Review browser routes | Authorization-code sign-in, callback state and browser session cookies. [Callback corpus](../../../../crates/registry-breg-review/tests/review_pages/token_characterisation.rs) and [review page tests](../../../../crates/registry-breg-review/tests/review_pages.rs). | | Registry Session browser routes | Authorization-code sign-in and host-only session cookies. [Public session tests](../../../../crates/registry-session/tests/public.rs). | | Discovery public routes | Public unauthenticated search and resolution. [HTTP journey](../../../../crates/registry-discovery/tests/http_journey.rs). | @@ -149,6 +161,7 @@ cargo test --locked -p registry-breg --features runtime --lib token_characterisa cargo test --locked -p registry-casework -p registry-documents -p registry-evidence -p registry-evidence-oid4vci -p registry-messaging -p registry-scheduling --lib token_characterisation -- --nocapture cargo test --locked -p registry-adapter -p registry-coordinator -p registry-mcp-edge -p registry-render --lib token_characterisation -- --nocapture cargo test --locked -p registry-evidence-oid4vp --lib token_characterisation -- --nocapture +cargo test --locked -p registry-breg-review --test review_pages token_characterisation -- --nocapture cargo test --locked -p registry-mcp --test serve production_and_development_refusals_preserve_status_and_posture_detail cargo test --locked -p registry-breg-mcp --test mcp_gateway production_and_development_refusals_preserve_status_and_posture_detail ``` diff --git a/products/platform/conformance/tokens/browser-callback-expected.json b/products/platform/conformance/tokens/browser-callback-expected.json new file mode 100644 index 0000000000..f14cc9b844 --- /dev/null +++ b/products/platform/conformance/tokens/browser-callback-expected.json @@ -0,0 +1,18 @@ +{ + "schema": "registry.browser-callback-expectations/v1", + "rows": [ + {"fixture": "thunderid-id-token", "callback": "bound", "breg-review": {"production": "signed-in", "development": "signed-in"}}, + {"fixture": "keycloak-id-token", "callback": "bound", "breg-review": {"production": "signed-in", "development": "signed-in"}}, + {"fixture": "supabase-id-token", "callback": "bound", "breg-review": {"production": "signed-in", "development": "signed-in"}}, + {"fixture": "entra-id-token", "callback": "bound", "breg-review": {"production": "signed-in", "development": "signed-in"}}, + {"fixture": "esignet-id-token", "callback": "foreign-issuer", "breg-review": {"production": "refused", "development": "refused"}}, + {"fixture": "esignet-standin-id-token", "callback": "foreign-issuer", "breg-review": {"production": "refused", "development": "refused"}}, + {"fixture": "thunderid-id-token", "callback": "missing-nonce", "breg-review": {"production": "refused", "development": "refused"}}, + {"fixture": "thunderid-id-token", "callback": "wrong-nonce", "breg-review": {"production": "refused", "development": "refused"}}, + {"fixture": "thunderid-id-token", "callback": "wrong-audience", "breg-review": {"production": "refused", "development": "refused"}}, + {"fixture": "thunderid-id-token", "callback": "development-marked", "breg-review": {"production": "refused", "development": "signed-in"}}, + {"fixture": "thunderid-user-access", "callback": "bound", "breg-review": {"production": "refused", "development": "refused"}}, + {"fixture": "thunderid-refresh-token", "callback": "bound", "breg-review": {"production": "refused", "development": "refused"}}, + {"fixture": "supabase-api-key-opaque", "callback": "bound", "breg-review": {"production": "refused", "development": "refused"}} + ] +} From 97484db1a82f09138414706f7dd5a532d349743b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:04:38 +0000 Subject: [PATCH 17/26] docs(auth): scope negative token fixtures to bearer admission Signed-off-by: Jeremi Joslin --- products/platform/conformance/tokens/token-fixture.schema.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/platform/conformance/tokens/token-fixture.schema.json b/products/platform/conformance/tokens/token-fixture.schema.json index 5f0f80ca88..e81c8d79ba 100644 --- a/products/platform/conformance/tokens/token-fixture.schema.json +++ b/products/platform/conformance/tokens/token-fixture.schema.json @@ -11,7 +11,7 @@ "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." + "description": "A positive fixture is one a correctly configured product can admit for a plain read. Every resource server must refuse a negative fixture for bearer admission." }, "provider": { "enum": ["keycloak", "thunderid", "entra", "supabase-auth", "esignet", "rstack-dev", "synthetic"] }, "kind": { "enum": ["user-access", "client-access", "user-id", "user-refresh", "api-key"] }, From 05cfd96faf7b899a884e24bbb5d0e734da6e820e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:58:52 +0000 Subject: [PATCH 18/26] test(breg): prove holder renewal and crossed authority refusals Signed-off-by: Jeremi Joslin --- .../holder-authorized-action/README.md | 16 +++ .../dev-journeys.yaml | 12 ++ .../holder-authorized-action/dev.yaml | 26 ++++ .../holder-authorized-action/service.yaml | 12 ++ .../holder-authorized-action/verify.sh | 119 ++++++++++++++++++ 5 files changed, 185 insertions(+) create mode 100644 products/breg/fixtures/holder-authorized-action/README.md create mode 100644 products/breg/fixtures/holder-authorized-action/dev-journeys.yaml create mode 100644 products/breg/fixtures/holder-authorized-action/dev.yaml create mode 100644 products/breg/fixtures/holder-authorized-action/service.yaml create mode 100755 products/breg/fixtures/holder-authorized-action/verify.sh diff --git a/products/breg/fixtures/holder-authorized-action/README.md b/products/breg/fixtures/holder-authorized-action/README.md new file mode 100644 index 0000000000..a1f2f47f88 --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/README.md @@ -0,0 +1,16 @@ +# Holder-authorized renewal fixture + +Pass `verify.sh` the absolute paths to matching `rstack`, `breg`, and +`bregctl` binaries with named-role support. Then pass the medical-renewal +preview's `project` directory and a new private work directory. The script +copies the preview's Record types and Actions and starts disposable PostgreSQL +with Docker. + +The fixture exercises the served BReg routes with two holders and an officer. +A holder reads a target condition, renews their own licence and retries the same +command. The other licence's condition and write remain protected. The officer's +credential is refused on the holder profile. The other holder verifies that +the refused requests leave both the expiry and target condition unchanged. + +The separate holder-functions journey proves the function input and credential +boundary. This fixture reaches BReg directly. diff --git a/products/breg/fixtures/holder-authorized-action/dev-journeys.yaml b/products/breg/fixtures/holder-authorized-action/dev-journeys.yaml new file mode 100644 index 0000000000..e1967bc4fb --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/dev-journeys.yaml @@ -0,0 +1,12 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/journeys/journeys.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 +kind: RStackJourneys +journeys: + - id: holder-profile + steps: + - id: holder-lists-licences + product: breg + as: holder + method: GET + path: /v1/records/licences + expect: {status: 200} diff --git a/products/breg/fixtures/holder-authorized-action/dev.yaml b/products/breg/fixtures/holder-authorized-action/dev.yaml new file mode 100644 index 0000000000..cb99483002 --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/dev.yaml @@ -0,0 +1,26 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/dev/dev.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 +kind: RStackDev +issuer: https://identity.licences.example.test +products: + - {product: breg, project: ., audience: "urn:example:licence-registry"} +people: + holder: + subject: 00000000-0000-4000-8000-000000000101 + client: licence-holder + roles: [licence-holder] + claims: + breg: {holder_ref: synthetic-doctor-holder} + officer: + subject: 00000000-0000-4000-8000-000000000102 + client: licence-officer + roles: [licence-officer] + claims: + breg: {jurisdiction: north} + other-holder: + subject: 00000000-0000-4000-8000-000000000103 + client: licence-holder + roles: [licence-holder] + claims: + breg: {holder_ref: synthetic-other-holder} +journeyFile: dev-journeys.yaml diff --git a/products/breg/fixtures/holder-authorized-action/service.yaml b/products/breg/fixtures/holder-authorized-action/service.yaml new file mode 100644 index 0000000000..8f1f73c816 --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/service.yaml @@ -0,0 +1,12 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/service/service.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +roles: + licence-holder: + actorKind: human + claims: [holder_ref] + accessProfiles: {breg: [licence-holder]} + licence-officer: + actorKind: human + claims: [jurisdiction] + accessProfiles: {breg: [licence-officer]} diff --git a/products/breg/fixtures/holder-authorized-action/verify.sh b/products/breg/fixtures/holder-authorized-action/verify.sh new file mode 100755 index 0000000000..36aaf51405 --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/verify.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 5 ]]; then + printf 'Usage: %s ABSOLUTE_RSTACK ABSOLUTE_BREG ABSOLUTE_BREGCTL ABSOLUTE_MEDICAL_PROJECT ABSOLUTE_NEW_WORK_DIR\n' "$0" >&2 + exit 2 +fi + +rstack="$1" +export RSTACK_BREG_BIN="$2" RSTACK_BREGCTL_BIN="$3" +donor="$4" +scratch="$5" +for path in "$rstack" "$RSTACK_BREG_BIN" "$RSTACK_BREGCTL_BIN" "$donor" "$scratch"; do + [[ "$path" = /* ]] +done +fixture="${BASH_SOURCE[0]%/*}" +mkdir -m 700 "$scratch" +cp -R "$donor" "$scratch/project" +cp "$fixture/dev.yaml" "$fixture/dev-journeys.yaml" "$fixture/service.yaml" "$scratch/project/" +unset RSTACK_DEV_DATABASE_URL RSTACK_DEV_DATABASE_CA +export RSTACK_DEV_STATE_DIR="$scratch/state" +dev=("$rstack" --install-root "$scratch/install" --format json dev) +run_id='' + +cleanup() { + if [[ -n "$run_id" ]]; then + "${dev[@]}" stop "$run_id" --clean >"$scratch/stop.json" + jq -e '.status == "stopped"' "$scratch/stop.json" >/dev/null + fi +} +trap cleanup EXIT + +"${dev[@]}" start "$scratch/project" --ttl 5m >"$scratch/start.json" +run_id="$(jq -er '.run_id' "$scratch/start.json")" +origin="$(jq -er '.products.breg' "$scratch/start.json")" +[[ "$origin" =~ ^http://127\.0\.0\.1:[0-9]+$ ]] + +credential_file() { + local actor="$1" file + file="$("${dev[@]}" token "$run_id" --as "$actor" | jq -er '.credentials[0].header_file')" || return + [[ "$file" = "$scratch/"* && -f "$file" ]] || return + printf '%s\n' "$file" +} + +holder="$(credential_file holder)" +other_holder="$(credential_file other-holder)" +officer="$(credential_file officer)" +response="$scratch/response.json" + +http() { + local credential="$1" method="$2" route="$3" expected="$4" body="${5:-}" key="${6:-}" + local status + local -a arguments=(--silent --show-error --noproxy '*' --max-time 10 --request "$method" + --header "@$credential" --output "$response" --write-out '%{http_code}') + if [[ -n "$body" ]]; then + arguments+=(--header 'Content-Type: application/json' --data "$body") + fi + if [[ -n "$key" ]]; then + arguments+=(--header "Idempotency-Key: $key") + fi + status="$(curl "${arguments[@]}" "$origin$route")" + if [[ "$status" != "$expected" ]]; then + printf 'Expected HTTP %s, received %s\n' "$expected" "$status" >&2 + jq -c '{code, status}' "$response" >&2 + return 1 + fi +} + +issue() { + local number="$1" holder_ref="$2" body + body="$(jq -cn --arg number "$number" --arg holder "$holder_ref" ' + {input:{licenceNumber:$number,holderRef:$holder,holderName:"Example Holder", + profession:"doctor",jurisdiction:"north",issuedOn:"2026-07-01",expiresOn:"2027-06-30"}} + ')" + http "$officer" POST '/v1/actions/issue?accessProfile=licence-officer' 200 "$body" "issue-$number" || return + jq -er '.results.licence.recordId' "$response" +} + +conditions() { + local credential="$1" licence="$2" expected="$3" body + body="$(jq -cn --arg id "$licence" '{input:{licenceId:$id}}')" + http "$credential" POST '/v1/actions/renew/target-conditions?accessProfile=licence-holder' "$expected" "$body" +} + +renewal() { + jq -cn --arg id "$1" --arg tag "$2" ' + {input:{licenceId:$id,newExpiresOn:"2028-06-30"},preconditions:{licenceId:{ifMatch:$tag}}} + ' +} + +own="$(issue MED-2026-001 synthetic-doctor-holder)" +foreign="$(issue MED-2026-002 synthetic-other-holder)" +[[ "$own" != "$foreign" ]] + +conditions "$holder" "$own" 200 +own_tag="$(jq -er '.preconditions.licenceId.ifMatch' "$response")" +own_body="$(renewal "$own" "$own_tag")" +renew='/v1/actions/renew?accessProfile=licence-holder' +http "$holder" POST "$renew" 200 "$own_body" renew-med-2026-001-to-2028 +http "$holder" POST "$renew" 200 "$own_body" renew-med-2026-001-to-2028 +http "$holder" GET "/v1/records/licences/$own?accessProfile=licence-holder" 200 +jq -e '.data.domainData.expiresOn == "2028-06-30"' "$response" >/dev/null + +conditions "$holder" "$foreign" 404 +jq -e '.code == "resource.not-found"' "$response" >/dev/null +conditions "$other_holder" "$foreign" 200 +foreign_tag="$(jq -er '.preconditions.licenceId.ifMatch' "$response")" +foreign_body="$(renewal "$foreign" "$foreign_tag")" +http "$holder" POST "$renew" 412 "$foreign_body" holder-crossed-record +jq -e '.code == "precondition.failed"' "$response" >/dev/null +http "$officer" POST "$renew" 403 "$foreign_body" officer-crossed-profile +jq -e '.code == "profile.not-authorized"' "$response" >/dev/null + +conditions "$other_holder" "$foreign" 200 +jq -e --arg original "$foreign_tag" '.preconditions.licenceId.ifMatch == $original' "$response" >/dev/null +http "$other_holder" GET "/v1/records/licences/$foreign?accessProfile=licence-holder" 200 +jq -e '.data.domainData.expiresOn == "2027-06-30"' "$response" >/dev/null + +printf '%s\n' 'Holder renewal and replay succeeded. Crossed target and profile refused. Foreign expiry and condition unchanged.' From b80097557f57a780ee392ca63f20ae25bae3fc1b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:59:53 +0000 Subject: [PATCH 19/26] feat(rstack): bind holder preparation to one BReg action Signed-off-by: Jeremi Joslin --- clients/typescript/holder-function.ts | 132 +++++++++ .../typescript/tests/holder-function.test.ts | 279 ++++++++++++++++++ 2 files changed, 411 insertions(+) create mode 100644 clients/typescript/holder-function.ts create mode 100644 clients/typescript/tests/holder-function.test.ts diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts new file mode 100644 index 0000000000..eb69f84a5a --- /dev/null +++ b/clients/typescript/holder-function.ts @@ -0,0 +1,132 @@ +import { RegistryError } from './core.ts' + +const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/u +const strongTag = /^"[\x21\x23-\x7e]{1,254}"$/u +const maximumRequestBytes = 32_768 +const bodyTooLarge = Symbol('body too large') + +interface HolderSubmission { + recordId: string + ifMatch: string + preparation: Preparation +} + +interface HolderCommand { + recordId: string + ifMatch: string + idempotencyKey: string + input: Input + signal: AbortSignal +} + +/** Host-owned parsing and invocation for one generated BReg Action and its fixed access profile. */ +interface HolderActionBinding { + path: string + parseSubmission: (body: unknown) => HolderSubmission | undefined + parsePreparation: (body: unknown) => Input | undefined + invoke: (credential: string, command: HolderCommand) => Promise<{ recordId: string }> +} + +function reply(body: object, status: number): Response { + return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) +} + +function parseJson(source: string): unknown { + const value: unknown = JSON.parse(source, (_key, member: unknown) => { + if (typeof member === 'number' && + (!Number.isFinite(member) || Number.isInteger(member) && !Number.isSafeInteger(member))) { + throw new SyntaxError('Unsupported JSON number.') + } + return member + }) + // On valid JSON, a quoted token followed by a colon is an object key. + // Decode the key before comparing so Unicode escapes cannot hide duplicates. + const objects: Set[] = [] + for (const [token, quoted, colon] of source.matchAll(/("(?:[^"\\]|\\.)*")(\s*:)?|[{}]/gu)) { + if (token === '{') objects.push(new Set()) + if (token === '}') objects.pop() + if (quoted && colon) { + const keys = objects.at(-1)! + const key: string = JSON.parse(quoted) + if (keys.has(key)) throw new SyntaxError('Duplicate JSON member.') + keys.add(key) + } + } + return value +} + +async function readSubmission(request: Request): Promise { + if (!request.body) return undefined + const reader = request.body.getReader() + const decoder = new TextDecoder('utf-8', { fatal: true }) + let bytes = 0 + let body = '' + try { + for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) { + bytes += chunk.value.byteLength + if (bytes > maximumRequestBytes) { + await reader.cancel() + return bodyTooLarge + } + body += decoder.decode(chunk.value, { stream: true }) + } + return parseJson(body + decoder.decode()) + } finally { + reader.releaseLock() + } +} + +/** Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. */ +export function createHolderActionHandler( + { path, parseSubmission, parsePreparation, invoke }: HolderActionBinding, + prepare: (input: Preparation) => unknown | Promise, +): (request: Request) => Promise { + if (!/^\/api\/functions\/[a-z][a-z0-9_-]{0,63}$/u.test(path)) throw new TypeError('Expected a declared function path.') + + return async request => { + const url = new URL(request.url) + if (request.method !== 'POST' || url.pathname !== path || url.search || url.hash) { + return reply({ message: 'Unknown function route.' }, 404) + } + const credential = /^Bearer ([A-Za-z0-9._-]+)$/u.exec(request.headers.get('authorization') ?? '')?.[1] + if (!credential) return reply({ message: 'Sign in to continue.' }, 401) + + const idempotencyKey = request.headers.get('idempotency-key') + const mediaType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() + if (!idempotencyKey || !uuid.test(idempotencyKey.toLowerCase()) || mediaType !== 'application/json') { + return reply({ message: 'Send a JSON request with its attempt key.' }, 400) + } + let submission: HolderSubmission | undefined + try { + const body = await readSubmission(request) + if (body === bodyTooLarge) return reply({ message: 'The request is too large.' }, 413) + if (body !== undefined) submission = parseSubmission(body) + } catch { + return reply({ message: 'Send a valid JSON request.' }, 400) + } + if (!submission || !uuid.test(submission.recordId) || !strongTag.test(submission.ifMatch)) { + return reply({ message: 'Send a record and its reviewed condition.' }, 400) + } + const { recordId, ifMatch, preparation } = submission + + let input: Input | undefined + try { + request.signal.throwIfAborted() + input = parsePreparation(await prepare(preparation)) + } catch { + return reply({ message: 'The function could not prepare the request.' }, 502) + } + if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) + + try { + const result = await invoke(credential, { recordId, ifMatch, idempotencyKey, input, signal: request.signal }) + if (result.recordId === recordId) return reply({ recordId }, 200) + } catch (error) { + if (error instanceof RegistryError && error.kind === 'refused' && !error.outcomeUnknown && + error.status !== undefined && error.status >= 400 && error.status < 500) { + return reply({ message: 'BReg refused the request.' }, error.status) + } + } + return reply({ message: 'The Action outcome is unavailable. Retry the same attempt.' }, 502) + } +} diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts new file mode 100644 index 0000000000..86abc8e5f4 --- /dev/null +++ b/clients/typescript/tests/holder-function.test.ts @@ -0,0 +1,279 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { Transport, type Operation } from '../core.ts' +import { createHolderActionHandler } from '../holder-function.ts' + +const route = '/api/functions/renew' +const licenceId = 'c137aa49-8a74-4d63-9f38-47fde38b2949' +const otherLicenceId = 'a4d5b3fe-eaf4-456e-ae33-9ef6b85fa4b2' +const reviewedExpiresOn = '2027-06-30' +const newExpiresOn = '2028-06-30' +const ifMatch = '"reviewed-revision"' +const otherIfMatch = '"other-reviewed-revision"' +const idempotencyKey = '08114403-75d2-48d3-961a-5d4fb8b19687' +const holderAuthorization = 'Bearer synthetic-holder' +const submission = { licenceId, reviewedExpiresOn, preconditions: { licenceId: { ifMatch } } } +const holder = { subject: 'person-a', holderRef: 'holder-a', actor: 'human', client: 'licence-holder', + profile: 'licence-holder', audience: 'licences' } +const identities = new Map([ + [holderAuthorization, holder], + ['Bearer synthetic-other-subject', { ...holder, subject: 'person-b', holderRef: 'holder-b' }], + ['Bearer synthetic-agent', { ...holder, actor: 'agent' }], + ['Bearer synthetic-officer', { ...holder, profile: 'licence-officer' }], + ['Bearer synthetic-other-client', { ...holder, client: 'other' }], + ['Bearer synthetic-other-audience', { ...holder, audience: 'other' }], +]) +const records = new Map([[licenceId, { holderRef: 'holder-a', ifMatch }], + [otherLicenceId, { holderRef: 'holder-b', ifMatch: otherIfMatch }]]) +const otherSubmission = { ...submission, licenceId: otherLicenceId, preconditions: { licenceId: { ifMatch: otherIfMatch } } } + +const renewal: Operation = { + method: 'POST', path: '/v1/actions/renew', product: 'breg', + accessProfileParameter: true, accessProfileRequired: true, + keyed: true, mutating: true, requestMediaType: 'application/json', + problemValidators: { default: value => exactObject(value, ['code', 'detail', 'status']) }, + responses: { 200: [{ mode: 'json', mediaType: 'application/json' }] }, +} + +function exactObject(value: unknown, keys: readonly string[]): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)) +} + +function parseSubmission(value: unknown) { + if (!exactObject(value, ['licenceId', 'reviewedExpiresOn', 'preconditions']) || + typeof value.licenceId !== 'string' || typeof value.reviewedExpiresOn !== 'string' || + !exactObject(value.preconditions, ['licenceId']) || !exactObject(value.preconditions.licenceId, ['ifMatch']) || + typeof value.preconditions.licenceId.ifMatch !== 'string') return undefined + return { + recordId: value.licenceId, ifMatch: value.preconditions.licenceId.ifMatch, + preparation: { reviewedExpiresOn: value.reviewedExpiresOn }, + } +} + +function parsePreparation(value: unknown) { + if (!exactObject(value, ['newExpiresOn']) || typeof value.newExpiresOn !== 'string') return undefined + return { newExpiresOn: value.newExpiresOn } +} + +function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string } = {}) { + const { path = route, authorization = holderAuthorization, body = submission, key = idempotencyKey } = options + const headers = new Headers({ + 'Content-Type': 'application/json', 'Idempotency-Key': key, + 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', + }) + if (authorization !== null) headers.set('Authorization', authorization) + return new Request('https://service.test' + path, { method: 'POST', headers, body: JSON.stringify(body) }) +} + +function prepareRenewal({ reviewedExpiresOn }: { reviewedExpiresOn: string }) { + const year = Number(reviewedExpiresOn.slice(0, 4)) + return { newExpiresOn: String(year + 1) + reviewedExpiresOn.slice(4) } +} + +function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prepareRenewal, + { loseFirstReceipt = false, parse = parseSubmission, receiptRecordId = '' } = {}, +) { + const preparations: unknown[][] = [] + const calls: { url: string; method: string | undefined; headers: Record; body: unknown }[] = [] + const writes: string[] = [] + const committed = new Map() + + const fetchProduct: typeof fetch = async (target, options) => { + const url = new URL(String(target)) + const headers = new Headers(options?.headers) + const body = JSON.parse(String(options?.body)) + calls.push({ url: url.href, method: options?.method, headers: Object.fromEntries(headers), body }) + if (url.pathname !== renewal.path || options?.method !== 'POST' || url.searchParams.get('accessProfile') !== 'licence-holder') { + throw new Error('The caller changed the checked Action contract.') + } + const refuse = (status: number, code = 'synthetic.refusal') => Response.json({ status, code, detail: 'product-only detail' }, + { status, headers: { 'Content-Type': 'application/problem+json' } }) + const identity = identities.get(headers.get('authorization') ?? '') + if (!identity || identity.audience !== 'licences') return refuse(401) + if (identity.actor !== 'human' || identity.client !== 'licence-holder' || identity.profile !== 'licence-holder') return refuse(403) + const record = records.get(body.input.licenceId) + if (record?.holderRef !== identity.holderRef || body.preconditions.licenceId.ifMatch !== record.ifMatch) return refuse(412) + if (body.input.newExpiresOn !== newExpiresOn) return refuse(412, 'synthetic.guard') + const receiptKey = identity.subject + ':' + headers.get('idempotency-key') + const command = JSON.stringify(body) + if (committed.has(receiptKey)) { + if (committed.get(receiptKey) !== command) return refuse(409) + return Response.json({ recordId: body.input.licenceId }) + } + committed.set(receiptKey, command) + writes.push(body.input.licenceId) + if (loseFirstReceipt && writes.length === 1) throw new Error('Simulated lost product receipt') + return Response.json({ recordId: receiptRecordId || body.input.licenceId, detail: 'product-only detail' }) + } + + const handle = createHolderActionHandler({ + path: route, + parseSubmission: parse, + parsePreparation, + async invoke(credential, command) { + const { recordId, ifMatch, input, idempotencyKey, signal } = command + const client = new Transport({ baseUrl: 'https://licences.test', token: () => credential, fetch: fetchProduct }) + const { data } = await client.call<{ recordId: string }>(renewal, { + query: { accessProfile: 'licence-holder' }, + body: { input: { licenceId: recordId, newExpiresOn: input.newExpiresOn }, preconditions: { licenceId: { ifMatch } } }, + idempotencyKey, + signal, + }) + return data + }, + }, (...args) => { + preparations.push(args) + return prepare(...args) + }) + return { handle, preparations, calls, writes } +} + +test('preparation receives one projected value and the checked Action receives the holder command', async () => { + const { handle, preparations, calls, writes } = setup() + const result = await handle(request()) + assert.equal(result.status, 200) + assert.deepEqual(await result.json(), { recordId: licenceId }) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.equal(calls.length, 1) + const call = calls[0]! + assert.equal(call.url, 'https://licences.test/v1/actions/renew?accessProfile=licence-holder') + assert.equal(call.method, 'POST') + assert.equal(call.headers.authorization, holderAuthorization) + assert.equal(call.headers['idempotency-key'], idempotencyKey) + for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) + assert.deepEqual(call.body, { input: { licenceId, newExpiresOn }, preconditions: { licenceId: { ifMatch } } }) + assert.deepEqual(writes, [licenceId]) +}) + +test('a missing caller or request outside the declared binding never reaches preparation or BReg', async () => { + const { handle, preparations, calls } = setup() + const cases = [ + [request({ authorization: null }), 401], + [request({ path: route + '/other' }), 404], + [request({ path: route + '?accessProfile=licence-officer' }), 404], + [request({ path: '/api/functions/issue' }), 404], + [request({ body: { ...submission, action: 'issue' } }), 400], + [request({ body: { ...submission, product: 'other' } }), 400], + [request({ body: { ...submission, accessProfile: 'licence-officer' } }), 400], + [request({ body: { ...submission, subject: 'other' } }), 400], + [request({ body: { ...submission, licenceId: licenceId.toUpperCase() } }), 400], + [request({ key: 'wrong' }), 400], + ] as const + for (const [incoming, expected] of cases) assert.equal((await handle(incoming)).status, expected) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('a preparation result outside its projection cannot substitute the target or invoke BReg', async () => { + const { handle, preparations, calls } = setup(() => ({ newExpiresOn, licenceId: otherLicenceId })) + assert.equal((await handle(request())).status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.deepEqual(calls, []) +}) + +test('a throwing submission parser returns a fixed refusal before preparation or BReg', async () => { + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { throw new Error('submitted values excluded from the reply') }, + }) + const response = await handle(request()) + assert.equal(response.status, 400) + assert.doesNotMatch(await response.text(), /submitted values/u) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('absent and oversized bodies are refused before the submission parser', async () => { + let parsed = 0 + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { parsed++; return parseSubmission(submission) }, + }) + const { url, headers, method } = request() + assert.equal((await handle(new Request(url, { headers, method }))).status, 400) + assert.equal((await handle(request({ body: 'x'.repeat(32_768) }))).status, 413) + assert.equal(parsed, 0) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('ambiguous request JSON is refused before the submission parser', async () => { + let parsed = 0 + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { parsed++; return parseSubmission(submission) }, + }) + const { url, headers, method } = request() + const cases = [ + '{"preconditions":{"licenceId":{"ifMatch":"a","ifM\\u0061tch":"b"}}}', + '{"input":9007199254740993}', + ] + for (const body of cases) assert.equal((await handle(new Request(url, { headers, method, body }))).status, 400) + assert.equal(parsed, 0) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('the owning product refuses a wrong subject, actor, role, client, audience, target, or condition', async () => { + const { handle, calls, writes } = setup() + const refusals = [ + [request({ authorization: 'Bearer synthetic-other-subject' }), 412], + [request({ authorization: 'Bearer synthetic-agent' }), 403], + [request({ authorization: 'Bearer synthetic-officer' }), 403], + [request({ authorization: 'Bearer synthetic-other-client' }), 403], + [request({ authorization: 'Bearer synthetic-other-audience' }), 401], + [request({ body: otherSubmission }), 412], + [request({ authorization: 'Bearer synthetic-other-subject', body: { ...submission, licenceId: otherLicenceId } }), 412], + [request({ body: { ...submission, preconditions: { licenceId: { ifMatch: '"stale-revision"' } } } }), 412], + ] as const + for (const [incoming, expected] of refusals) { + const response = await handle(incoming) + assert.equal(response.status, expected) + assert.doesNotMatch(await response.text(), /product-only detail|synthetic/u) + } + assert.equal(calls.length, refusals.length) + assert.deepEqual(writes, []) +}) + +test('overlapping requests keep each captured holder and exact target together', async () => { + const { handle, calls, writes } = setup() + const [first, second] = await Promise.all([ + handle(request()), + handle(request({ authorization: 'Bearer synthetic-other-subject', body: otherSubmission })), + ]) + assert.deepEqual([first.status, second.status], [200, 200]) + assert.deepEqual(await first.json(), { recordId: licenceId }) + assert.deepEqual(await second.json(), { recordId: otherLicenceId }) + assert.deepEqual(calls.map(call => call.headers.authorization).sort(), + [holderAuthorization, 'Bearer synthetic-other-subject'].sort()) + assert.deepEqual(writes.sort(), [licenceId, otherLicenceId].sort()) +}) + +test('a product refusal of the prepared value stays a refusal', async () => { + const { handle, calls, writes } = setup(() => ({ newExpiresOn: '2031-07-01' })) + const response = await handle(request()) + assert.equal(response.status, 412) + assert.deepEqual(await response.json(), { message: 'BReg refused the request.' }) + assert.equal(calls.length, 1) + assert.deepEqual(writes, []) +}) + +test('a product receipt for a different record leaves the original attempt unconfirmed', async () => { + const { handle, calls } = setup(prepareRenewal, { receiptRecordId: otherLicenceId }) + const response = await handle(request()) + assert.equal(response.status, 502) + assert.doesNotMatch(await response.text(), new RegExp(otherLicenceId, 'u')) + assert.equal(calls.length, 1) +}) + +test('after a lost product receipt the same renewal prepares the same command and reads back one effect', async () => { + const { handle, calls, preparations, writes } = setup(prepareRenewal, { loseFirstReceipt: true }) + const first = await handle(request()) + assert.equal(first.status, 502) + assert.doesNotMatch(await first.text(), /Simulated/u) + const retry = await handle(request()) + assert.equal(retry.status, 200) + assert.deepEqual(await retry.json(), { recordId: licenceId }) + assert.equal(calls.length, 2) + assert.deepEqual(calls[0], calls[1]) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }], [{ reviewedExpiresOn }]]) + assert.deepEqual(writes, [licenceId]) +}) From e76fb73ec085123a0ba742be9606748047fdb5a6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 20:08:55 +0000 Subject: [PATCH 20/26] test(breg): bind the public check to its release fixtures Signed-off-by: Jeremi Joslin --- products/breg/evidence/README.md | 3 +- .../public-check/breg-journeys-v0.49.0.yaml | 86 +++++++++++++++++++ .../evidence/public-check/dev-v0.49.0.yaml | 32 +++++++ .../breg/evidence/tests/verify-composition.py | 4 + 4 files changed, 124 insertions(+), 1 deletion(-) create mode 100644 products/breg/evidence/public-check/breg-journeys-v0.49.0.yaml create mode 100644 products/breg/evidence/public-check/dev-v0.49.0.yaml diff --git a/products/breg/evidence/README.md b/products/breg/evidence/README.md index 613d04fe98..0aa46c7249 100644 --- a/products/breg/evidence/README.md +++ b/products/breg/evidence/README.md @@ -99,7 +99,8 @@ For the served synthetic licence check, give the same runner matching released v0.49.0 binaries for all five options, including `--breg` and `--rstack`. It starts a disposable BReg and Evidence run with Docker, compares two native exports to the pinned inventory in `public-check/bregctl-v0.49.0.SHA256SUMS`, -and calls the public route on loopback. The run exercises a valid licence, a +and calls the public route on loopback. The served run also uses the Dev plan +and BReg test journeys pinned for that release in `public-check/`. The run exercises a valid licence, a missing request member, a wrong code, a record issued without a code, and an absent record. Use `--work-dir` to retain the generated authoring artifacts. diff --git a/products/breg/evidence/public-check/breg-journeys-v0.49.0.yaml b/products/breg/evidence/public-check/breg-journeys-v0.49.0.yaml new file mode 100644 index 0000000000..cbb0d197ae --- /dev/null +++ b/products/breg/evidence/public-check/breg-journeys-v0.49.0.yaml @@ -0,0 +1,86 @@ +apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +# Journeys rehearse the native request schema, so every field appears under the +# identifier registry.yaml declares. `registration-number` also declares +# `apiName: registrationNumber`, the property name the HTTP API uses and the one +# the seed records in ../dev/scenarios.yaml carry. +journeys: +- id: source-lookup-boundary + steps: + - id: operator-creates-record + recordType: record + accessProfile: operator + claims: + principal: generic-registry-operator + purpose: registry-operations + scopes: + - registry:generic:operate + request: + type: create + data: + code: SYNTHETIC-JOURNEY + registration-number: SYNTHETIC-JOURNEY-REG + status: active + label: SYNTHETIC-PRIVATE-LABEL + expect: + outcome: success + status: 201 + fields: + code: SYNTHETIC-JOURNEY + status: active + capture: record + - id: source-looks-up-by-code + recordType: record + accessProfile: evidence-source + claims: + principal: evidence-source + purpose: evidence-source-read + scopes: + - registry:evidence:lookup + request: + type: lookup + selector: by-code + values: + code: SYNTHETIC-JOURNEY + expect: + outcome: success + status: 200 + fields: + code: SYNTHETIC-JOURNEY + status: active + - id: source-looks-up-by-registration-number + recordType: record + accessProfile: evidence-source + claims: + principal: evidence-source + purpose: evidence-source-read + scopes: + - registry:evidence:lookup + request: + type: lookup + selector: by-registration-number + values: + registration-number: SYNTHETIC-JOURNEY-REG + expect: + outcome: success + status: 200 + fields: + registration-number: SYNTHETIC-JOURNEY-REG + status: active + - id: source-unresolved-is-not-a-negative-status + recordType: record + accessProfile: evidence-source + claims: + principal: evidence-source + purpose: evidence-source-read + scopes: + - registry:evidence:lookup + request: + type: lookup + selector: by-code + values: + code: SYNTHETIC-NOT-REGISTERED + expect: + outcome: refusal + status: 404 + problemCode: lookup.unresolved diff --git a/products/breg/evidence/public-check/dev-v0.49.0.yaml b/products/breg/evidence/public-check/dev-v0.49.0.yaml new file mode 100644 index 0000000000..d7aaeb0c08 --- /dev/null +++ b/products/breg/evidence/public-check/dev-v0.49.0.yaml @@ -0,0 +1,32 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/dev/dev.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 +kind: RStackDev +issuer: https://identity.evidence.example.test +products: + - product: breg + project: . + audience: urn:example:evidence-registry +people: + operator: + subject: generic-registry-operator + client: operator + grants: + breg: + profile: operator + scopes: + - registry:generic:operate + claims: + registry_purpose: registry-operations + registry_actor_kind: service + source: + subject: evidence-source + client: source + grants: + breg: + profile: evidence-source + scopes: + - registry:evidence:lookup + claims: + registry_purpose: evidence-source-read + registry_actor_kind: service +journeyFile: dev-journeys.yaml diff --git a/products/breg/evidence/tests/verify-composition.py b/products/breg/evidence/tests/verify-composition.py index b2f040d3c4..7167397bc2 100644 --- a/products/breg/evidence/tests/verify-composition.py +++ b/products/breg/evidence/tests/verify-composition.py @@ -351,6 +351,10 @@ def verify_live_public_check(workspace: Path, binaries: dict[str, Path]) -> dict } registry = workspace / "licence-registry" public_check_registry(registry) + # Keep release-specific fixture authoring paired with the checked binaries. + version = versions["rstack"] + shutil.copyfile(PUBLIC_CHECK / f"dev-v{version}.yaml", registry / "dev.yaml") + shutil.copyfile(PUBLIC_CHECK / f"breg-journeys-v{version}.yaml", registry / "tests/journeys.yaml") journey_path = registry / "dev-journeys.yaml" journey = read(journey_path) active, no_code, _ = journey["journeys"][0]["steps"] From 05f2f3362bbd6dc8d27995344f834c2a441f71e9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:04:07 +0000 Subject: [PATCH 21/26] test(docs): classify the bregctl report schema among BReg tool schemas The completed identity facts report schema sits beside the BReg tool schemas but is an output an adopter reads, not configuration they write. Name it as a report schema so the inventory check still requires every other committed tool schema to be a documented contract. Signed-off-by: Jeremi Joslin --- docs/site/scripts/generate-breg-configuration.test.mjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/site/scripts/generate-breg-configuration.test.mjs b/docs/site/scripts/generate-breg-configuration.test.mjs index dcc80f4d31..60e0ede0fd 100644 --- a/docs/site/scripts/generate-breg-configuration.test.mjs +++ b/docs/site/scripts/generate-breg-configuration.test.mjs @@ -59,10 +59,13 @@ test('BReg reference includes module extensions, hook conditions, and runtime de test('BReg covers every committed tool schema, in the order an adopter meets the files', async () => { const committed = async (directory) => (await readdir(new URL(`../../../${directory}/`, import.meta.url))) .map((name) => `${directory}/${name}`); + // Report formats bregctl writes. An adopter reads them and never authors one, so the + // configuration reference leaves them out; every other tool schema must be a contract. + const reportSchemas = ['products/breg/generated/tools/ctl-report.v1alpha1.schema.json']; assert.deepEqual([ ...await committed('products/breg/generated/tools'), ...await committed('products/platform/generated/dev'), - ].sort(), TOOL_CONTRACTS.map((entry) => entry.file).sort()); + ].sort(), [...TOOL_CONTRACTS.map((entry) => entry.file), ...reportSchemas].sort()); assert.deepEqual(TOOL_CONTRACTS.map((entry) => entry.id), ['rstack-dev', 'rstack-service', 'rstack-journeys', 'example-scenarios', 'journeys', 'schema-test-credentials', 'migration-descriptor', 'backup-binding', 'model-selection']); }); From 889775d2f34ced1e57db888d6c7fdab912f65ce0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:11:08 +0000 Subject: [PATCH 22/26] test(rstack): name the holder test attempt without a secret keyword The secret scan's generic API key rule read the fixed attempt UUID, assigned to a constant named after the idempotency key, as a credential. It is a synthetic attempt identifier, so name it for what it is instead of widening the scan allowlist. Signed-off-by: Jeremi Joslin --- clients/typescript/tests/holder-function.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts index 86abc8e5f4..ca598b6139 100644 --- a/clients/typescript/tests/holder-function.test.ts +++ b/clients/typescript/tests/holder-function.test.ts @@ -10,7 +10,7 @@ const reviewedExpiresOn = '2027-06-30' const newExpiresOn = '2028-06-30' const ifMatch = '"reviewed-revision"' const otherIfMatch = '"other-reviewed-revision"' -const idempotencyKey = '08114403-75d2-48d3-961a-5d4fb8b19687' +const attemptId = '08114403-75d2-48d3-961a-5d4fb8b19687' const holderAuthorization = 'Bearer synthetic-holder' const submission = { licenceId, reviewedExpiresOn, preconditions: { licenceId: { ifMatch } } } const holder = { subject: 'person-a', holderRef: 'holder-a', actor: 'human', client: 'licence-holder', @@ -57,7 +57,7 @@ function parsePreparation(value: unknown) { } function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string } = {}) { - const { path = route, authorization = holderAuthorization, body = submission, key = idempotencyKey } = options + const { path = route, authorization = holderAuthorization, body = submission, key = attemptId } = options const headers = new Headers({ 'Content-Type': 'application/json', 'Idempotency-Key': key, 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', @@ -140,7 +140,7 @@ test('preparation receives one projected value and the checked Action receives t assert.equal(call.url, 'https://licences.test/v1/actions/renew?accessProfile=licence-holder') assert.equal(call.method, 'POST') assert.equal(call.headers.authorization, holderAuthorization) - assert.equal(call.headers['idempotency-key'], idempotencyKey) + assert.equal(call.headers['idempotency-key'], attemptId) for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) assert.deepEqual(call.body, { input: { licenceId, newExpiresOn }, preconditions: { licenceId: { ifMatch } } }) assert.deepEqual(writes, [licenceId]) From a5c2e9dc4522be6636984229bc03bf2380da507e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 01:17:14 +0000 Subject: [PATCH 23/26] chore(identifiers): catalog the completed BReg identity facts report schema The report schema joined the BReg v1alpha1 tool schemas without a regenerated catalog, so the reference closure refused its identifier. Regenerated with products/identifiers/scripts/generate.py --write. Signed-off-by: Jeremi Joslin --- .../identifiers/generated/catalog.v1.json | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 23eec07fc8..ad5294efad 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5533,7 +5533,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/backup-binding.v1alpha1.schema.json", @@ -5541,6 +5541,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "breg", + "title": "Completed BReg identity facts command report", + "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", + "source": { + "path": "crates/registry-bregctl/src/tool_schema.rs", + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" + }, + "artifact": { + "path": "products/breg/generated/tools/ctl-report.v1alpha1.schema.json", + "sha256": "6513298c7020104c036804abd150c61f28d18b7b38113a489b84f67335dc40ef", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/breg/event-record-view/event-record-view.v1alpha1.schema.json", "kind": "schema", @@ -5587,7 +5605,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/example-scenarios.v1alpha1.schema.json", @@ -5605,7 +5623,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/journeys.v1.schema.json", @@ -5659,7 +5677,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/migration-descriptor.v1alpha1.schema.json", @@ -5695,7 +5713,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/model-selection.v1alpha1.schema.json", @@ -5717,7 +5735,7 @@ }, "artifact": { "path": "products/breg/generated/authoring/registry-module.schema.json", - "sha256": "543316774c84e783eda4a79f87a037ecc2c94d2df14a906feaacdd9552cfc7e0", + "sha256": "135e6f4fb68281ce84ad8a15ad87ad464d96722e37a89ad2bd697fc382bcbca9", "mediaType": "application/schema+json" } }, @@ -5735,7 +5753,7 @@ }, "artifact": { "path": "products/breg/generated/authoring/registry-project.schema.json", - "sha256": "940c6e30dadf260f209ad059d9bc21239f43fe7d3b58fdbc9f941bf91aa28822", + "sha256": "cc701340565561324fb44b9db9f65b0f08f137e4a0754ba86c19ef9502fb9c76", "mediaType": "application/schema+json" } }, @@ -5839,7 +5857,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/schema-test-credentials.v1.schema.json", From 66e7aace4b0aaa31b527c32c92391a8ef2275cb2 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 03:16:25 +0000 Subject: [PATCH 24/26] test(bregctl): hold the explain report example to current output The ctl-report registration's example is the completed identity facts report, which shares the explain report's apiVersion and kind. Read the explain example directly and keep the registration check for apiVersion and kind. Signed-off-by: Jeremi Joslin --- crates/registry-bregctl/tests/explain_contract.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/registry-bregctl/tests/explain_contract.rs b/crates/registry-bregctl/tests/explain_contract.rs index cfb95544c1..cf323b2aa7 100644 --- a/crates/registry-bregctl/tests/explain_contract.rs +++ b/crates/registry-bregctl/tests/explain_contract.rs @@ -1321,7 +1321,7 @@ fn authored_display_examples_pin_every_presentation_surface() { } #[test] -fn registered_ctl_report_example_matches_current_actions_report() { +fn ctl_report_explain_example_matches_current_actions_report() { let root = repo_root(); let registry = format_registry(&root); let registration = registry["formats"] @@ -1330,7 +1330,9 @@ fn registered_ctl_report_example_matches_current_actions_report() { .iter() .find(|format| format["id"] == "breg/ctl-report") .expect("ctl report is registered"); - let path = root.join(registration["example"].as_str().unwrap()); + // The registration's example and schema are the completed identity facts report. + // This explain report shares its apiVersion and kind and is held to current output here. + let path = root.join("products/breg/examples/formats/ctl-report.json"); let bytes = std::fs::read(&path).unwrap(); let example: Value = serde_json::from_slice(&bytes).expect("registered report parses"); assert_eq!(example["apiVersion"], registration["current"]["apiVersion"]); From dfbf773151330aeb4a1f15b6ee5d4fc69ca546ab Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 03:16:25 +0000 Subject: [PATCH 25/26] test(breg-mcp): enable token fixtures for the native citizen test The shared review test support signs tokens with TokenSigner and TokenFixture, which registry-platform-testing exposes only under token-fixtures. Signed-off-by: Jeremi Joslin --- crates/registry-breg-mcp/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/registry-breg-mcp/Cargo.toml b/crates/registry-breg-mcp/Cargo.toml index 0a0487e053..ecee2ecd7f 100644 --- a/crates/registry-breg-mcp/Cargo.toml +++ b/crates/registry-breg-mcp/Cargo.toml @@ -74,7 +74,7 @@ jsonschema.workspace = true # The composed journey test serves the citizen review page beside the gateway; # the gateway itself never links the page. registry-breg-review.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 registry-mcp-edge = { workspace = true, features = ["test-support"] } # The test client reaches the gateway over plain loopback HTTP. rmcp's From be9236d106e389143f35e43be0c0149bf841229b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 03:16:25 +0000 Subject: [PATCH 26/26] test(rstack): give the synthetic caseworkctl its complete owner report An offline dev check requires the owning tool's complete report for identity facts. The fake now prints the report real caseworkctl emits under the development posture, counting the facts it wrote. Signed-off-by: Jeremi Joslin --- crates/registry-rstack/tests/dev_run.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index ad5f858371..82fd5bcb49 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -1139,7 +1139,9 @@ fn start_with_casework_tool( } // The synthetic Casework helper projects the known reviewer profile and -// echoes the issuer and audience in the runner's facts-only input. +// echoes the issuer and audience in the runner's facts-only input. Its receipt +// is the complete owner report an offline check requires, counting the facts +// it wrote. const CASEWORK_FACTS_COMMAND: &str = concat!( r#"if [[ $3 == generate ]]; then"#, "\n", @@ -1161,7 +1163,7 @@ const CASEWORK_FACTS_COMMAND: &str = concat!( "\n", r#" printf '{"apiVersion":"id.registrystack.org/formats/platform/identity-facts/v1","kind":"PlatformIdentityFacts","product":"casework","issuer":"%s","audience":"%s","allowedClients":"unrestricted","claims":{"registry_actor_kind":"string"},"accessProfiles":[{"id":"reviewer","scopes":["casework:review"],"actorKind":"human"}]}\n' "$issuer" "$audience" >"$9""#, "\n", - r#" printf '%s\n' '{"ok":true}'"#, + r#" printf '{"ok":true,"command":"generate-identity-facts","status":"complete","apiVersion":"id.registrystack.org/formats/casework/report/v1alpha2","kind":"CaseworkReport","accessProfiles":1,"assertionIssuers":0,"claims":1,"output":"%s","product":"casework","posture":{"value":"development","source":"environment"},"diagnostics":[]}\n' "$9""#, "\n", " exit 0\n", "fi\n",